Hello,
I have a huge legacy database with loads of tables which have composite keys.
To avoid creating a separate classPK for all my entity classes (of the quite huge legacy database I work with using hibernate), I came up with a (maybe crazy) idea.
Can I not use the "main" entity as IdClass as well?
Consider this:
Code:
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.Table;
@Entity
@org.hibernate.annotations.Entity(dynamicInsert = true, dynamicUpdate = true)
@Table(name = "MYTEST")
@IdClass(MyTest.class) // this is not a typo, I deliberately declare the entity as IdClass as well
public class MyTest implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private int ordernr;
@Id
private int custnr;
@Id
private int orderdate;
private int itemnr;
private Integer qty;
private String name;
private String otherString1;
// setters and getters omitted
}
Now when I run the following code:
Code:
MyTest t = new MyTest();
t.setOrdernr(2);
t.setCustnr(2);
t.setOrderdate(1234);
MyTest myTest = (MyTest) session.load(MyTest.class, t);
I get the following exceptions:
Code:
org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [mydomain.MyTest#custnr=2, ordernr=2, orderdate=1234]
org.hibernate.impl.SessionFactoryImpl$2.handleEntityNotFound(SessionFactoryImpl.java:409)
org.hibernate.proxy.AbstractLazyInitializer.checkTargetState(AbstractLazyInitializer.java:108)
org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:97)
org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:140)
org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:190)
mydomain.MyTest_$$_javassist_0.getOrderdate(MyTest_$$_javassist_0.java)
Is it at all possible what I try to do?
I have several hundred tables in the DB, the annotated hibernate pojos will be generated, nevertheless I would be glad to avoid doubling the number of classes "just" for adding the "tablePK-classes" for every entity.
Best regards,
yglodt