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.
For Example (Just to Illustrate)
Car
@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;
}
}
Engine
@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;
}
}
Here is what the schema looks like:
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
Testing 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);
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.
Are there any obvious problems with this that I am missing? I know it does not exactly fit the JPA/Hibernate spec, but I think it works.