☛Hibernate Lazy Loading and Eager Loading Annotation Example

hibernate lazy loading and eager loading annotation example

hibernate.cfg.xml

<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/hibernate1?useSSL=false&serverTimezone=UTC</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <property name="connection.pool_size">1</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <property name="show_sql">true</property>
        <property name="current_session_context_class">thread</property>
     </session-factory>
</hibernate-configuration>

Student.java

package com.code4devops;
import java.util.ArrayList;
import java.util.List;
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;
@Entity
@Table
public class Student {
	
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name="student_id",length = 10,nullable = false)
	private int id;
	
	@Column(name="first_name",length = 100,nullable = false)
	private String fname;
	
	@Column(name="Last_name",length = 100,nullable = false)
	private String lname;
	
	@Column(name="mobile",length = 100,nullable = false)
	private String mobile;
	
	@Column(name="email",length = 100,nullable = false)
	private String email;
	
	@OneToMany(fetch = FetchType.EAGER,mappedBy = "student",cascade = { CascadeType.PERSIST,CascadeType.MERGE,CascadeType.DETACH,CascadeType.REFRESH})
	//@OneToMany(fetch = FetchType.LAZY,mappedBy = "student",cascade = { CascadeType.PERSIST,CascadeType.MERGE,CascadeType.DETACH,CascadeType.REFRESH})
	private List coachingClasses;
	
	public Student() {}
	
	public Student(String fname, String lname, String mobile, String email) {
		this.fname = fname;
		this.lname = lname;
		this.mobile = mobile;
		this.email = email;
	}	
	public List<Coaching< getCoachingClasses() {
		return coachingClasses;
	}
	public void setCoachingClasses(List<Coaching< coachingClasses) {
		this.coachingClasses = coachingClasses;
	}
	public void myAdd(Coaching tempCoachingClass) {
		if(coachingClasses==null) {
			coachingClasses=new ArrayList<Coaching<();
		}
		coachingClasses.add(tempCoachingClass);
		tempCoachingClass.setStudent(this);
	}
	@Override
	public String toString() {
		return "Student [id=" + id + ", fname=" + fname + ", lname=" + lname + ", mobile=" + mobile + ", email=" + email
				+ ", coachingClasses=" + coachingClasses + "]";
	}
}

Coaching.java

package com.code4devops;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
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
public class Coaching{
	
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name="Coaching_id",length = 10,nullable = false)
	int id;
	
	@Column(name="class_Name",length = 100,nullable = false)
	String className;
	
	@ManyToOne(cascade = { CascadeType.PERSIST,CascadeType.MERGE,CascadeType.DETACH,CascadeType.REFRESH})
	@JoinColumn(name = "student_id")
	private Student student;
	
	public Coaching() {}
	
	public Coaching(String className) {
		this.className=className;
	}
	public Student getStudent() {
		return student;
	}
	public void setStudent(Student student) {
		this.student = student;
	}
	@Override
	public String toString() {
		return "Coaching [id=" + id + ", className=" + className + "]";
	}
}

App.java

package com.code4devops;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class App {
public static void main(String[] args) {
		Configuration configuration=new Configuration();
		Configuration configuration2=configuration.configure("hibernate.cfg.xml");
		Configuration configuration3=configuration2.addAnnotatedClass(Student.class).addAnnotatedClass(Coaching.class);
		SessionFactory sessionFactory=configuration3.buildSessionFactory();
		int studentId=1;
		Session session=sessionFactory.getCurrentSession();
		try {
			session.beginTransaction();
			Student student=session.get(Student.class, studentId);
			if(student!=null){
				System.out.println("Code4devops Student : "+student);
				System.out.println("Code4devops Coaching : "+student.getCoachingClasses());
			}else {
				System.out.println(studentId+" Student ID does not exist ");
			}
			System.out.println("Code4devops DONE");
		}catch (Exception e) {
			System.out.println(e);
		} 
		finally {
			session.close();
			sessionFactory.close();
		}
		
	}
			
}