Hibernate multi-to-many relationship configuration--adding and deleting changes

Source: Internet
Author: User

Hibernate multi-to-many association configuration--and to implement additions and deletions

Hibernate does not introduce more, this is directly on my project to use examples to illustrate.

Data model


This is a draft of the data model ER diagram for users and user groups in the project, and the specific model object fields are primarily in the project.

Model class and Pojo interface, where Pojo interface is not used, we can also remove the test

Package Com.supre.model;import Java.io.serializable;import Java.util.set;public class User {private int userid;private String Userno;private string Username;private string password;private string telephone;private string remark;private int Userstatus;private set<group> groups;public User () {super ();//TODO auto-generated constructor stub}public User ( int userId, String userno) {super (); This.userid = Userid;this.userno = Userno;} Public User (int userId, string userno, String userName, String password,string Telephone, string remark, int userstatus, S Et<group> groups) {super (); This.userid = Userid;this.userno = Userno;this.username = Username;this.password = Password;this.telephone = Telephone;this.remark = Remark;this.userstatus = Userstatus;this.groups = groups;} public int getUserId () {return userId;} public void Setuserid (int userId) {this.userid = userId;} Public String Getuserno () {return userno;} public void Setuserno (String userno) {this.userno = Userno;} Public String GetusErname () {return userName;} public void Setusername (String userName) {this.username = UserName;} Public String GetPassword () {return password;} public void SetPassword (String password) {this.password = password;} Public String Gettelephone () {return telephone;} public void Settelephone (String telephone) {this.telephone = telephone;} Public String Getremark () {return remark;} public void Setremark (String remark) {This.remark = remark;} public int Getuserstatus () {return userstatus;} public void setuserstatus (int userstatus) {this.userstatus = UserStatus;} Public set<group> getgroups () {return groups;} public void Setgroups (set<group> groups) {this.groups = groups;} @Overridepublic String toString () {return "User [userid=" + UserId + ", userno=" + Userno + ", username=" + UserName + ", p assword= "+ password +", telephone= "+ telephone +", remark= "+ Remark +", userstatus= "+ UserStatus +", groupsize= "+ G Roups.size () + "]";}}

Package Com.supre.model;import Java.io.serializable;import Java.util.date;import java.util.set;public class Group{   private int groupid;private string groupname;private Date createtime;private string remark;//private user user; Owner Private set<user> users;public Group () {super ();//TODO auto-generated constructor stub}public int Getgroupid () {return groupId;} public void setgroupid (int groupId) {this.groupid = groupId;} Public String Getgroupname () {return groupName;} public void Setgroupname (String groupName) {this.groupname = GroupName;} Public Date Getcreatetime () {return createtime;} public void Setcreatetime (Date createtime) {this.createtime = Createtime;} Public String Getremark () {return remark;} public void Setremark (String remark) {This.remark = remark;} Public set<user> Getusers () {return users;} public void Setusers (set<user> users) {this.users = users;} Public Group (int groupId, string groupName, Date createtime, string remark,set<user> users) {super (); THIS.GRoupid = Groupid;this.groupname = Groupname;this.createtime = Createtime;this.remark = Remark;this.users = Users;} @Overridepublic String toString () {return "Group [groupid=" + GroupId + ", groupname=" + groupname+ ", createtime=" + Crea Tetime + ", remark=" + remark+ ", usersize=" + users.size () + "]";}}

Configuration information for Hibernate

The XML configuration used in this project is the Hibernate Master profile: Hibernate.xml Configuration database connection information

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "http// Hibernate.sourceforge.net/hibernate-configuration-3.0.dtd ">
Map file for model class user

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "Http://hibernate.sourceforge.net/hib Ernate-mapping-3.0.dtd "> 
Map file for Model class group

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "Http://hibernate.sourceforge.net/hib Ernate-mapping-3.0.dtd "> 

Hibernate's Help class

Package Com.supre.util;import Org.hibernate.session;import Org.hibernate.sessionfactory;import Org.hibernate.cfg.configuration;public class Hibernatesessionfactory {private static sessionfactory factory;private Static Configuration cfg;private static threadlocal<session> local = new threadlocal<session> (), static {cfg = new Configuration (). Configure ("Hibernate.xml"); factory = Cfg.buildsessionfactory ();} public static void Buildsessionfactory () {cfg = new Configuration (). Configure ("Hibernate.xml"); factory = Cfg.buildsessionfactory ();} Private Hibernatesessionfactory () {};p ublic static Sessionfactory getsessionfactory () {return factory;} public static session GetSession () {session session=local.get (); if (Session==null | |!session.isopen ()) {if (factory== NULL) {buildsessionfactory ();} Session = Factory.opensession (); Local.set (session);} return session;} public static void CloseSession () {Session session=local.get (); if (Session!=null && session.isopen ()) { Session.close ();} Local.set (null);}} 

Here is the test class,


Package Com.supre.util;import Java.util.hashset;import Java.util.list;import java.util.set;import Org.hibernate.session;import Com.supre.model.group;import Com.supre.model.user;public class TestHibernate {public static void Main (string[] args) {//testaddgroup ();//testadduser ();//testaddgroup2 ();//testadduser2 ();// TestAddUser3 ();//testselect ();//testdeleteuser (); Testdeletegroup ();} Test Add Simple Master object (Group) public static void Testaddgroup () {Session s = hibernatesessionfactory.getsession (); S.begintransaction (); Group G = new Group (); G.setgroupname ("Group 1"); S.save (g); S.flush (); S.gettransaction (). commit (); S.clear (); S.close ();} Test adds a simple controlled object (User) public static void Testadduser () {Session s = hibernatesessionfactory.getsession (); S.begintransaction (); User U = New user (), u.setusername ("User 1"); S.save (U); S.flush (); S.gettransaction (). commit (); S.clear (); S.close ();} The test adds the Master object (Group) and the corresponding relationship/** * If the master (group.hbm.xml) * is configured cascade= ' Save-update ', the Controlled party (User) data * Configuration cascade= ' is modified in the following results None ', the Controlled party (User) data will not be modified in the following results */public static void TestAddGroup2 () {Session s = hibernatesessionfactory.getsession (); S.begintransaction (); User U = new user (); U.setuserid (3);//Database existing user Iduser u1 = new User (); U1.setuserid (4);//Database of existing users idgroup g = new Group (); G. Setgroupname ("Group 4"); set<user> US = new hashset<> (); Us.add (U); Us.add (U1); G.setusers (US); S.save (g); S.flush (); S.gettransaction (). commit (); S.clear (); S.close ();} To test the addition of the controlled object (User) and the corresponding relationship/** * Here the accused and the master are configured cascade= "None" * * in the following code, can not be implemented to add the relationship to the User_group table, * on the contrary will delete G and G1 in User_ All relationships in group, * because the users in G and G1 are all empty */public static void TestAddUser2 () {Session s = hibernatesessionfactory.getsession (); S.begintransaction (); User U = new user (); U.setusername ("4"); Group G = new Group (); G.setgroupid (6);//Database existing user idGROUP G1 = new Group () G1.setgroupid (8);//Database existing user Idset<group > GS = new hashset<> (); Gs.add (g); Gs.add (G1); u.setgroups (GS); S.save (U); S.flush (); S.gettransaction (). Commit (); S.clear (); S.close ();} Test Add the Controlled object (User) and the corresponding relationship/** * Here the prosecution and the master are configured cascade= "None" * because Group isThe master (maintains the relationship side), when adding or modifying the relationship, * must be controlled by the group, 1 and 22 in the following code is required, * if there is no following 1 and 22 lines of code, it will simply add the user data, * Do not write the relationship to the User_group table */public static void TestAddUser3 () {Session s = hibernatesessionfactory.getsession (); S.begintransaction (); User U = new user (); U.setusername ("8"); Group G = (group) s.get (Group.class, 9); Group G1 = (group) s.get (Group.class, 10); set<group> GS = new hashset<> (); G.getusers (). Add (U); ----1g1.getusers (). Add (U); -----2gs.add (g); Gs.add (G1); u.setgroups (GS); S.save (U); S.flush (); S.gettransaction (). commit (); S.clear (); s.close ();} /** * The update and save methods are roughly the same, but note that before the main control (group) executes the Update method, the * must first take the users in the original Group and modify it so that the relationship can be maintained accurately when modifying the relationship. Modify the relationship by modifying the users in group */public static void Testupdate () {Session s = hibernatesessionfactory.getsession (); S.begintransaction (); Group G = (group) s.get (Group.class, 9), G.setgroupname ("Administrator"),//g.getusers (). Remove (New User (7, "")); S.save (g); S.flush (); S.gettransaction (). commit (); S.clear (); S.close ();} /** * Here Both the prosecution and the master are configured cascade= "None" * If the main control groupThe cascade= "delete" or cascade= "all" that is configured in the. Hbm.xml will be deleted by cascading the user */public static void Testdeletegroup () {Session s = Hibernatesessionfactory.getsession (); s.begintransaction ();//delete the specified user and the relationship Group G = (group) s.get (Group.class, 9); User U = (user) S.get (user.class, 7); G.getusers (). Remove (U);//Delete the relationship requires that the corresponding User in users is removed from S.delete (g); S.flush (); S.gettransaction (). commit (); S.clear (); S.close ();} /** * Here the prosecution and the main control are configured cascade= "None" * here if you need to delete a relationship or need to get the master first, the relationship is maintained through the master */public static void Testdeleteuser () {Session s = hibe Rnatesessionfactory.getsession (); s.begintransaction ();//delete the specified user and the relationship user U = (user) S.get (user.class, 12); set<group> GS = u.getgroups (), for (Group g:gs) {g.getusers (). Remove (U), or//If you need to delete the relationship you need this operation}s.delete (U); S.flush (); S.gettransaction (). commit (); S.clear (); S.close ();} /** * The query is not divided between the main and the accused * Configuration Query loading mode * lazy= "false" does not use lazy loading, the query is loaded directly associated data * lazy= "true" support lazy loading, only when the associated data to execute the query * Support lazy loading need to note: In the use of the association  Data can only be within one transaction (that is, within a database session) * If the data is used outside the transaction, the program will report a database connection exception because the session is closed when the query is executed outside the transaction. * Depending on your project, you need toTo take the best configuration */public static void Testselect () {Session s = hibernatesessionfactory.getsession (); S.begintransaction (); list<group> GS = S.createquery ("from Group"). the list (); for (Group g:gs) {/** * It is also important to note here that the default ToString () method cannot be used when printing objects For the default ToString () method, the set collection is processed directly by calling the ToString () of each object in the Set collection () * If there is a user value in the group object, in the Group.tostring () call set in the User.tostring () * while user.tostring () will fall off with the group.tostring () method in Set, and a dead loop causes a memory overflow exception */system.out.println (g);//}set< user> US = gs.get (3). Getusers (); for (user user:us) {System.out.println (user);} list<user> users = S.createquery ("from User"). List (), for (User u:users) {System.out.println (U);} S.flush (); S.gettransaction (). commit (); S.clear (); S.close ();}}


Hibernate multi-to-many relationship configuration--adding and deleting changes

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.