也许有人可以澄清下面的代码有什么问题。当我在嵌入式类中创建一对一关联(它是复合主键)时,如下面的代码所示:
@Entity
public class Test {
@EmbeddedId
private TestId id;
@Embeddable
public static class TestId implements Serializable {
private static final long serialVersionUID = 1950072763330622759L;
@OneToOne(optional = false)
@JoinColumn(name = "linkedTable_id")
private LinkedTable linkedTable;
}
..........
}
我得到以下堆栈跟踪:
--------------------------------------------
Caused by: java.lang.NullPointerException
at org.hibernate.cfg.AnnotationBinder.bindOneToOne(AnnotationBinder.java:1867)
at org.hibernate.cfg.AnnotationBinder.processElementAnnotations(AnnotationBinder.java:1286)
at org.hibernate.cfg.AnnotationBinder.fillComponent(AnnotationBinder.java:1662)
at org.hibernate.cfg.AnnotationBinder.bindId(AnnotationBinder.java:1695)
at org.hibernate.cfg.AnnotationBinder.processElementAnnotations(AnnotationBinder.java:1171)
at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:706)
at org.hibernate.cfg.AnnotationConfiguration.processArtifactsOfType(AnnotationConfiguration.java:452)
at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:268)
at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1121)
at org.hibernate.ejb.Ejb3Configuration.buildMappings(Ejb3Configuration.java:1211)
at org.hibernate.ejb.EventListenerConfigurator.configure(EventListenerConfigurator.java:154)
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:847)
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:178)
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:235)
... 26 more
有趣的是,如果我将关联类型更改为多对一并且不能与一对一一起工作,上面的示例是如何工作的?
答案 0 :(得分:5)
我不知道这是可能的,但根据Hibernate Annotation参考文档,它是(这是Hibernate特定的):
2.2.3.2.1. @EmbeddedId property
(...)
虽然在JPA,Hibernate中不支持 让你放置你的联想 直接在嵌入式id组件中 (而不是必须使用
@MapsId
注释)。@Entity class Customer { @EmbeddedId CustomerId id; boolean preferredCustomer; } @Embeddable class CustomerId implements Serializable { @OneToOne @JoinColumns({ @JoinColumn(name="userfirstname_fk", referencedColumnName="firstName"), @JoinColumn(name="userlastname_fk", referencedColumnName="lastName") }) User user; String customerNumber; } @Entity class User { @EmbeddedId UserId id; Integer age; } @Embeddable class UserId implements Serializable { String firstName; String lastName; }
使用您提供的代码,以下代码段对我有用:
LinkedTable linkedTable = new LinkedTable();
linkedTable.setId(1l);
session.persist(linkedTable);
session.flush();
Test.TestId testId = new Test.TestId();
testId.setLinkedTable(linkedTable);
Test test = new Test();
test.setId(testId);
session.persist(test);
session.flush();
使用Hibernate EM 3.4.0.GA,Hibernate Annotations 3.4.0.GA和Hibernate Core 3.3.0.SP1进行测试。
如果它对您不起作用,您是否可以提供更多代码以便重现问题?