当ManyToOne与OneToMany通过关系表一起使用时,持久性不起作用

时间:2018-09-07 07:58:32

标签: java hibernate many-to-one hibernate-onetomany

我有3个实体,用户,订单,商品,其映射如下:

@Entity
public class Item {
    @Id
    @Access(AccessType.PROPERTY)
    private long id; // item id predefined

    //..getters and setters
}

@Entity
public class Client {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    //...getters and setters
}

@Entity
public class Order {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(nullable = false)
    @Access(AccessType.PROPERTY)
    private Long id;

    @ManyToOne(optional = false, fetch = FetchType.LAZY, cascade = {
        CascadeType.PERSIST, CascadeType.MERGE,
        CascadeType.REFRESH, CascadeType.DETACH
    })// without removing
    //@JoinColumn(name = "client_id") - works fine
    @JoinTable(name = "client_cr_order_cr_item",
        joinColumns = @JoinColumn(name = "order_id"),
        inverseJoinColumns = @JoinColumn(name = "client_id"))
    private Client client;

    @NotEmpty
    @OneToMany(fetch = FetchType.LAZY, cascade = {
        CascadeType.PERSIST, CascadeType.MERGE,
        CascadeType.REFRESH, CascadeType.DETACH
    })// without removing
    @JoinTable(name = "client_cr_order_cr_item",
        joinColumns = @JoinColumn(name = "order_id"),
        inverseJoinColumns = @JoinColumn(name = "item_id"))
    private List<Item> items;

    //...getters and setters
}

当我坚持订购时,它失败并显示错误:

  

错误:“ item_id”列中的空值违反了非空约束

它生成这样的查询:

insert into client_cr_order_cr_item (client_id, order_id) values ()

即由于某些原因,我不填写segment_id字段。但是我不是通过第三表而是使用FK @JoinColumn(name = "client_id")来指代客户端,然后它会生成正确的查询:

insert into order_cr_item (order_id, item_id) values ()

请,您能解释一下这种行为吗?为什么客户端映射会影响项目?有什么提示可以让休眠状态将项目保留到第3个表吗?

0 个答案:

没有答案