Hibernate batch delete on many-to-many table

前端 未结 1 1857
攒了一身酷
攒了一身酷 2021-01-25 18:47

yet another many-to-many Hibernate questions. I have the simplest possible many-to-many mapping as follows:

@Entity
public class Strategy implements Serializable         


        
相关标签:
1条回答
  • 2021-01-25 19:23

    First of all, your mapping is wrong. One side of the association must be the owner side, and define the mapping of the association. The other must be the inserse side, and just use the mappedBy attribute:

    @ManyToMany(fetch = FetchType.EAGER, mappedBy = "groups")
    private Set<Strategy> strategies = new HashSet<Strategy>();
    

    Second, you should really avoid EAGER fetching on a toMany association, and particularly on both sides: this will force Hibernate to load all the associated entities recursively, and has a good chance to load all the rows of both tables in memory each time you load one row.

    Now to your question:

    If you want to delete everything from both tables, you first need to make sure that the join table is empty, else some rows in one of the tables will still be referenced by a row of the join table, and it will obviosuly fail. To do that, the best option in your case is to use a SQL query to delete everything from the join table before executing the two HQL queries you already have.

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