Search code examples
hibernateone-to-manyhibernate-mappingmany-to-one

Create a list in Hibernate


I want to create the following table:

ITEM_TABLE:

ID | TITLE | STORE1_TITLE | STORE1_PRICE | STORE2_TITLE | STORE2_PRICE

As we can see this is a list with X number of stores that should be extracted to a separate table like this:

ITEM_TABLE:

ID | TITLE

STORE_ITEM_TABLE:

ITEM_ID | STORE_TITLE | PRICE

Question: Which approach do I use to achieve this with Hibernate?

What I have tested:

@Entity
@Table(name = "ITEM_TABLE")
public class Item {
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @Column(name = "TITLE")
    private String title;

    @OneToMany(mappedBy = "STORE")
    private List<Store> stores;
}

Next:

@Entity
@Table(name = "ITEM_STORE_TABLE")
public class Store {
    
    @ManyToOne
    @JoinColumn(name="ITEM_ID", nullable=false)
    private Item item;

    @Column(name = "STORE_TITLE")
    private String title;

    @Column(name = "PRICE")
    private double price;
}

Problem with this approach is that Hibernate dose not seem to allow ITEM_STORE_TABLE to be created without an ID. I cant see any reason for it to have and ID because it is just a list belonging to the row in ITEM_TABLE and is not an actual store in that sense.

Am I on the right path? Or should I use @IdClass and use multiple keys in STORE_ITEM_TABLE (dose not feel right)? Or should I use @Embeddable to handle a list?

Any feedback are welcome!


Solution

  • Yes, you can add list to tables with @ElementCollection. But because this is slow the recommended approach is to use reference @Id as follows:

    @Entity
    @Table(name = "ITEM_STORE_TABLE")
    public class Store {
        
        @Id
        @ManyToOne
        @JoinColumn(name="ITEM_ID", nullable=false)
        private Item item;
    
        @Column(name = "STORE_TITLE")
        private String title;
    
        @Column(name = "PRICE")
        private double price;
    }