hibernate one to many using a join table, and hibernate annotations

前端 未结 1 1713
遥遥无期
遥遥无期 2021-02-08 01:33

I want do a one-to-many relationship between two tables using a join table.

This is why I want to use a join table:

  • Hibernate unidirectional one to many as
相关标签:
1条回答
  • 2021-02-08 02:29

    Don't look for examples. Read the official documentation:

    @Entity
    public class Product {
    
        private String serialNumber;
        private Set<Part> parts = new HashSet<Part>();
    
        @Id
        public String getSerialNumber() { return serialNumber; }
        void setSerialNumber(String sn) { serialNumber = sn; }
    
        @OneToMany
        @JoinTable(
                name="PRODUCT_PARTS",
                joinColumns = @JoinColumn( name="PRODUCT_ID"),
                inverseJoinColumns = @JoinColumn( name="PART_ID")
        )
        public Set<Part> getParts() { return parts; }
        void setParts(Set parts) { this.parts = parts; }
    }
    
    
    @Entity
    public class Part {
       ...
    }
    

    Also, note that this is the default for unidirectional one-to-many associations. So you don't even have to provide the @JoinTable annotation if the default table and column names suit you.

    0 讨论(0)
提交回复
热议问题