Hibernate creating redundant many-to-many tables

前端 未结 2 918
感情败类
感情败类 2021-01-03 12:53

While developing my Spring Boot application I had to drop my database and have Hibernate generate it again with hibernate.hbm2ddl.auto=update. After that I want

相关标签:
2条回答
  • 2021-01-03 12:58

    If you use @OneToMany without @JoinColumn Hibernate creates a join table

    @OneToMany(fetch = FetchType.EAGER, targetEntity = Skill.class)
    @Cascade({CascadeType.DETACH})
    private Set<Skill> children;
    

    change it to

    @OneToMany(fetch = FetchType.EAGER)
    @Cascade({CascadeType.DETACH})
    @JoinColumn
    private Set<Skill> children;
    

    Please, don't use unnecessary mapping properties — targetEntity = Skill.class

    And I am not sure you need to use this association

    private Skill parent; 
    

    It is incorrect to associate User and Role using the @OneToMany association, because of User can have multiple roles and each role can belong to multiple users. Use @ManyToMany for such an association.

    An example of an association between User and Role

    0 讨论(0)
  • 2021-01-03 13:12

    What you have here is a bidirectional association in which both sides are owners, turning it basically to two independent associations. In a one-to-many association the owner is usually the many-to side (note the mappedBy attribute):

    OneToMany(fetch = FetchType.EAGER, targetEntity = Skill.class, mappedBy = "parent")
    @Cascade({CascadeType.DETACH})
    private Set<Skill> children;
    

    This way Hibernate will ignore one-to side when maintaining the relationship (and will not create the join table which is the default configuration for @OneToMany association without @JoinColumn).

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