使用@Embeddable Annotation对一对多对多对一进行HIbernate

时间:2018-06-06 06:27:01

标签: java hibernate

当我尝试保存Customer对象时,异常表明它无法将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;
    }

}

1 个答案:

答案 0 :(得分:0)

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

在这些情况下,您需要手动设置ID,在您的情况下,您需要在保留之前手动设置customerId