使用hibernate / JBoss / Seam进行OneToOne映射

时间:2009-10-28 16:33:25

标签: hibernate

我想在Entity Customer和OptIn之间创建一对一的映射。 OptIn实体是可选的。 这就是外键必须在OptIn中的原因。在部署时,我得到以下错误,因为 无法找到映射:

OneToOneSecondPass.java:135

值:    otherSide = optIn,mappedBy = customer

otherSideProperty = BinderHelper.findPropertyByName(otherSide,mappedBy);

显示java.lang.NullPointerException     在org.hibernate.cfg.OneToOneSecondPass.doSecondPass(OneToOneSecondPass.java:135)     在org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1130)     在org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:296)     在org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1115)     ...

如何才能获得正确的映射?

@Entity
@Table(name = "KPS_OPT_IN", schema = "EB")
public class OptIn extends KmsEntity implements java.io.Serializable {

    private static final long serialVersionUID = -8818445355079384264L;


    private int id; /* kps_kunden_nr */

    private Customer customer;      

    public OptIn() {
    }

    @Id
    @Column(name = "KPS_KUNDEN_NR", unique = true, nullable = false)    
    public int getId() {
        return this.id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @OneToOne
    @PrimaryKeyJoinColumn(name="KPS_KUNDEN_NR", referencedColumnName="KPS_KUNDEN_NR")   
    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
        this.setId(customer.getId());
    }    
}

@Entity
@Table(name = "KPS_KUNDEN", schema = "EB")
public class Customer extends KmsEntity implements java.io.Serializable {

    private static final long serialVersionUID = 1L;

    private int id; 

    private OptIn optIn;

    public Customer() {
    }

    public Customer(int id) {
        this.id = id;
    }

    @Id
    @GeneratedValue(generator="seqkpskunde")
    @SequenceGenerator(name="seqkpskunde",sequenceName="SEQ_KPS_KUNDE") 
    @Column(name = "KPS_KUNDEN_NR", unique = true, nullable = false)
    public int getId() {
        return this.id;
    }

    public void setId(int id) {
        this.id = id;
        if(optIn!=null){
            optIn.setId(id);
        }
    }

    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "customer")
    public OptIn getOptIn() {
        return optIn;
    }

    public void setOptIn(OptIn optIn) {
        this.optIn = optIn;
    }
}

1 个答案:

答案 0 :(得分:2)

我不确定你的意思是“外键必须在OptIn中”。您已通过@OneToOne映射了@PrimaryKeyJoinColumn关联,这意味着您的实体将通过其ID值进行关联。它还意味着:

  1. 您无法在@PrimaryKeyJoinColumn注释中指定列名称;它们将取自两个实体的相应@Id列。
  2. 将抓取标记为LAZY毫无意义,将被忽略;可选的@OneToOne关联始终急切地获取。
  3. 此关联的唯一方式OptIn是可选的,如果数据库中没有给定ID的条目。
  4. 您使用的是什么Hibernate / Annotations版本?如果它们相当老,那么它可能是Hibernate代码中的一个错误。但我相信如果您修复上述(1)和(2),它应该有效。