One to many and many to one example of Hibernate association

One to many and many to one example of Hibernate association
Techiio-author
Written by Sagar RabidasFebruary 21, 2022
16 min read
Hibernate
1 VIEWS 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 1 VIEWS SHARE
Techiio-author
Sagar Rabidas

Software Developer

Let's start the discussion with Hibernate Associations.

Introduction of Hibernate Associations:-

Hibernate Associations technology handles how to persist java objects. But, it is possible only when the object has the XML file that describes how to map it, or the object is annotated with hibernate annotations. In another case, the objects will be just simple plain java objects without relation to the database tables. Very regularly several entities may be associated. In this case, they must have references from every different. Such gadgets may have unidirectional or bidirectional references. We're going to apprehend in element how to cope with such situations.

Java gadgets can contain references to one or several other java items. They can have direct references as an embedded property or subject. In the case of indirect references, it is also carried out through arrays, units, lists, and so forth. These associations are represented within the database with overseas key relationships.

If the simplest one of the pair of java training includes a connection with the opposite, the association is called unidirectional. Inside the instances of mutual association, we get the bidirectional relation.

The sizeable novice’s mistake in designing entity models is to try and make all institutions bidirectional. It is vital to remember that associations that do not look like a herbal part of the model of your item should now not be pressured into it.

Create User and Address tables and relationships:-

Before starting with code we need to create User and Address tables and relationships in our MySql database example by running queries:

create table exampledb.USER (
  user_id INT NOT NULL auto_increment,
  first_name VARCHAR(100) default NULL,
  last_name  VARCHAR(100) default NULL,
  PRIMARY KEY (user_id)
);
create table exampledb.address (
  address_id INT NOT NULL auto_increment,
  city VARCHAR(20) default NULL,
  address  VARCHAR(20) default NULL,
  PRIMARY KEY (address_id),
  CONSTRAINT user_address FOREIGN KEY (address_id) REFERENCES user(user_id) ON DELETE CASCADE
);

Here are our entities in code:

package edu.hibernate.example;
import java.io.Serializable;
import javax.persistence.*;
@Entity
@Table(name = "User")
public class UserEntity implements Serializable {
@Id
@Column(name = "user_id", unique = true, nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "first_name", unique = false, nullable = false, length = 100)
private String firstName;
@Column(name = "last_name", unique = false, nullable = false, length = 100)
private String lastName;
@OneToOne(mappedBy="user", cascade = CascadeType.ALL)
AddressEntity address;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public AddressEntity getAddress() {
return address;
}
public void setAddress(AddressEntity address) {
this.address = address;
}
public Integer getId() {
return id;
}
}

package edu.hibernate.example;
import java.io.Serializable;
import javax.persistence.*;
@Entity
@Table(name = "Address")
public class AddressEntity  implements Serializable{
@Id
@Column(name = "address_id", unique = true, nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
 
@Column(name = "city", unique = false, nullable = false, length = 20)
private String city;
   
@Column(name = "address", unique = false, nullable = false, length = 20)
private String address;
 
@OneToOne
@PrimaryKeyJoinColumn
UserEntity user;
//getters and setters
}
And, the second entity:
package edu.hibernate.example;
import java.io.Serializable;
import javax.persistence.*;
@Entity
@Table(name = "Address")
public class AddressEntity implements Serializable {
@Id
@Column(name = "address_id", unique = true, nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "city", unique = false, nullable = false, length = 20)
private String city;
@Column(name = "address", unique = false, nullable = false, length = 20)
private String address;
@OneToOne
@PrimaryKeyJoinColumn
UserEntity user;
//getters and setters
}

In our case, with cascade operations and one-to-one relationships, it is sufficient to equal simply one entity into the database. Permits create the person and cope with objects, save one in every one of them into the database. After, we can create a brand new consultation and get our entities from the database to make sure that each person and address objects had been endured.

package egg.hibernate.example;

import java.util.Iterator;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
public class HibernateExample {
public static void main(String[] args) {
Configuration configuration = new Configuration();
configuration.addAnnotatedClass(edu.hibernate.example.UserEntity.class);
configuration.addAnnotatedClass(edu.hibernate.example.AddressEntity.class);
Session session1 = configuration.configure().buildSessionFactory().openSession();
 
session1.beginTransaction();
// Create new User object
UserEntity user = new UserEntity();
user.setFirstName("Jozeph");
user.setLastName("Jonson");
// Create new Address object
AddressEntity address = new AddressEntity();
address.setCity("Berlin");
address.setAddress("High str., 111");
user.setAddress(address);
address.setUser(user);
session1.save(user);
// session1.save(address);
session1.getTransaction().commit();
Integer userId = user.getId();
Integer addressId = address.getId();
Session session2 = configuration.configure().buildSessionFactory().openSession();
session2.beginTransaction();
UserEntity userDB = (UserEntity) session2.get(UserEntity.class, userId);
AddressEntity addressDB = (AddressEntity) session2.get(AddressEntity.class, addressId);
System.out.println(userDB.getId());
System.out.println(userDB.getAddress().getId());
System.out.println(addressDB.getId());
System.out.println(addressDB.getUser().getId());
}
}

There are extra approaches to create one-to-one relationships which might be less famous. As an example, we can create one more table to save keys of person and cope with tables, one report is answerable for one courting between the person and address objects. The desk is referred to as a common join table.

One more way is to create a one-to-one mapping with a shared primary key

In this technique, we have to use a common primary key value in both tables.

One-to-many association:-

In a one-to-many technique, both entities are answerable for growing the relationship and maintaining it. The consumer entity wishes to claim one-to-many relationships, the car entity proclaims is many-to-one from its give up. Permit’s take a look at the code of consumer and automobile entities.

package edu.hibernate.example;
import java.io.Serializable;
import java.util.Set;
import javax.persistence.*;
@Entity
@Table(name = "User")
public class UserEntity implements Serializable {
@Id
@Column(name = "user_id", unique = true, nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "first_name", unique = false, nullable = false, length = 100)
private String firstName;
@Column(name = "last_name", unique = false, nullable = false, length = 100)
private String lastName;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "USERE_ID")
private Set<CarEntity> cars;
// Getters and setters
}
package edu.hibernate.example;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "Car")
public class CarEntity implements Serializable {
@Id
@Column(name = "car_id", unique = true, nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "model", unique = false, nullable = false, length = 20)
private String model;
@ManyToOne
private UserEntity user;
// Getters and setters
}

Many-to-many association:-

Hibernate many-to-many mapping is between two entities where one can have a relation with multiple other entities and vice versa. For example, a user can be subscribed to several sites with the news. Every site with the news has a lot of users.

Let’s look at the code of our entities:

package edu.hibernate.example;
import java.io.Serializable;
import java.util.Set;
import javax.persistence.*;
@Entity
@Table(name = "User")
public class UserEntity implements Serializable {
@Id
@Column(name = "id", unique = true, nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "first_name", unique = false, nullable = false, length = 100)
private String firstName;
@Column(name = "last_name", unique = false, nullable = false, length = 100)
private String lastName;
    @ManyToMany(cascade=CascadeType.ALL)
    @JoinTable(name="USER_SUBSCRIPTIONS", joinColumns={@JoinColumn(referencedColumnName="ID")}, inverseJoinColumns={@JoinColumn(referencedColumnName="ID")})  
    private Set<SubscriptionEntity> subscriptions;
//Getters and setters 
}
package edu.hibernate.example;
import java.io.Serializable;
import java.util.Set;
import javax.persistence.*;
@Entity
@Table(name = "Subscription")
public class SubscriptionEntity implements Serializable {
@Id
@Column(name = "id", unique = true, nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "name", unique = false, nullable = false, length = 20)
private String name;
@Column(name = "link", unique = false, nullable = false, length = 100)
private String link;
@ManyToMany(mappedBy="subscriptions")
private Set<UserEntity> subscriptions;
 
//Getters and setters 
}

A user entity class is the owner entity, this is chargeable for making the affiliation and preserving it. For this entity, we have used @jointable annotation. Subcriptionentity is our mapped entity, which is mapped to the user entity the usage of the “mapped by” characteristic. Additionally, we consumer annotation @manytomany in each entity. Here is the manner to paintings on such styles of relationships.

package edu.hibernate.example;
import java.util.HashSet;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
public class HibernateExample {
public static void main(String[] args) 
    {
Configuration configuration = new Configuration();
configuration.addAnnotatedClass(edu.hibernate.example.UserEntity.class);
configuration.addAnnotatedClass(edu.hibernate.example.SubscriptionEntity.class);
Session session = configuration.configure().buildSessionFactory().openSession();
        SubscriptionEntity site1 = new SubscriptionEntity();
        SubscriptionEntity site2 = new SubscriptionEntity();
        Set<SubscriptionEntity> subscriptions = new HashSet<SubscriptionEntity>();
        subscriptions.add(site1);
        subscriptions.add(site2);
        
        UserEntity user1 = new UserEntity();
        UserEntity user2 = new UserEntity();     
        Set<UserEntity> users = new HashSet<UserEntity>();
        users.add(user1);
        users.add(user2);
        user1.setSubscriptions(subscriptions);
        user2.setSubscriptions(subscriptions);
 
        session.save(user1);
        session.save(user2);
         
        session.getTransaction().commit();
    }
}

Hibernate
Associations
Java
1 VIEWS 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 1 VIEWS SHARE
Was this blog helpful?
techiio-price-plantechiio-price-plantechiio-price-plantechiio-price-plantechiio-price-plan
You must be Logged in to comment
Code Block
Techiio-author
Sagar Rabidas
Software Developer
Techiio-followerTechiio-followerTechiio-followerTechiio-followerTechiio-follower
+8 more
300 Blog Posts
14 Discussion Threads
Trending Technologies
15
Software40
DevOps46
Frontend Development24
Backend Development20
Server Administration17
Linux Administration26
Data Center24
Sentry24
Terraform23
Ansible83
Docker70
Penetration Testing16
Kubernetes21
NGINX20
JenkinsX17
Techiio-logo

Techiio is on the journey to build an ocean of technical knowledge, scouring the emerging stars in process and proffering them to the corporate world.

Follow us on:

Subscribe to get latest updates

You can unsubscribe anytime from getting updates from us
Developed and maintained by Wikiance
Developed and maintained by Wikiance