☛Hibernate one to one Bi-Directional Mapping Annotation Example

Hibernate one to one 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>

Trainer.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.OneToOne;
import javax.persistence.Table;

@Entity
@Table
public class Trainer {
	
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "id",length = 10,nullable = false)
	private int id;

	@Column(name = "first_name",length = 50,nullable = false)
	private String first_name;
	
	@Column(name = "last_name",length = 50,nullable = false)
	private String last_name;
	
	@Column(name = "email",length = 50,nullable = false)
	private String email;
	
	@OneToOne(cascade = CascadeType.ALL)
	@JoinColumn(name = "trainerDetailId")
	private TrainerDetail trainerDetail;
	
	public Trainer() {
		System.out.println("in case of View And Delete default constructor requried");
	}

	public Trainer(String first_name, String last_name, String email) {
		this.first_name = first_name;
		this.last_name = last_name;
		this.email = email;
	}

	public Trainer(int id, String first_name, String last_name, String email) {
		this.id = id;
		this.first_name = first_name;
		this.last_name = last_name;
		this.email = email;
	}

	public TrainerDetail getTrainerDetail() {
		return trainerDetail;
	}

	public void setTrainerDetail(TrainerDetail trainerDetail) {
		this.trainerDetail = trainerDetail;
	}

	@Override
	public String toString() {
		return "Trainer [id=" + id + ", first_name=" + first_name + ", last_name=" + last_name + ", email=" + email +"]";
	}
}

TrainerDetail.java

package com.code4devops;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table
public class TrainerDetail {
	
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "id",length = 10,nullable = false)	
	private int id;
	
	@Column(name = "youtube_channel",length = 50,nullable = false)	
	private String youtube_channel;
	
	@Column(name = "channel_topic",length = 50,nullable = false)
	private String channel_topic;
	
	//@OneToOne(mappedBy="trainerDetail",cascade={CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH})
	@OneToOne(mappedBy = "trainerDetail",cascade = CascadeType.ALL)
	private Trainer trainer;
	
	public TrainerDetail() {
		System.out.println("in case of View And Delete default constructor requried");
	}
	
	public TrainerDetail(String youtube_channel, String channel_topic) {
		this.youtube_channel = youtube_channel;
		this.channel_topic = channel_topic;
	}
	
	public TrainerDetail(int id, String youtube_channel, String channel_topic) {
		this.id = id;
		this.youtube_channel = youtube_channel;
		this.channel_topic = channel_topic;
	}
	public Trainer getTrainer() {
		return trainer;
	}

	public void setTrainer(Trainer trainer) {
		this.trainer = trainer;
	}
	@Override
	public String toString() {
		return "TrainerDetail [id=" + id + ", youtube_channel=" + youtube_channel + ", channel_topic=" + channel_topic+ "]";
	}
}

MySessionFactory.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(Trainer.class).addAnnotatedClass(TrainerDetail.class);
		SessionFactory factory=configuration3.buildSessionFactory();
		return factory;
	}
}

TrainerService.java

package com.code4devops;
public interface TrainerService {
	public abstract void mydelete(int trainerId);
	public abstract void myView(int trainerId);
}

TrainerServiceImpl.java

package com.code4devops;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
public class TrainerServiceImpl implements TrainerService{
	
	SessionFactory factory=MySessionFactory.getMySessionFactory();
	Session session=factory.getCurrentSession();
	
@Override
public void mydelete(int trainerDetailId) {
	try {
			session.beginTransaction();
			TrainerDetail trainerDetail=session.get(TrainerDetail.class, trainerDetailId);
			if(trainerDetail!=null) {
				System.out.println("Deleteing "+ trainerDetail);
				System.out.println("Deleteing "+ trainerDetail.getTrainer());
				session.delete(trainerDetail);
			}else {
				System.out.println(trainerDetailId +" This Trainer ID does not exist");
			}
			session.getTransaction().commit();
			System.out.println("DONE");	
		}catch (Exception e) {
			System.out.println(e);
		}finally {
			session.close();
		}
		
	}

	@Override
	public void myView(int trainerDetailId) {
		try {
			session.beginTransaction();
			TrainerDetail trainerDetail=session.get(TrainerDetail.class, trainerDetailId);
			if(trainerDetail!=null) {
				System.out.println(trainerDetail);
				System.out.println(trainerDetail.getTrainer());
			}else {
				System.out.println(trainerDetailId +" This Trainer Detail ID does not exist");
			}
			session.getTransaction().commit();
			System.out.println("DONE");	
		}catch (Exception e) {
			System.out.println(e);
		}finally {
			session.close();
		}
		
	}
}

App.java

package com.code4devops;
public class App {
public static void main(String[] args) {
	TrainerService trainerService=new TrainerServiceImpl();
	/***********(@onetone Bi-Directional) delete****************/
	//trainerService.mydelete(4);
	/***********(@onetone Bi-Directional) view****************/
	//trainerService.myView(4);
	}
}