title: Hibernate/JPA - Foreign Key Index in Object itself
body: <p>I am currently working on 100+ Java Objects created by someone with no JPA/Hibernate experience into JPA Entities.  Their Objects reference other objects based on a Foreign Key in the Class itself.  All of the primary Keys are generated outside of the database.</p>
  
  <p>For Example (Just to Illustrate)</p>
  
  <p><strong>Car</strong></p>
  
  <pre><code>@Entity
  @Table(name="CAR")
  public class Car {
  
      private Integer id;
      private String name;
  
      @Id
      @Column(name="CAR_ID")
      public Integer getId() {
          return id;
      }
      public void setId(Integer id) {
          this.id = id;
      }
  
      @Column(name="CAR_NAME")
      public String getName() {
          return name;
      }
      public void setName(String name) {
          this.name = name;
      }
  
  }
  </code></pre>
  
  <p><strong>Engine</strong></p>
  
  <pre><code>@Entity
  @Table(name="ENGINE")
  public class Engine {
  
      private Integer id;
      private String name;
      private Integer carId;
  
      @Id
      @Column(name="ENGINE_ID")
      public Integer getId() {
          return id;
      }
      public void setId(Integer id) {
          this.id = id;
      }
  
      @Column(name="ENGINE_NAME")
      public String getName() {
          return name;
      }
      public void setName(String name) {
          this.name = name;
      }
  
      @Column(name="CAR_ID")
      public Integer getCarId() {
          return carId;
      }
      public void setCarId(Integer carId) {
          this.carId = carId;
      }
  
  }
  </code></pre>
  
  <p>Here is what the schema looks like:</p>
  
  <pre><code>CREATE TABLE CAR(CAR_ID INTEGER NOT NULL PRIMARY KEY,CAR_NAME VARCHAR(255))
  CREATE TABLE ENGINE(ENGINE_ID INTEGER NOT NULL PRIMARY KEY,CAR_ID INTEGER,ENGINE_NAME VARCHAR(255))
  ALTER TABLE ENGINE ADD FOREIGN KEY (CAR_ID) REFERENCES CAR(CAR_ID) ON DELETE CASCADE ON UPDATE CASCADE
  </code></pre>
  
  <p><strong>Testing Code</strong></p>
  
  <pre><code>    Car c = new Car();
      c.setId(100);
      c.setName("Dodge Intrepid");
      em.persist(c);
  
      Engine e = new Engine();
      e.setId(999);
      e.setName("V6");
      e.setCarId(c.getId());
      em.persist(e);
  
      Object entity = em.find(c.getClass(),c.getId());
      em.remove(entity);
  </code></pre>
  
  <p>So, the Car ID holds a reference to the Engine in the Database.   Losing Lazy Loading is not a big deal because we are using an TRANSACTIONAL Entity Manager.  I have tested this out and it seems to work fine.</p>
  
  <p>Are there any obvious problems with this that I am missing?  <strong>I know it does not exactly fit the JPA/Hibernate spec, but I think it works.</strong></p>