DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • How to Store Text in PostgreSQL: Tips, Tricks, and Traps
  • Simplify Java Persistence Using Quarkus and Hibernate Reactive
  • The Ultimate Guide on DB-Generated IDs in JPA Entities
  • Best Performance Practices for Hibernate 5 and Spring Boot 2 (Part 1)

Trending

  • Building Reliable LLM-Powered Microservices With Kubernetes on AWS
  • A Deep Dive Into Firmware Over the Air for IoT Devices
  • Enforcing Architecture With ArchUnit in Java
  • How to Ensure Cross-Time Zone Data Integrity and Consistency in Global Data Pipelines
  1. DZone
  2. Data Engineering
  3. Databases
  4. Hibernate Mapping

Hibernate Mapping

Let's take a look at Hibernate mapping and also explore the relationships that can be established between entities.

By 
Ankit Kumar user avatar
Ankit Kumar
·
Aug. 25, 18 · Analysis
Likes (16)
Comment
Save
Tweet
Share
143.3K Views

Join the DZone community and get the full member experience.

Join For Free

hibernate mappings are one of the key features of hibernate . they establish the relationship between two database tables as attributes in your model. that allows you to easily navigate the associations in your model and criteria queries.

you can establish either unidirectional or bidirectional i.e you can either model them as an attribute on only one of the associated entities or on both. it will not impact your database mapping tables, but it defines in which direction you can use the relationship in your model and criteria queries.

the relationship that can be established between entities are-

  • one to one — it represents the one to one relationship between two tables.
  • one to many/many to one — it represents the one to many relationship between two tables.
  • many to many — it represents the many to many relationship between two tables.

you all must have heard about these relationships. in this article, you will learn about all relationships using hibernate.

one to one

there is the one to one relationship between address . address must not be an entity as it is a value type, but for this example, we will consider address as a separate entity.

for the one to one relationship, we need to simply annotate the data member of the corresponding class with @onetoone. after running the application, if we look after the table created by the hibernate, we will find that the user_details table has all the fields i.e id , username, along with a foreign key of address table column (in this example). if we want to achieve two-way binding like user object should have address and vice-versa. then we have to make the user object inside address class and annotate it with @onetoone. then, the address table will also contain the foreign key of the user column.

you will see the name of the field in both the table will be default depending on table name but to change the default implementation, we have to annotate it with @joincolumn with an attribute name.

address.java

package com.innovatnm.demohibernate.model;

import javax.persistence.entity;
import javax.persistence.generatedvalue;
import javax.persistence.id;
import javax.persistence.onetoone;

@entity
public class address {

@id @generatedvalue
private int id;
private string street;
private string city;
@onetoone(mappedby="address")
private user user;

public address() {}
public address(int id, string street, string city) {
this.id = id;
this.street = street;
this.city = city;
}

public string getstreet() {
return street;
}

public void setstreet(string street) {
this.street = street;
}

public string getcity() {
return city;
}

public user getuser() {
return user;
}

public void setuser(user user) {
this.user = user;
}

public void setcity(string city) {
this.city = city;
}

public int getid() {
return id;
}

public void setid(int id) {
this.id = id;
}
}

one to many/many to one

there is a one to many relationship between user and mobile . as one user can have more than one mobile. and a many to one relationship between mobile and user .

for the one to many relationship, we have to annotate in the same manner as above with @onetomany to collection type data member . after running the application, if we look after the table created by hibernate, we will find that hibernate is making a new table for mapping of user_details table and mobile table( in this example ). for two-way binding, we annotate the user inside the mobile class with @manytoone.

you will see the mapping table and its column name will have a default name generated based on the two tables but to change the default implementation, andwe will annotate it @jointable and the attribute name in this is to change the name of mapping table and attribute joincolumns for the primary key of the same class ( user in this case) and inversejoincolumns for the primary key of corresponding class ( mobile in this case).

mobile.java

package com.innovatnm.demohibernate.model;

import javax.persistence.entity;
import javax.persistence.generatedvalue;
import javax.persistence.id;
import javax.persistence.joincolumn;
import javax.persistence.manytoone;

@entity
public class mobile {
@id @generatedvalue
private int id;
private string brand;
private string model;

@manytoone
@joincolumn(name="user_id")
private user user;

public int getid() {
return id;
}
public void setid(int id) {
this.id = id;
}
public string getbrand() {
return brand;
}
public void setbrand(string brand) {
this.brand = brand;
}
public string getmodel() {
return model;
}
public void setmodel(string model) {
this.model = model;
}
public user getuser() {
return user;
}
public void setuser(user user) {
this.user = user;
}

}

many to many

there is a many to many relationship between user and vehicle . we will let consider a world where there are multiple owner of a vehicle and a owner can also own multiple vehicle . you can consider that the vehicle is used for the rent and one user can rent multiple vehicle and a vehicle can be rented by multiple users .

for a many to many relationship, we have to annotate in the same manner as above with @manytomany to collection type data member and for two-way binding, we have to do the same in the corresponding class. after running the application if we look after the table created by the hibernate, we will found that the there is two mapping table formed one made by first mapping (by user in this case) and other mapping table by vehicle class. so, in order to restrict it, we have to tell hibernate that the mapping is already done by other class with the help of attribute mappedby in @manytomany. so, we will add this attribute in either of the class user or vehicle.

vehicle.java

package com.innovatnm.demohibernate.model;

import java.util.arraylist;
import java.util.collection;

import javax.persistence.entity;
import javax.persistence.generatedvalue;
import javax.persistence.generationtype;
import javax.persistence.id;
import javax.persistence.manytomany;

@entity
public class vehicle {

@id
@generatedvalue(strategy=generationtype.auto)
private int id;
private string name;

@manytomany(mappedby="vehicle")
private collection<user> user=new arraylist<>();;


public int getid() {
return id;
}
public void setid(int id) {
this.id = id;
}
public string getname() {
return name;
}
public void setname(string name) {
this.name = name;
}
public collection<user> getuser() {
return user;
}
public void setuser(collection<user> user) {
this.user = user;
}
}

now, after looking up to user class, you will need to understand things clearly. so here is user class

user.java

package com.innovatnm.demohibernate.model;

import java.util.arraylist;
import java.util.collection;

import javax.persistence.cascadetype;
import javax.persistence.entity;
import javax.persistence.generatedvalue;
import javax.persistence.generationtype;
import javax.persistence.id;
import javax.persistence.joincolumn;
import javax.persistence.jointable;
import javax.persistence.manytomany;
import javax.persistence.onetomany;
import javax.persistence.onetoone;
import javax.persistence.table;

@entity
@table(name="user_details")
public class user {

@generatedvalue(strategy=generationtype.auto)
@id
private int id;
private string username;

@manytomany(cascade=cascadetype.all)
@jointable(name="usr_vehicle",joincolumns=@joincolumn(name="user_id"),inversejoincolumns=@joincolumn(name="vehicle_id") )
private collection<vehicle> vehicle=new arraylist<>();

@onetoone(cascade=cascadetype.all)
@joincolumn(name="address_id")
private address address;

@onetomany(cascade=cascadetype.all)
@jointable(name="user_mobile_mapping",joincolumns=@joincolumn(name="user_id"),inversejoincolumns=@joincolumn(name="mobile_id"))
private collection<mobile> mobile=new arraylist<>();;


public collection<mobile> getmobile() {
return mobile;
}
public void setmobile(collection<mobile> mobile) {
this.mobile = mobile;
}
public collection<vehicle> getvehicle() {
return vehicle;
}
public void setvehicle(collection<vehicle> vehicle) {
this.vehicle = vehicle;
}
public address getaddress() {
return address;
}
public void setaddress(address address) {
this.address = address;
}
public int getid() {
return id;
}
public void setid(int id) {
this.id = id;
}
public string getusername() {
return username;
}
public void setusername(string username) {
this.username = username;
}
}


hibernatemain.java

package com.innovatnm.demohibernate;

import org.hibernate.session;
import org.hibernate.sessionfactory;
import org.hibernate.cfg.configuration;

import com.innovatnm.demohibernate.model.address;
import com.innovatnm.demohibernate.model.mobile;
import com.innovatnm.demohibernate.model.user;
import com.innovatnm.demohibernate.model.vehicle;

public class hibernatemain {

public static void main(string[] args) {
user user=new user();
user user2=new user();
user2.setusername("dev");
user.setusername("ankit");

address address= new address();
address.setstreet("sector 15");
address.setcity("noida");
address address2=new address();
address2.setcity("muzaffarpur");
address2.setstreet("sahebganj");


vehicle veh=new vehicle();
veh.setname("car");
vehicle vehicle=new vehicle();
vehicle.setname("jeep");
vehicle vehicle2= new vehicle();
vehicle2.setname("bike");
vehicle vehicle3= new vehicle();
vehicle3.setname("bus");
vehicle vehicle4=new vehicle();
vehicle4.setname("cycle");
vehicle vehicle5= new vehicle();
vehicle5.setname("truck");

mobile mobile =new mobile();
mobile.setbrand("sony");
mobile.setmodel("xperia z3");
mobile mobile2 = new mobile();
mobile2.setbrand("redmi");
mobile2.setmodel("note 5 pro");
mobile mobile3 = new mobile();
mobile3.setbrand("nokia");
mobile3.setmodel("7 plus");

user.setaddress(address);
user2.setaddress(address2);
address.setuser(user);
address2.setuser(user2);

user.getmobile().add(mobile);
user.getmobile().add(mobile2);
mobile.setuser(user);
mobile2.setuser(user);
user2.getmobile().add(mobile3);
mobile3.setuser(user2);

user.getvehicle().add(veh);
user.getvehicle().add(vehicle);
user.getvehicle().add(vehicle2);
veh.getuser().add(user);
vehicle.getuser().add(user);
vehicle2.getuser().add(user);
user2.getvehicle().add(vehicle3);
user2.getvehicle().add(vehicle4);
user2.getvehicle().add(vehicle5);
vehicle3.getuser().add(user2);
vehicle4.getuser().add(user2);
vehicle5.getuser().add(user2);


sessionfactory sf=new configuration().configure().buildsessionfactory();
session session=sf.opensession();
session.begintransaction();
session.save(user);
session.save(user2);
session.gettransaction().commit();
session.close();
}
}

after executing the main class, you will find the table as shown:

address table




mobile table

user_details table

usr_vehicle table

user_mobile_mapping table

vehicle table

Relational database Database Hibernate

Published at DZone with permission of Ankit Kumar. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How to Store Text in PostgreSQL: Tips, Tricks, and Traps
  • Simplify Java Persistence Using Quarkus and Hibernate Reactive
  • The Ultimate Guide on DB-Generated IDs in JPA Entities
  • Best Performance Practices for Hibernate 5 and Spring Boot 2 (Part 1)

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!