当链接的实体名称不是从父实体名称派生时,如何使用OneToOne映射避免NullPointerException?

时间:2012-10-03 21:44:15

标签: java hibernate nullpointerexception one-to-one

这个问题与我对这个问题的问题有关,但不完全相同:

How do I avoid NullPointerException with OneToOne mapping against a parent entity class?

如果我像这样指定我的映射,那么创建OneToOne映射似乎工作正常:

Person + PersonPartDeux
  |
  +--User

但是,如果我在OneToOne

中更改辅助实体的名称,则无效
Person + DersonPartDeux (note the D)
  |
  +--User

在这种情况下,我收到错误:

java.lang.NullPointerException
    at org.hibernate.cfg.OneToOneSecondPass.doSecondPass(OneToOneSecondPass.java:135)

我为此示例选择的名称非常糟糕,但我原始代码的名称较少,OneToOne映射到与原始实体完全不同的名称。

我调试了Hibernate-Annotations源代码,我发现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

@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;
}

1 个答案:

答案 0 :(得分:0)

在您的项目环境中,您是否需要列出persistence.xml中的实体类?也许您忘记更改<class>元素的名称。