Inverse and cascade in Hibernate, both of which are used in one-to-many (One-to-many) or many-to-many (many-to-many) relationships.
As a general rule,inverse represents whether the relationship is maintained by itself, and cascade represents whether to perform cascading operations. Next, give a column to explain the relationship in more detail.
Suppose there are t_department (departmental tables) and T_employee (employee tables), and they have a one-to-many relationship. The table is defined as follows:
CREATE TABLE t_department (id int auto_increment, name varchar), primary key (ID)-primary key) CREATE TABLE T_employee (id int auto_increment, name varchar (), salary int, DeptID int, primary key (ID),--primary key key FK_EMP_DEP T (deptid),--foreign KEY constraint cons_emp_dept foreign key (DeptID) references t_department (ID) on UPDATE cascade on delete C Ascade--FOREIGN KEY constraint)
Within a department, there can be multiple employees, that is, 1:n relationships. This 1:n relationship is implemented through T_department's primary key ID and T_employee's foreign key DeptID Association.
(1) Hibernate is an ORM framework that implements the mapping between a Java object and a data table . The t_department and T_employee mentioned above are tables in the database, and there are corresponding JavaBean classes in hibernate that correspond to two tables, that is, the Department class and the employee class.
Department.java
Package Com.rk.hibernate.g_one2many;import java.util.set;public class Department{private int deptid;private String deptname;private set<employee> emps;public int Getdeptid () {return deptid;} public void Setdeptid (int deptid) {this.deptid = DeptID;} Public String Getdeptname () {return deptname;} public void Setdeptname (String deptname) {this.deptname = Deptname;} Public set<employee> Getemps () {return emps;} public void Setemps (set<employee> emps) {this.emps = Emps;} @Overridepublic String toString () {return "Department [deptid=" + DeptID + ", deptname=" + Deptname + "]";}}
Department.hbm.xml
<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://www.hibernate.org/dtd/ Hibernate-mapping-3.0.dtd ">
Employee.java
Package com.rk.hibernate.g_one2many;public class employee{private int empid;private string empname;private double salary;private department dept;public int getempid () {return empid;} Public void setempid (int empid) {this.empid = empid;} Public string getempname () {return empname;} Public void setempname (string empname) {this.empname = empname;} Public double getsalary () {return salary;} Public void setsalary (double salary) {this.salary = salary;} Public department getdept () {return dept;} Public void setdept (department dept) {this.dept = dept;} @Overridepublic string tostring () {return "employee [empid=" + empId + ", empname=" + empName + ", salary=" + salary + "]";}}
Employee.hbm.xml
<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://www.hibernate.org/dtd/ Hibernate-mapping-3.0.dtd ">
(2) Hibernate is an ORM framework that implements the mapping between a Java object and a data table (I know I'm repeating it). In Hibernate, although the object it operates on is the JavaBean class (for example, the Department class and the Employee Class), it is eventually converted to operations on tables in the database (for example, T_department and T_employee).
(3) in the above mentioned, T_department and t_employee two tables exist 1:n relationship, then in the Department class and employee class instances (instance), should also reflect this relationship. In the T_employee table, there is a foreign key field DeptID, so the employee class corresponding to the T_employee table to maintain this association is "taken for granted."
(4) Hibernate, not just the "take it for granted" implementation, provides a more powerful function that allows the Department class to maintain an association between t_department and T_employee two tables. Of course, this feature that Hibernate provides is optional and can be used by developers or unused. This feature exists in Hibernate's mapping file in the form of the inverse attribute, which represents the ability to maintain relationship between two tables (Power): inverse= "false" means no inversion, That is, having the power to maintain the relationship between the two tables; Inverse= "True" indicates a reversal and does not have the power to maintain the relationship between the two tables.
(5) It is more straightforward to say that when we save an instance object of the Department class, if an instance of the Deparment class is associated with an object of several employee classes, Hibernate determines whether to update t_ based on the value of the inverse. The DeptID field in the Employee table. Note: Under normal circumstances, if you save an employee's object, updating the DeptID field in the T_employee table is normal and is understandable; now, save the instance object of the Deparment class, and the T_ The DeptID of the employee table is updated, and it is done to maintain the relationship between the two tables.
(6) The inverse property controls the relationship between two tables, while the Cascade property controls whether to change the contents of another table. In the example above, inverse may simply control whether the Department class can update the DeptID field of the T_employee table, and the Cascade property is a control over whether a data record can be added or deleted in the T_employee table ; inverse affects only one field, while Cascade affects a row of data.
650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M00/84/10/wKioL1eEotyBY1BEAAB8eKVpS6M956.png "title=" Hibernate_logo_a.png "alt=" Wkiol1eeotyby1beaab8ekvps6m956.png "/>
1. Inverse properties650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M01/84/11/wKiom1eEpmXCw2K4AAAUt6GN76M934.jpg "title=" Inverse.jpg "alt=" Wkiom1eepmxcw2k4aaaut6gn76m934.jpg "/>
Inverse attribute is sometimes referred to as relationship Owner.
Application Scenarios: When we is talking about one-to-many or many-to-many relationships, one of the sides should take the responsibility O F managing the relationship. (When we talk about 1-to-many, many-to-many relationships, one party needs to maintain a mapping between them.) The scenario for the inverse attribute is 1-to-many (One-to-many) or many-to-many (Many-to-many), which is not used in many-to-1 (many-to-one) scenarios. )
Default value: Note that the inverse= "false" was actually a default, so can skip providing the inverse attribute if you wish to SE t the inverse relationship to false. (Note: The default value for inverse is false.) )
the effect of the inverse property on operations
Serial Number |
type of Operation |
whether it affects |
Specific Instructions |
1 |
Save data |
Have an impact |
If you set control inversion, that is inverse=true, then the association is maintained through the departmental side. While saving the department, the data is saved, but the relationship is not maintained. That is, the foreign key field deptid is null |
2 |
Get Data |
No |
Getting data is only a reference to the relationship between two tables and does not modify the relationship, so getting data is not affected. |
3 |
Disassociate relationship |
Have an impact |
Inverse=false, you can disassociate Inverse=true, the current party (department) does not have control, can not release the association relationship. (no UPDATE statement is generated and no error is produced) |
4 |
Delete data |
Have an impact |
Inverse=false, with control, can be deleted. Empty the foreign key reference before deleting the data. Inverse=true, no control: If the deleted record has been referenced by foreign key, will error, violate the main foreign KEY reference constraint! If the deleted records are not referenced, you can delete them directly. |
App_inverse.java
package com.rk.hibernate.g_one2many;import java.util.hashset;import java.util.set;import org.hibernate.session;import org.hibernate.sessionfactory;import org.hibernate.cfg.configuration; import org.junit.test;public class app_inverse{private static sessionfactory sf; Static{sf = new configuration (). Configure (). addclass (Department.class). addclass (Employee.class) . Buildsessionfactory ();} 1. set inverse, what are the effects on saving data? have//if inverse= "false", the association relationship between Deparment and employee is added//if inverse= "true", the association relationship is not added @testpublic void testsave () {int i = 0; Session session = sf.opensession (); Session.begintransaction ();// employee 1EMPLOYEE&NBSP;EMP1 = new employee (); Emp1.setempname ("Zhangxiao" + i) emp1.setsalary (2Employee);// Employees emp2 = new employee (); Emp2.setempname ("Li Xiaoxi" + i); Emp2.setsalary (+);// Department department dept = new department ();d ept.setdeptname ("department" + i); Set<employee> emps = new hashset<employee> (); Emps.add (EMP1); Emps.add (EMP2); Dept.setemps (Emps);// inverse=true, does not set association relationships. The association should be maintained by the employee Side Session.save (dept); Session.save (EMP1); Session.save (EMP2); Session.gettransaction (). commit (); Session.close (); System.out.println ("Execution is over!") ");} 2. set Inverse, what is the impact on getting data? None. @Testpublic void testget () {session session = sf.opensession (); Session.begintransaction ();D epartment dept = (Department) session.get (Department.class, &NBSP;2); System.out.println (Dept.getdeptid ()); System.out.println (Dept.getdeptname ()); System.out.println (Dept.getemps ()); Session.gettransaction (). commit (); Session.close (); System.out.println ("Execution is over!") ");} 3. set inverse, the impact on the association relationship? Yes//if inverse= "false", the association relationship between Deparment and employee is removed///if inverse= "true", the association relationship cannot be deleted @testpublic void testclear () {session Session = sf.opensession (); Session.begintransaction ();// Acquisition Department department dept = (Department) session.get (department.class, 2);// release Relationship dept.getemps (). Clear (); Session.gettransaction (). commit (); Session.close (); System.out.println ("Execution is over!") ");} 4. set inverse, effect on delete? Yes//if inverse= "false", the association relationship between Deparment and employee can be deleted///if inverse= "true", the association relationship cannot be deleted. If the deleted record has been referenced by foreign key, will error, violate the primary foreign KEY reference constraint! If the deleted records are not referenced, you can delete them directly. @Testpublic void testdelete () {session session = sf.opensession (); Session.begintransaction ();// Get Department department dept = (Department) session.get ( department.class, 3);if (dept != null) {session.delete (dept);} Session.gettransaction (). commit (); Session.close (); System.out.println ("Execution is over!") ");}}
2. Cascade Properties
650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M01/84/11/wKiom1eEpgvxrMPcAAAeSRVQX4s535.jpg "title=" Cascade.jpg "alt=" Wkiom1eepgvxrmpcaaaesrvqx4s535.jpg "/>
function: When persisting object graphs, we usually has to issue save (or update) commands on individual entities. However, the Cascade attribute defined on the graph lets us save the whole graph without we have to worry about saving The entities one by one. Setting the cascading behavior can reduce the lines of code and make it more succinct. We are only having to save the parent node; The rest of the graph is handled by Hibernate ' s runtime.
scope of Use: The cascade attribute is set on the collection attributes.
Cascade represents a cascading operation, and it may have the following values:
None cascade operation, default value
Save-update Cascade Save or update
Delete Cascade deletion
Save-update,delete Cascade Save, UPDATE, delete
All ibid. Cascade Save, UPDATE, delete
App_cascade.java
package com.rk.hibernate.g_one2many;import java.util.hashset;import java.util.set;import org.hibernate.session;import org.hibernate.sessionfactory;import org.hibernate.cfg.configuration; import org.junit.test;public class app_cascade{private static sessionfactory sf; Static{sf = new configuration (). Configure (). addclass (Department.class). addclass (Employee.class) . Buildsessionfactory ();} @Testpublic void testsave () {int i=4; Session session = sf.opensession (); session.begintransaction ();//Employee 1employee emp1 = new employee (); Emp1.setempname ("Zhangxiao" + i); emp1.setsalary (1000);//Employee 2EMPLOYEE&NBSP;EMP2 = new employee (); Emp2.setempname ("Li Xiaoxi" + i); emp2.setsalary (800);//Department department Dept = new department ();d ept.setdeptname ("department" + i); Set<employee> emps = new hashset<employee> (); Emps.add (emp1); Emps.add (EMP2);d ept.setemps (Emps); Session.save (dept);//After you set up the Cascade Save, you only need to save Dept Object//session.save (EMP1);// Session.save (EMP2); Session.gettransaction (). commit (); Session.close (); System.out.println ("Execution is over!") ");} @Testpublic void testdelete () {session session = sf.opensession (); Session.begintransaction ();// Get Department department dept = (Department) session.get ( DEPARTMENT.CLASS,&NBSP;3), if (dept != null) {session.delete (dept);// Cascade Delete}session.gettransaction ( ). commit (); Session.close (); System.out.println ("Execution is over!") ");}}
3, Hibernate common interview question: Inverse and cascade difference?
(1) When it comes to the difference between the two, it must be similar or similar.
(2) The similarities between inverse and Cascade are that all two of them appear in One-to-many and many-to-many mappings.
(3) The difference between the two is that inverse controls whether to maintain relationship between tables, and cascade is to control whether cascade operations are performed.
(4) There is a pre-and post-implementation relationship between the two: Cascade before, inverse, because there is always "data" itself, and then "the relationship between data." Cascade operates on data, while inverse operates on relationships.
Different between Cascade and inverse
http://www.mkyong.com/hibernate/different-between-cascade-and-inverse/
() Hibernate's Inverse and cascade properties