Persistence top

I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE COURSE

1. Introduction

This quick Hibernate tutorial will take us through an example of a one-to-many mapping using JPA annotations – an alternative to XML.

We’ll also learn what bidirectional relationships are, how they can create inconsistencies, and how the idea of ownership can help.

2. Description

Simply put, one-to-many mapping means that one row in a table is mapped to multiple rows in another table.

Let’s look at the following entity relationship diagram to see a one-to-many association:

For this example, we will implement a cart system, where we have a table for each cart and another table for each item. One cart can have many items, so here we have a one-to-many mapping.

The way this works at the database level is we have cart_id as a primary key in the cart table and also a cart_id as a foreign key in items.

And, the way we do it in code is with @OneToMany.

Let’s map the Cart class to the Items object it a way that reflects the relationship in the database:

public class Cart {

    //...     
 
    @OneToMany(mappedBy="cart")
    private Set<Items> items;
	
    //...
}

We can also add a reference to Cart in Items using @ManyToOne, making this a bidirectional relationship. Bidirectional means that we are able to access items from carts, and also carts from items.

The mappedBy property is what we use to tell Hibernate which variable we are using to represent the parent class in our child class.

The following technologies and libraries are used in order to develop a sample Hibernate application that implements one-to-many association:

  • JDK 1.8 or later
  • Hibernate 4 or later
  • Maven 3 or later
  • MySQL Server 5.6 or later

3. Setup

3.1. Database Setup

Below is our database script for Cart and Items tables. We use the foreign key constraint for one-to-many mapping:

CREATE TABLE `Cart` (
  `cart_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`cart_id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

CREATE TABLE `Items` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `cart_id` int(11) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  KEY `cart_id` (`cart_id`),
  CONSTRAINT `items_ibfk_1` FOREIGN KEY (`cart_id`) REFERENCES `Cart` (`cart_id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

Our database setup is ready, let’s move on to creating the Hibernate example project.

3.2. Maven Dependencies

We will then add the Hibernate and MySQL driver dependencies to our pom.xml file.The Hibernate dependency uses JBoss logging and it automatically gets added as transitive dependencies:

  • Hibernate version 5.2.7.Final
  • MySQL driver version 6.0.5

Please visit the Maven central repository for the latest versions of Hibernate and the MySQL dependencies.

3.3. Hibernate Configuration

Here is the configuration of Hibernate:

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.connection.url">
          jdbc:mysql://localhost:3306/setup</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.current_session_context_class">thread</property>
        <property name="hibernate.show_sql">true</property>
    </session-factory>
</hibernate-configuration>

3.4. HibernateAnnotationUtil Class

With the HibernateAnnotationUtil class, we just need to reference the new Hibernate configuration file:

private static SessionFactory sessionFactory;

private SessionFactory buildSessionFactory() {
     
    Configuration configuration = new Configuration();
    configuration.configure("hibernate-annotation.cfg.xml");
    System.out.println("Hibernate Annotation Configuration loaded");
        	
    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
      .applySettings(configuration.getProperties()).build();
    System.out.println("Hibernate Annotation serviceRegistry created");
        	
    SessionFactory sessionFactory 
      = configuration.buildSessionFactory(serviceRegistry);
        	
    return sessionFactory;
}	

public SessionFactory getSessionFactory() {
    if(sessionFactory == null) sessionFactory = buildSessionFactory();
    return sessionFactory;
}

4. The Models

The mapping related configurations will be done using JPA annotations in the model classes:

@Entity
@Table(name="CART")
public class Cart {

    //...

    @OneToMany(mappedBy="cart")
    private Set<Items> items;
	
    // getters and setters
}

Please note that the @OneToMany annotation is used to define the property in Items class that will be used to map the mappedBy variable. That’s why we have a property named “cart” in the Items class:

@Entity
@Table(name="ITEMS")
public class Items {
    
    //...
    @ManyToOne
    @JoinColumn(name="cart_id", nullable=false)
    private Cart cart;

    public Items() {}
    
    // getters and setters
}

It is important to note that the @ManyToOne annotation is associated with Cart class variable. @JoinColumn annotation references the mapped column.

5. In Action

In the test program, we are creating a class with a main() method for getting the Hibernate Session and saving the model objects into the database implementing the one-to-many association:

sessionFactory = HibernateAnnotationUtil.getSessionFactory();
session = sessionFactory.getCurrentSession();
System.out.println("Session created");
	    
tx = session.beginTransaction();

session.save(cart);
session.save(item1);
session.save(item2);
	    
tx.commit();
System.out.println("Cart ID=" + cart.getId());
System.out.println("item1 ID=" + item1.getId()
  + ", Foreign Key Cart ID=" + item.getCart().getId());
System.out.println("item2 ID=" + item2.getId()
+ ", Foreign Key Cart ID=" + item.getCart().getId());

This is the output of our test program:

Session created
Hibernate: insert into CART values ()
Hibernate: insert into ITEMS (cart_id)
  values (?)
Hibernate: insert into ITEMS (cart_id)
  values (?)
Cart ID=7
item1 ID=11, Foreign Key Cart ID=7
item2 ID=12, Foreign Key Cart ID=7
Closing SessionFactory

6. The @ManyToOne Annotation

As we’ve seen in section 2, we can specify a many-to-one relationship by using the @ManyToOne annotation. A many-to-one mapping means that many instances of this entity are mapped to one instance of another entity – many items in one cart.

The @ManyToOne annotation lets us create bidirectional relationships, too. We’ll cover this in detail in the next few subsections.

6.1. Inconsistencies and Ownership

Now, if Cart referenced Items, but Items didn’t, in turn, reference Cart, our relationship would be unidirectional. The objects would also have a natural consistency.

In our case, though, the relationship is bidirectional, bringing in the possibility of inconsistency.

Let’s imagine a situation where a developer wants to add item1 to cart and item2 to cart2, but makes a mistake so that the references between cart2 and item2 become inconsistent:

Cart cart1 = new Cart();
Cart cart2 = new Cart();

Items item1 = new Items(cart1);
Items item2 = new Items(cart2); 
Set<Items> itemsSet = new HashSet<Items>();
itemsSet.add(item1);
itemsSet.add(item2); 
cart1.setItems(itemsSet); // wrong!

As shown above, item2 references cart2 whereas cart2 doesn’t reference item2 — and that’s bad.

How should Hibernate save item2 to the database? Will item2 foreign key reference cart1 or cart2?

We resolve this ambiguity using the idea of an owning side of the relationship — references belonging to the owning side take precedence and are saved to the database.

6.2. items as the Owning Side

As stated in the JPA specification under section 2.9, it’s a good practice to mark many-to-one side as the owning side.

In other words, Items would be the owning side and Cart the inverse side, which is exactly what we did earlier.

So, how did we achieve this?

By including the mappedBy attribute in the Cart class, we mark it as the inverse side.

At the same time, we also annotate the Items.cart field with @ManyToOne, making Items the owning side.

Going back to our “inconsistency” example, now Hibernate knows that the item2‘s reference is more important and will save item2‘s reference to the database.

Let’s check the result:

item1 ID=1, Foreign Key Cart ID=1
item2 ID=2, Foreign Key Cart ID=2

Although cart references item2 in our snippet, item2‘s reference to cart2 is saved in the database.

6.3. cart as the Owning Side

It’s also possible to mark the one-to-many side as the owning side, and many-to-one side as the inverse side.

Although this is not a recommended practice, let’s go ahead and give it a try.

The code snippet below shows the implementation of one-to-many side as the owning side:

public class ItemsOIO {
    
    //  ...
    @ManyToOne
    @JoinColumn(name = "cart_id", insertable = false, updatable = false)
    private CartOIO cart;
    //..
}

public class CartOIO {
    
    //..  
    @OneToMany
    @JoinColumn(name = "cart_id") // we need to duplicate the physical information
    private Set<ItemsOIO> items;
    //..
}

Notice how we removed the mappedBy element and set the many-to-one @JoinColumn as insertable and updatable to false.

If we run the same code, the result will be the opposite:

item1 ID=1, Foreign Key Cart ID=1
item2 ID=2, Foreign Key Cart ID=1

As shown above, now item2 belongs to cart.

7. Conclusion

We have seen how easy it is to implement the one-to-many relationship with the Hibernate ORM and MySQL database using JPA annotations.

Also, we learned about bidirectional relationships and how to implement the notion of owning side.

The source code of this tutorial can be found over on GitHub.

Persistence bottom

I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE LESSONS

newest oldest most voted
Notify of
Sagar Kalburgi
Guest
Sagar Kalburgi

Thanks for writing this blog! It was helpful