Hibernate inverse keyword


Hibernate inverse keyword

In this section, you will learn how to use inverse keyword in Hibernate.

In this section, you will learn how to use inverse keyword in Hibernate.

Hibernate inverse keyword

In this section, you will learn how to use inverse keyword in Hibernate.

The keyword inverse is always very confusing to the developers. The inverse keyword is always used in One-to-Many and Many-to-Many relationship, Many-to-One doesn't have this keyword. It tells us which side is the relationship owner. In a relation (One-to-Many / Many-to-Many) , relationship owner is in charge of the relationship and handle the relationship among the two.

The keyword  inverse=true means the related table is relationship owner and inverse=false means table is not the relationship owner.

The inverse  keyword tells Hibernate which table is the relationship owner between the two tables and the class related to the relationship owner table will UPDATE the relationship.

Consider the below example, the employee and address table has a one-to-many relationship.

The employee table has many-to-one relationship. And the address table has one-to-many relationship.

 The Address.hbm.xml is given below :

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

<hibernate-mapping package="net.roseindia">
<class name="Address" table="address">
<id name="addressId" column="address_id">
<generator class="native" />
<property name="street" column="street"/>
<property name="city" column="city"/>
<property name="state" column="state"/>
<property name="country" column="country"/>
<set name="employees" table="employee" inverse="{true/false}" lazy="true" fetch="select">
<column name="address_id" not-null="true" />
<one-to-many class="net.roseindia.Employee" />

inverse = true

Here inverse can be true or false. Here, if inverse=true , employee is the relationship owner. So, Address will not UPDATE the relationship

inverse = false

If inverse=false , address is the relationship owner and Address will UPDATE the relationship.

If keyword inverse is not define

If keyword inverse is not define,  inverse=false is used as default.


When inverse=false in the above, the following code will produce three SQL statements, two inserts and one update :


Address address = new Address();
address.setStreet("Lake Gardens");
address.setState("West Bengal");

Employee e1 = new Employee("Rakesh", "Sharma", "9999999999");





Hibernate: insert into address (street, city, state, country) values (?, ?, ?, ?)
Hibernate: insert into employee (firstname, lastname, cell_phone, address_id) values (?, ?, ?, ?)
Hibernate: update employee set address_id=? where employee_id=?

Address will update the ?employee.address_id? through Set variable (employees), because Address is the relationship owner.