@ Manytomany (insert, update, and delete for multiple-to-multiple data ing)

Source: Internet
Author: User

 

I have always thought that it is very troublesome to configure the hibernate ing file of the hibernate data table during multi-table join queries, recently, it is rare to have time to learn Java annotation. So by the way, I will continue to learn about hibernate. Although many people write these things, I think it is outdated, but as a bird, I hope to share my learned knowledge and experience with more birds like me. Let's just talk about it. Here I will share my understanding with you through many-to-many instances of individual personnel and roles.

1. The first is a pojo class of user. Java and role. java. The Code is as follows:

(1) user. Java

Package COM. candy. hibernate. bean; <br/> Import Java. io. serializable; <br/> Import Java. util. linkedhashset; <br/> Import Java. util. set; <br/> Import javax. persistence. column; <br/> Import javax. persistence. entity; <br/> Import javax. persistence. fetchtype; <br/> Import javax. persistence. ID; <br/> Import javax. persistence. manytoyun; <br/> Import javax. persistence. table; <br/> @ entity <br/> @ table (name = "user ") <br/> public class user implements serializable {<br/>/** <br/> */<br/> Private Static final long serialversionuid = 1l; <br/> @ ID <br/> @ column (name = "user_id", length = 7, nullable = false) <br/> private string ID; </P> <p> @ column (name = "user_name", length = 20, nullable = false) <br/> private string name; </P> <p> @ column (name = "user_pwd", length = 20, nullable = false) <br/> private string password; </P> <p> @ column (name = "user_addr", length = 50) <br/> private string address; </P> <p> @ column (name = "user_mail", length = 20) <br/> private string email; <br/> @ column (name = "head_img", length = 50) <br/> private string headimage; </P> <p> @ manytomany (mappedby = "users", fetch = fetchtype. lazy) <br/> private set <role> roles = new linkedhashset <role> (); </P> <p> Public String GETID () {<br/> return ID; <br/>}< br/> Public void setid (string ID) {<br/> This. id = ID; <br/>}< br/> Public String getname () {<br/> return name; <br/>}< br/> Public void setname (string name) {<br/> This. name = Name; <br/>}< br/> Public String GetPassword () {<br/> return password; <br/>}< br/> Public void setpassword (string password) {<br/> This. password = password; <br/>}< br/> Public String getaddress () {<br/> return address; <br/>}< br/> Public void setaddress (string address) {<br/> This. address = address; <br/>}< br/> Public String getemail () {<br/> return email; <br/>}< br/> Public void setemail (string email) {<br/> This. email = Email; <br/>}< br/> Public String getheadimage () {<br/> return headimage; <br/>}< br/> Public void setheadimage (string headimage) {<br/> This. headimage = headimage; <br/>}</P> <p> Public set <role> getroles () {<br/> return roles; <br/>}< br/> Public void setroles (set <role> roles) {<br/> This. roles = roles; <br/>}< br/> @ override <br/> Public String tostring () {<br/> stringbuilder STB = new stringbuilder (); <br/> Stb. append ("User ["); <br/> Stb. append ("ID:" + GETID (); <br/> Stb. append ("; Name:" + getname (); <br/> Stb. append ("; Password:" + GetPassword (); <br/> Stb. append ("; email:" + getemail (); <br/> Stb. append ("; Address:" + getaddress (); <br/> Stb. append ("headimage:" + getheadimage (); <br/> Stb. append ("]"); <br/> return Stb. tostring (); <br/>}< br/>}

 

Role. Java

 

Package COM. candy. hibernate. bean; <br/> Import Java. io. serializable; <br/> Import Java. util. linkedhashset; <br/> Import Java. util. set; <br/> Import javax. persistence. cascadetype; <br/> Import javax. persistence. column; <br/> Import javax. persistence. entity; <br/> Import javax. persistence. fetchtype; <br/> Import javax. persistence. ID; <br/> Import javax. persistence. joincolumn; <br/> Import javax. persistence. jointable; <br/> Import javax. persistence. manytoyun; <br/> Import javax. persistence. table; <br/> @ entity <br/> @ table (name = "role ") <br/> public class role implements serializable {<br/>/** <br/> */<br/> Private Static final long serialversionuid = 15972711247801_657l; <br/> @ ID <br/> @ column (name = "role_id", length = 7, nullable = false) <br/> private int ID; </P> <p> @ column (name = "role_name", length = 10, nullable = false) <br/> private string role; </P> <p> @ manytomany (cascade = cascadetype. persist, fetch = fetchtype. lazy) <br/> @ jointable (name = "user_role", joincolumns ={@ joincolumn (name = "role_id ")}, inversejoincolumns ={@ joincolumn (name = "user_id")}) <br/> private set <user> Users = new javashashset <user> (); </P> <p> @ manytomany (mappedby = "Roles") <br/> private set <priority> prioritys = new linkedhashset <priority> (); </P> <p> Public int GETID () {<br/> return ID; <br/>}< br/> Public void setid (int id) {<br/> This. id = ID; <br/>}< br/> Public String getrole () {<br/> return role; <br/>}< br/> Public void setrole (string role) {<br/> This. role = role; <br/>}</P> <p> Public set <user> getusers () {<br/> return users; <br/>}< br/> Public void setusers (set <user> Users) {<br/> This. users = users; <br/>}< br/> @ override <br/> Public String tostring () {<br/> stringbuilder STB = new stringbuilder (); <br/> Stb. append ("role ["); <br/> Stb. append ("ID:" + GETID (); <br/> Stb. append ("; Role:" + getrole (); <br/> Stb. append ("]"); <br/> return Stb. tostring (); <br/>}< br/>}

 

The preceding Java annotation can be used to map three tables:

(1) @ table (name = "user"): obtain the data table named "user.

(2) @ table (name = "role"): Obtain the table named role.

(3) @ jointable (name = "user_role.

 

At the same time. java @ manytomany (mappedby = "users ",...) we know that the primary prosecution is in role. java, that is, when a delete operation occurs in the role, Hibernate will automatically delete all data related to this role in the user_role table. In short, it is relatively easy to maintain the intermediate table when performing operations on the primary prosecution, so I will not talk about it here. For the operations to be prosecuted, we often need to maintain the intermediate relationship table during maintenance of the intermediate table. Below is an example of maintaining the intermediate table during the operations to be prosecuted:

 

A. Add a user with a specified role. To add a role to a user, the brain first thinks of adding the user to the group of the specified role. That's right. The Code is as follows:

 

Public void adduser (User user) {<br/> try {<br/> for (role: user. getroles () {<br/> role. getusers (). add (User); <br/>}< br/> This. gethibernatetemplate (). save (User); <br/>}catch (exception e) {<br/> E. printstacktrace (); <br/> logger. error ("error occured at:", e); <br/>}< br/>}

 

B. Update the user.

For updating a user, the maintenance idea for the intermediate table is similar to the above. My idea is to remove all roles before the user is updated, and then add existing roles for the user, so the code is roughly as follows (the following code is not very good, who has a good way to write it, and I hope to leave a message. Here I will introduce myself ):

Public void updateuser (User user) {<br/> try {<br/> // update user's role <br/> User olduser = (User) This. gethibernatetemplate (). get (user. class, <br/> User. GETID (); <br/> If (olduser! = NULL) {<br/> for (role: olduser. getroles () {<br/> role. getusers (). remove (olduser); <br/>}< br/> for (role: user. getroles () {<br/> role. getusers (). add (olduser); <br/>}< br/> This. gethibernatetemplate (). save (olduser); <br/> // update inverse table, the middle table has not been updated <br/> This. gethibernatetemplate (). merge (User); <br/>}< br/>} catch (exception e) {<br/> E. printstacktrace (); <br/> logger. error ("error occured at:", e); <br/>}< br/>}

 

C. The idea of deleting operations is similar. I will not talk about it here. The Code is as follows:

Public void deleteuser (string primarykey) {<br/> try {<br/> User user = (User) This. gethibernatetemplate (). get (user. class, <br/> primarykey); <br/> If (user! = NULL) {<br/> // remove the relationship <br/> for (role: user. getroles () {<br/> role. getusers (). remove (User); <br/>}< br/> This. gethibernatetemplate (). delete (User); <br/>}< br/>}catch (exception e) {<br/> E. printstacktrace (); <br/> logger. error ("error occured at:", e); <br/>}< br/>}

 

The following is the SQL statement for the table generated by hibernate:

 

Create Table 'user '(
'User _ id' varchar (7) Not null,
'User _ ADDR 'varchar (50) default null,
'User _ mail' varchar (20) default null,
'Head _ IMG 'varchar (50) default null,
'User _ name' varchar (20) not null,
'User _ pwd' varchar (20) not null,
Primary Key ('user _ id ')
) Eng

 

Create Table 'role '(
'Role _ id' int (11) not null,
'Role _ name' varchar (10) Not null,
Primary Key ('Role _ id ')
) Engine = InnoDB default charset = utf8;

 

Create Table 'user _ role '(
'Role _ id' int (11) not null,
'User _ id' varchar (7) Not null,
Primary Key ('Role _ id', 'user _ id '),
Key 'fk143bf46ad86b0194 '('Role _ id '),
Key 'fk143bf46a7d953854' ('user _ id '),
Constraint 'fk143bf46a7d9500004 'foreign key ('user _ id') References 'user' ('user _ id '),
Constraint 'fk143bf46ad86b0194 'foreign key ('Role _ id') References 'role' ('Role _ id ')
) Engine = InnoDB default charset = utf8;

 

Well, I can share so much with you. I hope it will be useful to you. If you have a wrong understanding, you are welcome to criticize and correct it.

 

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.