首页 > 解决方案 > 使用@Embeddable Annotation 休眠一对多/多对一

问题描述

当我试图保存客户对象时,异常指出它不能将 NULL 插入 ()...

我相信异常是由于使用了@Embeddable Annotation 引起的

但是,当我明确设置 customer_id 的值时,它可以正常工作,但该值不会作为外键保存在 Customerphone 表中。

@Entity
@Table(name = "CUSTOMER")
public class Customer implements java.io.Serializable {

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "Customer")
    public Set<CustomerPhone> getCustomerPhones() {
        return this.CustomerPhones;
    }
}

@Entity
@Table(name="CUSTOMER_PHONE")
public class CustomerPhone  implements java.io.Serializable {

    private CustomerPhoneId id;

    @EmbeddedId
    @AttributeOverrides( {
        @AttributeOverride(name="customerId", column=@Column(name="CUSTOMER_ID", nullable=false, precision=22, scale=0) ), 
        @AttributeOverride(name="phoneTypeCd", column=@Column(name="PHONE_TYPE_CD", nullable=false, length=5) ) } )
    public CustomerPhoneId getId() {
        return this.id;
    }

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


    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="CUSTOMER_ID", nullable=false, insertable=false, updatable=false)
    public Customer getCustomer() {
        return this.stpCustomer;
    }

}

@Embeddable
public class CustomerPhoneId  implements java.io.Serializable {

    private BigDecimal customerId;

    @Column(name="CUSTOMER_ID", nullable=false, precision=22, scale=0)
    public BigDecimal getCustomerId() {
        return this.customerId;
    }

}

标签: javahibernate

解决方案


您的 ID 没有 Generation 架构,例如@GeneratedValue(strategy=GenerationType.AUTO).

在这些情况下,您需要手动设置 ID,在您的情况下,您需要customerId在持久化之前手动设置。


推荐阅读