为什么@OneToMany注释不起作用

时间:2016-11-15 18:39:13

标签: hibernate jpa

我的问题:

我想将STORE_ID和BOOK_ID存储在INVENTORY表中,但为什么不在Inventory表中存储STORE_ID?我是JPA的新手,请建议我在INVENTORY表中为商店STORE_ID做些什么。

1.Book

@Entity
@Table(name="book")
public class Book implements Serializable {
    @Id
    @Column(name="book_id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;
    private String isbn;
    private String title;
    private Date publishedOn;
    private Double price;
    private int version = -1;

    @OneToOne(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="book")
    Inventory inventoryRecords = new Inventory();

2.Inventory

@Entity
@Table(name="inventory")
public class Inventory implements Serializable {
    /**
     * 
     */
    @Id
    @Column(name="INVENTORY_ID")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    @OneToOne
    @JoinColumn(name="book_id")
    private Book book;

    @OneToMany(cascade=CascadeType.ALL)
    @JoinColumn(name="STORE_ID")
    private Set<Store> stores = new HashSet<Store>();

    private Integer quantity;

3.Store

 @Entity
@Table(name="store")
public class Store implements Serializable {
    @Id
    @Column(name="STORE_ID")    
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;
    @Column(name="NickName")
    private String nickName;

4.在主要

Book b = new Book();
        b.setTitle("abc");
        b.setIsbn("abc");

    Inventory i = new Inventory();     
        i.setBook(b); 
        b.setInventoryRecords(i); 

    Store s = new Store();

        s.setNickName("yyynn6");
        i.getStores().add(s);
        entitymanager.persist(b);

    OUTPUT=
    Hibernate: insert into book (isbn, price, publishedOn, title, version) values (?, ?, ?, ?, ?)
    Hibernate: insert into inventory (book_id, quantity) values (?, ?)
    Hibernate: insert into store (NickName) values (?)

3 个答案:

答案 0 :(得分:0)

我认为你在数据库级别搞砸了。如果商店里有很多书,我会摆脱库存实体并执行此操作:

在店铺:

@OneToMany(mappedBy="store", cascade=CascadeType.ALL)
private Set<Book> books= new HashSet<Book>();

在书上:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "STORE_ID")
private Store store;

您真的需要库存表吗?

答案 1 :(得分:0)

您为关系选择了错误的列;您将Id Store实体注释为加入列,您还没有在另一方指定反向关系,我更喜欢在商店内提供INVENTORY_ID列:

在商店中:

@ManyToOne
@JoinColumn(name="INVENTORY_ID")
private Inventory inventory;

并在库存中:

@OneToMany(mappedBy="inventory",cascade=CascadeType.ALL)
@JoinColumn(name="INVENTORY_ID")
private Set<Store> inventories=new HashSet<Store>();

答案 2 :(得分:0)

Prashant你做错了映射,这就是为什么你的查询没有正确解雇和数据没有插入库存表。所以请纠正你的映射。