Hibernate5 (14) annotation mapping [6] Many-to-many intermediate table associations

Source: Internet
Author: User

In our role management system, a user can have multiple roles, one role can be given to multiple users, and obviously the user and role is a typical many-to-many relationship. or blog site, the user and the article like the record is also a many-to-many relationship, that a user can click to like more than one article, an article can give a number of user likes and so on, at this time, we often need to attach some information, such as authorization times, like time and so on. In the above two instances, can correspond to hibernate many-to-many mapping relationship two ways, in many-to-many mappings, we often use the intermediate table to establish the association relationship, but also is a two-way association, to ensure that either party add or delete, you can operate on the intermediate table to maintain the association relationship.

Let's look at the first implementation of many-to-many mappings:
Let's take a look at the wrong configuration:

/**************** User Class ***************/@Entity@Table(name ="T_user3") Public  class User {    @Id    @GeneratedValue(strategy = Generationtype.auto)PrivateInteger ID;PrivateString UserName;@ManyToMany(cascade = Cascadetype.all)Privateset<role> roles;//Ignore Get and set methods}/**************** role Class ***************/@Entity@Table(name ="T_role3") Public  class Role {    @Id    @GeneratedValue(strategy = Generationtype.auto)PrivateInteger ID;PrivateString RoleName;@ManyToMany(cascade = Cascadetype.all)PrivateSet<user> users;@Override     Public int hashcode() {Final intPrime = to;intresult =1; result = Prime * result + ((id = =NULL) ?0: Id.hashcode ()); result = Prime * result + ((RoleName = =NULL) ?0: Rolename.hashcode ());returnResult }//Ignore Get and set methods}

Here we simply set up the relationship of the two sides through the annotation manytomany, and cascade all the operations, this time, call our test method:

@Testpublicvoidtest1(){    new User();    user.setUserName("userName");    new Role();    role.setRoleName("roleName");    new HashSet<Role>();    roles.add(role);    user.setRoles(roles);//建立关联关系    session.save(user);}

Execution method, we will see data records such as

In the database, Hibernate helped us generate 4 tables, of which 2 were the intermediate tables, because both user and role were associated with the master, and would build an intermediate table on their own , through cascading inserts we will find that we add the user, Even if a role is added to the Cascade, the maintenance relationship is in the user Master's intermediate table T_user3_t_role3, so that if I try to cascade the record from the role side, because the maintenance relationship is not found in the role-placed master table T_role3_t_user3, Will cause the cascade operation to fail!
For example, we perform the following actions:

2);//获取刚刚插入的记录System.out.println(role.getUsers().size());//结果打印0,即从Role端找不到关联的Usersession.delete(role);//尝试删除操作,看能否级联删除

This is the view record

found that only the records of the role table were deleted. Of course, this deletion will fail if the database has a foreign key association, because the roles_id=2 of the intermediate table T_user3_t_role3 will be constrained

Next, we'll restore the role-side records:

Then do the following:

1);System.out.println(user.getRoles().size());//打印1session.delete(user);

We'll see the console record hibernate uses the following SQL statement:

Hibernate:delete from T_user3_t_role3 where user_id=?
Hibernate:delete from T_role3 where id=?
Hibernate:delete from T_user3 where id=?
The main point here is that if we set up cascade deletion, not only the relationship maintenance records of the intermediate table will be cleared, but also the records of the other party will be deleted. In practical applications, we often do not want to have this cascade deletion , which is like I want to remove a meaningless role, accidentally deleted the associated user, this is not the result we want, so we have to control the cascade relationship.

Let's look at a proper affinity configuration:

/******************** user Side **************/@ManyToMany@Cascade(Org.hibernate.annotations.CascadeType.SAVE_UPDATE)//Use hibernate annotations to cascade save and update@JoinTable(name ="T_user_role", Joincolumns = {@JoinColumn(name ="user_id")},//joincolumns defining the primary key mappings for this party in the intermediate tableInversejoincolumns = {@JoinColumn(name ="role_id")})//inversejoincolumns defining another primary key mapping in the intermediate tablePrivateset<role> roles;/******************** Role Party **************/@ManyToMany@Cascade(Org.hibernate.annotations.CascadeType.SAVE_UPDATE)//Use hibernate annotations to cascade save and update@JoinTable(name ="T_user_role", Joincolumns = {@JoinColumn(name ="role_id")},//joincolumns defining the primary key mappings for this party in the intermediate tableInversejoincolumns = {@JoinColumn(name ="user_id")})//inversejoincolumns defining another primary key mapping in the intermediate tablePrivateSet<user> users;

Here, we set both sides as the main control, so that both sides can maintain the correlation relationship. If we only need the user side to maintain the correlation, we can change the role to the following configuration:

@ManyToMany"roles")@Cascade(org.hibernate.annotations.CascadeType.SAVE_UPDATE)//使用hibernate注解级联保存和更新private Set<User> users;

Above is the first to establish a many-to-many relationship, but the disadvantage of this configuration is that we do not know the context of the relationship between the contextual properties, such as authorization time, for this need, we can create a separate intermediate table, and then let the user table and the role table and the intermediate table to establish a one-to-many relationship, so that We can add some additional information such as authorization start time, authorization end time and so on in the intermediate table, which makes sense in the actual development.
The implementation of this method is no longer an example. A configuration implementation of a one-to-many association relationship can refer to my previous article.

Hibernate5 (14) annotation mapping [6] Many-to-many intermediate table associations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.