Hibernate (ii)

Source: Internet
Author: User

1. The State of the object

Code


public class Statetest extends hiberanteutils{/** * Session.save method converts an object in a temporary state to a persisted state object */@Testpublic void Testsaveperson () {Session session = Sessionfactory.opensession (); Transaction Transaction = Session.begintransaction (); person person = new person ();p erson.setpname ("AfDs");p erson.setpsex ("AF"), Session.save (person); Transaction.commit ( ); Session.close ();} /** * Session.update method can change the state of an object to a persisted state/@Testpublic void Testupdate () {Session session = Sessionfactory.opensession () ; Transaction Transaction = Session.begintransaction (); Person Person2 = new person ();//Temporary State person2.setpid (1L);//Temporary State session.update (PERSON2);//Persistent state transaction.commit (); Session.close ();} /** * When the Session.get method gets an object, it does not need to execute the UPDATE statement, because it is already persisted * when an object is a persisted object, when committing, hibernate will let the object and the snapshot compare, if the same, Do not issue an UPDATE statement * If it is not the same, issue an UPDATE statement */@Testpublic void Testget () {Session session = Sessionfactory.opensession (); Transaction Transaction = Session.begintransaction (); Person person = (person) session.get (Person.class, 1L);//Persistent PersoN.setpname ("TTKJKJHG");//session.update (person); Transaction.commit (); Session.close ();} /** * Session.clear method to empty all objects from the session */@Testpublic void Testclear () {Session session = Sessionfactory.opensession (); Transaction Transaction = Session.begintransaction (); Person person = (person) session.get (Person.class, 1L);p erson.setpname ("ASD"); Session.clear ();// Empties all the objects in the session session.update (person),//Converts the object from the off-tube state to the persistent state transaction.commit (); Session.close (); /** * Session.evict to empty an object from the session */@Testpublic void Testevict () {Session session = Sessionfactory.opensession (); Transaction Transaction = Session.begintransaction (); Person person = (person) session.get (Person.class, 1L);p erson.setpname ("asdsss"); Session.evict (person);// Session.update (person);//Convert the state of the object to a persistent state transaction.commit (); Session.close ();} /** * Whether an object is a persisted object is for a session of the */@Testpublic void Testsession () {Session session = Sessionfactory.opensession (); Transaction Transaction = Session.begintransaction (); Person person = (person) session.geT (Person.class, 1L);p erson.setpname ("ASFD"); Transaction.commit (); Session.close (); session = Sessionfactory.opensession ();//94transaction = Session.begintransaction ();//person.setpname ("AAA");// The person object is a temporary state object for the 94 session session.update (person); Transaction.commit (); Session.close ();} /** * When performing a transaction.commit, hibernate will check session * 1, if an object is a temporary state of objects, then session will not tube * 2, if an object is persisted state of the object, if there is an ID value, and the data Library corresponding, * then the object is compared with the snapshot, if the same, then do nothing, if inconsistent, issued an UPDATE statement * 3, if an object is persisted state of the object, if there is no ID value, then issued a save statement */@Testpublic void testm Uplyoption () {Session session = Sessionfactory.opensession (); Transaction Transaction = Session.begintransaction (); person person = new person ();p erson.setpname ("rrr1");p erson.setpsex ("asdfasdf"); Person Person3 = new person ();p erson3.setpname ("rrr2");p erson3.setpsex ("Asdfasdf"), Session.save (person); Person Person2 = (person) session.get (Person.class, 18L);p erson2.setpname ("asdfasdf"); Transaction.commit ();// The state of the object in the session is checked. If it is a temporary object, the session does not matter at all//if the ID of the persistent Session object has a value, update. No value, SAVE () Session.close ();} @Testpublic void TestMutiplyOption2 () {Session session = Sessionfactory.opensession (); Transaction Transaction = Session.begintransaction (); person person = new person ();p erson.setpname ("Haha1");p erson.setpsex ("Haha2"), Session.save (person); Transaction.commit (); session.evict (person); Session.close (); session = Sessionfactory.opensession (); transaction = Session.begintransaction (); session.update (person); session.clear (); Transaction.commit (); Session.close ();}}
2. One-to-many individual associations2.1. Database tables and entity class relationships

2.2. Configuration of Cascade, inverse, and foreign keys in the classes mapping file


<?xml version= "1.0" encoding= "Utf-8"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd "> 




2.3. Code representation


Package Cn.itcast.hibernate.sh.test;import Java.util.arraylist;import Java.util.hashset;import java.util.List; Import Java.util.set;import Org.hibernate.session;import Org.hibernate.transaction;import Org.hibernate.annotations.type;import Org.junit.test;import Cn.itcast.hiberate.sh.domain.classes;import Cn.itcast.hiberate.sh.domain.student;import cn.itcast.hibernate.sh.utils.hiberanteutils;/** * 1, create a new class * 2, create a new student * 3 , create a new class and create a new student * 4, there is already a class, a new student, establish the relationship between the student and the class * 5, there is a student, a new class, the students to join the class * 6, the transfer of a student from one class to another class * 7, To resolve the relationship between a class and a student * 8, lift the relationship between a class and some students * 9, lift the relationship between the class and all students * 10, there is already a class, there is a student, establish the relationship between the class and the student * 11, there is already a class, There are already multiple students, to establish the relationship between the students and the class * 12, delete the student * 13, delete the class * Delete the class at the same time delete the students * before deleting the class, the relationship between the class and students * @author Think * */public clas s onetomanysingletest extends hiberanteutils{@Testpublic void Testsaveclasses () {Session session = Sessionfactory.opensession (); Transaction Transaction = Session.begintransaction (); Classes Classes = new Classes (); Classes.setcname ("Wisdom Shanghai Cloud Phase IClasses.setdescription ("very bull"); Session.save (classes); Transaction.commit (); Session.close ();} @Testpublic void Testsavestudent () {Session session = Sessionfactory.opensession (); Transaction Transaction = Session.begintransaction (); Student Student = new Student () student.setsname ("Monitor"); Student.setdescription ("Old bull: Very Bull"); Session.save (Student); Transaction.commit (); Session.close ();} @Testpublic void Testsaveclasses_student () {Session session = Sessionfactory.opensession (); Transaction Transaction = Session.begintransaction (); Classes Classes = new Classes () classes.setcname ("Chuan Zhi Shanghai Yun Two:"); Classes.setdescription ("Very bull X"); Student Student = new Student () student.setsname ("Monitor"); Student.setdescription ("Old ox: Very ox x"); Session.save (Student); Session.save (classes); Transaction.commit (); Session.close ();} /** * When saving classes, cascade save students */@Testpublic void Testsaveclasses_cascade_student_save () {Session session = Sessionfactory.opensession (); Transaction Transaction = Session.begintransaction (); Classes Classes = new Classes (); classes.seTcname ("Chuan Zhi Shanghai Yun Three period:"); Classes.setdescription ("Very cow xx"); Student Student = new Student () student.setsname ("Monitor"); Student.setdescription ("Old ox: Very cow xx"); set<student> students = new hashset<student> (); Students.add (Student);// Establish an association between classes and student classes.setstudents (students); Session.save (classes); Transaction.commit (); Session.close () ;} /** * When saving class, Cascade update student */@Testpublic void Testsaveclasses_cascade_student_update () {Session session = Sessionfactory.opensession (); Transaction Transaction = Session.begintransaction (); Classes Classes = new Classes () classes.setcname ("Chuan Zhi Shanghai Yun Four:"); Classes.setdescription ("Very bull xxx"); Student Student = (Student) session.get (Student.class, 1L); Student.setsname ("Class secret"); set<student> students = new hashset<student> (); Students.add (Student); classes.setstudents (students); Session.save (classes); Transaction.commit (); Session.close ();} /** * Update class while saving students */@Testpublic void Testupdateclasses_cascade_student_save () {Session session = Sessionfactory.opensession (); Transaction TRAnsaction = Session.begintransaction (); Classes Classes = (Classes) session.get (Classes.class, 5L); Student Student = new Student (), Student.setsname ("Baan Hua"), student.setdescription ("rare Person"), classes.getstudents (). Add ( Student);//Because there is already a class, so first get the class students, then add students//Because classes is persistent object, so do not update () Transaction.commit (); Session.close ();} /** * Update class while updating students */@Testpublic void Testupdateclasses_cascade_student_update () {Session session = Sessionfactory.opensession (); Transaction Transaction = Session.begintransaction (); Classes Classes = (Classes) session.get (Classes.class, 5L); set<student> students = classes.getstudents ()///For all students of the CID 5 class//for (Student student:students) {// Student.setdescription ("Pressure Alexander");//} snapshot Transaction.commit (); Session.close ();} /** * A wrong demo---deleted in the classes mapping file cascade= "save-update" * Save the class while saving the student *------------------------------------* The client tries to save the student by saving the class, but because there is no cascade attribute in the configuration file for students, there is no cascade, * So student in classes is the object of the temporary state, Hibernate does not allow this to happen. * Session.save/update The operation of an object as a display operation, the action of a Cascade object is implicitly manipulated */@Testpublic void Testsaveclasses_cascade_student_save_error () {Session session = Sessionfactory.opensession (); Transaction Transaction = Session.begintransaction (); Classes Classes = new Classes () classes.setcname ("Chuan Zhi Shanghai Yun Six:"); Classes.setdescription ("Very bull xxxxxx"); Student Student = new Student () student.setsname ("Monitor xxxxxx"); Student.setdescription ("Old Ox: Very bull xxxxxx"); set<student> students = new hashset<student> (); Students.add (Student);// Establish an association between classes and student classes.setstudents (students); Session.save (classes); Transaction.commit (); Session.close () ;} /** * "Way One" * already exists a class, create a new student, establish the relationship between the student and the class * ============================================================== * Newly established a student, In the student table of CID self-cut everywhere, add the Student class ID, that is, establish a relationship. * By updating class cascade save student Cascade function, responsible for: There is already a class, a new student * Establish the relationship between class and students inverse function, responsible for: Establish the relationship between students and the class * ========================= ===================================== * uses the inverse attribute instead of the foreign key, the object-oriented way of thinking. Because the CID * inverse is not present in the student class to maintain the relationship between the two tables */@Testpublic void testsavestudent_r_1 () {Session session = SessionfactOry.opensession (); Transaction Transaction = Session.begintransaction (); Student Student = new Student () student.setsname ("Technical Monitor"); Student.setdescription ("Great God"); Classes Classes = (Classes) session.get (Classes.class, 1L); Classes.getstudents (). Add (student); Transaction.commit (); Session.close ();} /** "Way Two" * Hibernate:select Classes0_.cid as cid0_0_, classes0_.cname as cname0_0_, classes0_.description as descript3_0_ 0_ from Classes classes0_ where classes0_.cid=? Hibernate:select Max (SID) from Studenthibernate:select Students0_.cid as cid0_1_, Students0_.sid as Sid1_, students0_.si D as sid1_0_, Students0_.sname as sname1_0_, students0_.description as descript3_1_0_ from Student students0_ where Studen Ts0_.cid=? Hibernate:insert into Student (sname, description, sid) VALUES (?,?,?) Update the operation of the relationship hibernate:update Student set cid=? where sid=? */@Testpublic void testsavestudent_r_2 () {Session session = Sessionfactory.opensession (); Transaction Transaction = Session.begintransaction (); Student Student = NEW Student (); Student.setsname ("Technical Monitor"); Student.setdescription ("The Great God"); Classes Classes = (Classes) session.get (Classes.class, 1L); Session.save (student); Classes.getstudents (). Add (Student) Inverse can only work if the relationship is established. If not this line CID for Nulltransaction.commit (); Session.close ();} /** * There is already a student, a new class, to add students to the class */@Testpublic void Testsaveclasses_r () {Session session = Sessionfactory.opensession (); Transaction Transaction = Session.begintransaction (); Classes Classes = new Classes () Classes.setcname ("Lao BI Basic Reinforcement Class"); Classes.setdescription ("Must See, Killer"); Student Student = (Student) session.get (Student.class, 2L); set<student> students = new hashset<student> (); Students.add (Student); classes.setstudents (students); Session.save (classes); Transaction.commit (); Session.close ();} /** * Transfer a student from one class to another * that is, to relieve the relationship between the class and the student, and then establish the relationship between the student and the other class * Hibernate:select classes0_.cid as cid0_0_, Classes0_.cnam E as cname0_0_, classes0_.description as descript3_0_0_ from Classes classes0_ where classes0_.cid=? Hibernate:select Classes0_.cid AS cid0_0_, classes0_.cname as cname0_0_, classes0_.description as descript3_0_0_ from Classes classes0_ where classes0_.ci D=? Hibernate:select Student0_.sid as sid1_0_, student0_.sname as sname1_0_, student0_.description as descript3_1_0_ from Stu Dent student0_ where student0_.sid=? Hibernate:select students0_.cid as cid0_1_, Students0_.sid as sid1_, Students0_.sid as sid1_0_, students0_.sname as Sname 1_0_, students0_.description as descript3_1_0_ from Student students0_ where students0_.cid=? Hibernate:select students0_.cid as cid0_1_, Students0_.sid as sid1_, Students0_.sid as sid1_0_, students0_.sname as Sname 1_0_, students0_.description as descript3_1_0_ from Student students0_ where students0_.cid=? Hibernate:update Student set cid=null where cid=? and sid=? Lift Hibernate:update Student set cid=? where sid=? Simple operation: Direct the foreign key 5 to 6 to complete the */@Testpublic void Testtransformclass () {Session session = Sessionfactory.opensession (); Transaction Transaction = Session.begintransaction ();//classesCLASSES5 = (Classes) session.get (Classes.class, 5L); Classes classes6 = (Classes) session.get (Classes.class, 6L); Student Student = (Student) session.get (Student.class, 1L);//classes5.getstudents (). Remove (Student); Just remove the relationship, not delete student classes6.getstudents (). Add (student);//Create New Relationship transaction.commit (); Session.close ();} /** * Lift the relationship between a class and some students * * @Testpublic void Testr_some () {Session session = Sessionfactory.opensession (); Transaction Transaction = Session.begintransaction (); Classes Classes = (Classes) session.get (Classes.class, 1L); set<student> students = classes.getstudents ();//for (Student student:students) {//if (Student.getsid (). Longvalue () ==6| | Student.getsid (). Longvalue () ==7) {//students.remove (student);//}//}//set-->listlist<student> sList = new Arraylist<student> (students); for (int i=0;i<slist.size (); i++) {if (Slist.get (i). GetSID (). Longvalue () ==6| | Slist.get (i). GetSID (). Longvalue () ==7) {Slist.remove (Slist.get (i)); i--;}} Students = new hashset<student> (sList); Classes.setstudenTS (students);/** * Enhanced for loop can only be modified once * 1, with the normal for loop * 2, create a new set set, the original set set to keep the data stored in the new set set */transaction.commit (); Sessio N.close ();} /** the relationship between class one and all students * classes.setstudents (NULL); Set the class directly to student collection to NULL */@Testpublic void Testrealseall () {Session Session = Sessionfactory.opensession (); Transaction Transaction = Session.begintransaction (); Classes Classes = (Classes) session.get (Classes.class, 1L);//mode one set<student> students = classes.getstudents ();//   Students.clear (); Why not RemoveAll (conllection c)//mode 2classes.setstudents (NULL); Transaction.commit (); Session.close ();} /** * Delete student */@Testpublic void Testdeletestudent () {Session session = Sessionfactory.opensession (); Transaction Transaction = Session.begintransaction (); Student Student = (Student) session.get (Student.class, 8L); Session.delete (Student); Transaction.commit (); Session.close ();} /** * Remove the relationship between class and student before deleting class */@Testpublic void testdeleteclasses () {Session session = Sessionfactory.opensession (); Transaction Transaction = session.begintrAnsaction (); Classes Classes = (Classes) session.get (Classes.class, 5L);//classes.setstudents (null);//If the relationship is not maintained. Inverse=truesession.delete (classes);//class maintenance of the relationship, so in the deletion of classes, nature also lifted the relationship between the students and the class Transaction.commit (); Session.close ();} /** * Cascade Delete Class 5 while deleting the student */@Testpublic void Testdeleteclasses_cascade () {Session session = Sessionfactory.opensession (); Transaction Transaction = Session.begintransaction (); Classes Classes = (Classes) session.get (Classes.class, 5L); Session.delete (Classes); Transaction.commit (); Session.close ();}}



2.4. Common error Analysis

3. Hibernate Basics Summary
1. Hibernate component Persistence class implementation The corresponding serialization interface must have the default constructor persisted class properties cannot use the keyword identifier mapping file type Java type and Hibernate class  Type primary key generator increment identity assigned UUID ID prototype SET collection cascade the relationship between object and object, and foreign key does not have relationship between inverse object and foreign key The link information for the profile database holds the information for the mapping fileAdditional information: Hibernate internal features information display SQL statement: <property name= "Show_sql" >true</property> generated table: <property name= " Hbm2ddl.auto ">update</property>2, hibernate process configuraction loaded config file configuration = new Con    Figuration (); Configuration.configure (); Sessionfactory (interface) configuration file information, mapping file information, persisted class information all in Sessionfactory features: thread safety, singleton sessionfactory sessionfactory = Configuration    . Buildsessionfactory ();        Session (interface) Session session = Sessionfactory.opensession ();         1, CRUD operations are completed by the session 2, the transaction is opened by the session 3, two different sessions can only use their own transaction 4, the session determines the object's state an object in the session, it must be persistent 5, create a session, equivalent to open a database link transactiontransaction transaction = session.begintransaction (); Transaction.commi        T ();      1, the transaction is not automatically committed by default * JDBC Transaction default is auto-commit 2, must be opened by session 3, must and the current session binding (two sessions cannot share a transaction) 3, the state of the object of the transformation of 4, Hibernate principle: According to the client's code, reference the mapping file, generate SQL statements, using JDBC Technology for database operation











Hibernate (ii)

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.