☛Hibernate one to many Bi-Directional Mapping Annotation Example

Hibernate one to many Bi-Directional Mapping Annotation

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.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(mappedBy = "student",cascade = { CascadeType.PERSIST,
			CascadeType.MERGE,
			CascadeType.DETACH,
			CascadeType.REFRESH})
	private List<Coaching> 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 + "]";
	}
}

Coaching.java

package com.code4devops;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class MySessionFactory{
	public static  SessionFactory getMySessionFactory() {
		Configuration configuration=new Configuration();
		Configuration configuration2=configuration.configure("hibernate.cfg.xml");
		Configuration configuration3=configuration2.addAnnotatedClass(Student.class).addAnnotatedClass(Coaching.class);
		SessionFactory factory=configuration3.buildSessionFactory();
		return factory;
	}
}

StudentCoachingService.java

package com.code4devops;
public interface StudentCoachingService {
public abstract void mysave();
public abstract void myview();
public abstract void myDelete();
}

StudentCoachingServiceImpl.java

package com.code4devops;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
public class StudentCoachingServiceImpl implements StudentCoachingService{

	@Override
	public void mysave() {
		SessionFactory sessionFactory=MySessionFactory.getMySessionFactory();
		Session session=sessionFactory.getCurrentSession();
		try {			
			session.beginTransaction();
			Student student=new Student("Anmol", "singh", "7894564567", "anmol@gmail.com");
			Coaching className1=new Coaching("Spring MVC");
			Coaching className2=new Coaching("AWS");
			Coaching className3=new Coaching("GCP");
			student.myAdd(className1);
			student.myAdd(className2);
			student.myAdd(className3);
			session.save(student);
			session.save(className1);
			session.save(className2);
			session.save(className3);
			session.getTransaction().commit();
		}catch (Exception e) {
			System.out.println(e);
		} 
		finally {
			session.close();
			sessionFactory.close();
		}
	}
	
	@Override
	public void myview() {
		int studentId=1;
		SessionFactory sessionFactory=MySessionFactory.getMySessionFactory();
		Session session=sessionFactory.getCurrentSession();
		try {
			session.beginTransaction();
			Student student=session.get(Student.class, studentId);
			if(student!=null){
				System.out.println(student);
				System.out.println(student.getCoachingClasses());
			}else {
				System.out.println(studentId+" Student ID does not exist ");
			}
			session.getTransaction().commit();
		}catch (Exception e) {
			System.out.println(e);
		} 
		finally {
			session.close();
			sessionFactory.close();
		}
	}
	
	@Override
	public void myDelete() {
		int coachingId=1;
		SessionFactory sessionFactory=MySessionFactory.getMySessionFactory();
		Session session=sessionFactory.getCurrentSession();
		try {
			session.beginTransaction();
			Coaching coaching=session.get(Coaching.class, coachingId);
			if(coaching!=null){
				session.delete(coaching);
			}else {
				System.out.println(coachingId+" Coaching ID does not exist ");
			}
			session.getTransaction().commit();
		}catch (Exception e) {
			System.out.println(e);
		} 
		finally {
			session.close();
			sessionFactory.close();
		}
	}
}

App.java

package com.code4devops;
public class App {
	public static void main(String[] args) {
		StudentCoachingService service=new StudentCoachingServiceImpl();
		//service.mysave();
		service.myview();
		//service.myDelete();
	}
}