Posted In: Hibernate

Hibernate 5 – One to Many – @JoinColumn vs mappedBy


@JoinColumn
Specifies a column for joining an entity association or element collection. If the JoinColumn annotation itself is defaulted, a single join column is assumed and the default values apply.

mappedBy
The field that owns the relationship. Required unless the relationship is unidirectional.

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "employer")
private Set employees = new HashSet();

@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "EMPLOYER_ID", nullable = false)
private Employer employer;

 

Maven Hibernate 5.2.5

<dependency>
	<groupId>org.hibernate</groupId>
	<artifactId>hibernate-tools</artifactId>
	<version>5.2.5.Final</version>
</dependency>
<dependency>
	<groupId>org.hibernate</groupId>
	<artifactId>hibernate-core</artifactId>
	<version>5.2.10.Final</version>
</dependency>
<dependency>
	<groupId>org.hibernate</groupId>
	<artifactId>hibernate-entitymanager</artifactId>
	<version>5.2.10.Final</version>
</dependency>
<dependency>
	<groupId>org.hibernate.javax.persistence</groupId>
	<artifactId>hibernate-jpa-2.1-api</artifactId>
	<version>1.0.0.Final</version>
</dependency>
<dependency>
	<groupId>javassist</groupId>
	<artifactId>javassist</artifactId>
	<version>3.12.1.GA</version>
</dependency>
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<version>5.1.43</version>
</dependency>
<dependency>
	<groupId>org.slf4j</groupId>
	<artifactId>slf4j-log4j12</artifactId>
	<version>1.7.25</version>
</dependency>

 

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
	<session-factory>
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="connection.url">jdbc:mysql://localhost:3306/new_schema</property>
		<property name="connection.username">root</property>
		<property name="connection.password">password</property>
		<property name="connection.pool_size">10</property>
		<property name="dialect">org.hibernate.dialect.MySQL57Dialect</property>
		<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
		<property name="show_sql">true</property>
		<property name="hbm2ddl.auto">create</property>
		<mapping class="com.example.hibernate.Employee" />
		<mapping class="com.example.hibernate.Employer" />
	</session-factory>
</hibernate-configuration>

 

Employee POJO @ManyToOne and @JoinColumn

package com.example.hibernate;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name = "employee_master")
public class Employee {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "EMPLOYEE_ID")
	private Long employeeId;
	@Column(name = "FIRST_NM", length = 50)
	private String firstName;
	@Column(name = "LAST_NM", length = 50)
	private String lastName;
	@Column(name = "MIDLLE_NM", length = 50)
	private String middleName;

	@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
	@JoinColumn(name = "EMPLOYER_ID", nullable = false)
	private Employer employer;
...............
//getter setter
}

 

Employer POJO with mappedBy = “employer”

package com.example.hibernate;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

@Entity
@Table(name = "employer_master", uniqueConstraints = {
        @UniqueConstraint(columnNames = "EMPLOYER_NM") })
public class Employer {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "EMPLOYER_ID")
	private Long employerId;
	@Column(name = "EMPLOYER_NM", length = 50)
	private String employerName;
	@Column(name = "EMPLOYER_ADDRESS", length = 150)
	private String employerAddress;

	@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "employer")
	private Set<Employee> employees = new HashSet<Employee>();
...............
//getter setter
}

 

Session creator

package com.example.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

	private static final SessionFactory sessionFactory = buildSessionFactory();

	private static SessionFactory buildSessionFactory() {

		try {
			Configuration configuration = new Configuration()
			        .configure("hibernate.cfg.xml");
			configuration.addAnnotatedClass(Employee.class);
			configuration.addAnnotatedClass(Employer.class);
			StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
			        .applySettings(configuration.getProperties());
			SessionFactory factory = configuration
			        .buildSessionFactory(builder.build());

			return factory;
		} catch (Throwable ex) {
			ex.printStackTrace();
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}
}

 

Create and save Employer and list of Employees

package com.example.hibernate;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class Main {

	public static void main(String[] args) {

		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		try {

			Employer employer = new Employer();
			employer.setEmployerId(0L);
			employer.setEmployerName("INFOSYS");
			employer.setEmployerAddress("Bengaluru");

			Employee employee = new Employee();
			employee.setEmployeeId(0L);
			employee.setFirstName("Abhijit");
			employee.setLastName("Pednekar");
			employee.setEmployer(employer);

			session.beginTransaction();
			session.save(employer);
			session.save(employee);

			session.getTransaction().commit();
			session.close();

			session = sessionFactory.openSession();
			List<Employer> employers = session
			        .createNativeQuery("SELECT * FROM employer_master",
			                Employer.class)
			        .getResultList();
			System.out.println(employers);

			List<Employee> employees = session
			        .createNativeQuery("SELECT * FROM employee_master",
			                Employee.class)
			        .getResultList();
			System.out.println(employees);
			
			Employer empr = (Employer) session.get(Employer.class, new Long(1));
			System.out.println(empr.getEmployees());

		} catch (HibernateException e) {
			e.printStackTrace();
		} finally {
			session.close();
			sessionFactory.close();
		}
	}
}

by , on September 4th, 2017

  • Categories