Java 当链接实体名称不是从父实体名称派生时,如何使用OneToOne映射避免NullPointerException?
这个问题与我在这个问题上遇到的问题有关,但不完全相同: 如果我这样指定我的映射,则创建OneTONE映射似乎可以正常工作:Java 当链接实体名称不是从父实体名称派生时,如何使用OneToOne映射避免NullPointerException?,java,hibernate,nullpointerexception,one-to-one,Java,Hibernate,Nullpointerexception,One To One,这个问题与我在这个问题上遇到的问题有关,但不完全相同: 如果我这样指定我的映射,则创建OneTONE映射似乎可以正常工作: Person + PersonPartDeux | +--User 但是,如果我在OneToOne中更改辅助实体的名称,则它不起作用: Person + DersonPartDeux (note the D) | +--User 在这种情况下,我得到一个错误: java.lang.NullPointerException at org.hibe
Person + PersonPartDeux
|
+--User
但是,如果我在OneToOne
中更改辅助实体的名称,则它不起作用:
Person + DersonPartDeux (note the D)
|
+--User
在这种情况下,我得到一个错误:
java.lang.NullPointerException
at org.hibernate.cfg.OneToOneSecondPass.doSecondPass(OneToOneSecondPass.java:135)
我在本例中选择的名称非常糟糕,但我的原始代码没有那么多伪造的名称,OneToOne
映射到与原始实体完全不同的名称
我调试了Hibernate注释源代码,发现personPartDeux
作为属性正确映射(在OneToOneSecondPass.java
中),但如果实体/属性名称为dersonPartDeux
,则它不会在实体上显示为属性
此属性未映射的原因是什么?
是否有方法覆盖此行为(例如,在其中一个批注中指定联接列名或实体名)?
我正在使用Hibernate 3.2.4.sp1和Hibernate Annotations 3.2.1.GA,目前无法升级
以下是有效的代码:
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class Person implements Serializable
{
@Id
@GeneratedValue
public Long id;
@Version
public int version = 0;
public String name;
@OneToOne(cascade = CascadeType.ALL)
@PrimaryKeyJoinColumn
public PersonPartDeux personPartDeux;
}
@Entity
public class PersonPartDeux implements Serializable
{
@Id
@GeneratedValue(generator = "person-primarykey")
@GenericGenerator(
name = "person-primarykey",
strategy = "foreign",
parameters = @Parameter(name = "property", value = "person")
)
public Long id = null;
@Version
public int version = 0;
@OneToOne(optional=false, mappedBy="personPartDeux")
public Person person;
public String someText;
}
@Entity
@PrimaryKeyJoinColumn(name = "person_Id")
public class User extends Person
{
public String username;
public String password;
}
如果我替换这两个类,我会得到上面提到的NullPointerException
I:
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class Person implements Serializable
{
@Id
@GeneratedValue
public Long id;
@Version
public int version = 0;
public String name;
@OneToOne(cascade = CascadeType.ALL)
@PrimaryKeyJoinColumn
public DersonPartDeux dersonPartDeux; // Note D in entity/field name
}
@Entity
public class DersonPartDeux implements Serializable
{
@Id
@GeneratedValue(generator = "person-primarykey")
@GenericGenerator(
name = "person-primarykey",
strategy = "foreign",
parameters = @Parameter(name = "property", value = "person")
)
public Long id = null;
@Version
public int version = 0;
@OneToOne(optional=false, mappedBy="dersonPartDeux") // Note the d in the property name
public Person person;
public String someText;
}
在项目环境中,是否需要在
persistence.xml
中列出实体类?可能您忘了更改
元素的名称。我们正在使用的框架(不确定这是Hibernate功能还是Seam功能)会自动检测用@Entity
注释的所有类型,因此这不是问题所在。不过谢谢你看一看!