Jumat, 19 Desember 2014

Hibernate One-To-Many Mapping Using Java Annotations Tutorial with Examples


One To Many Relationship

Also known as a many-to-one relationship, this occurs when the maximum of one multiplicity is one and the other is greater than one. An example is the relationship between Student and Marks_Details. Consider the following relationship:
Hibernate One-To-Many Mapping Using Java Annotations Tutorial with Examples

According to the relationship each Student can have a any number of marks_Details. But each marks_Details will be associated with only one Student. Hence we will need two tables namely STUDENT and MARKS_DETAILS to create this relation. In Hibernate, one-to-many relationship between entities can be created by 2 different techniques. These techniques are:
  1. Using foreign key association:

    In this association, we can have a foreign key column in MARKS_DETAILS table i.e student_id. This column will refer to primary key of STUDENT table. This way no two Marks Details can be associated with multiple students. Obviously, Marks Details needs to be unique for enforcing this restriction. The example below in this post demonstrates this asscociation.
  2. Using a common join table:

    In this association, we can have a common join table lets say STUDENT_MARKS_DETAILS. This table will have two column i.e. student_id which will be foreign key referring to primary key in STUDENT table and similarly MARKSID which will be foreign key referring to primary key of MARKS_DETAILS table.

Creating Database

Before we start lets create a simple database and table to apply hibernate operations on. Copy and Paste the following sql query in your query editor and execute.
CREATE table STUDENT (student_id int identity NOT NULL PRIMARY KEY,
rollno varchar(20),
firstname varchar(50),
lastname varchar(50),
course varchar(50))

CREATE TABLE STUDENT_MARKS_DETAILS (student_id int NOT NULL PRIMARY KEY FOREIGN KEY REFERENCES STUDENT (student_id),
test_id int NOT NULL identity,
subject varchar(100) DEFAULT NULL,
max_marks varchar(100) DEFAULT NULL,
marks_obtained varchar(100) DEFAULT NULL,
result varchar(100) DEFAULT NULL
)




NOTE : Above script is written for SQL Server, you can change accordingly for different DB.

Adding Hibernate Jars

Download latest Hibernate jars from here http://hibernate.org/ and add to your classpath.
Create Model Classes As a next step let’s create the model classes Student.java and StudentMarksDetails.java using Annotations.
The contents of the model classes are as below
Student.java
package com.tutorialsdesk.hibernate.bean;

import java.io.Serializable;
import java.util.Set;

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.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
@Entity
@Table(name="STUDENT",uniqueConstraints = { @UniqueConstraint(columnNames = "student_id") })

public class Student implements Serializable {

private static final long serialVersionUID = 5502738307095121008L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "student_id")
private int id;

@Column(name="rollno")
private String rollno;

@Column(name="firstname")
private String firstname;

@Column(name="lastname")
private String lastname;

@Column(name="course")
private String course;

// @OneToOne(cascade = CascadeType.ALL)
//@PrimaryKeyJoinColumn
//private StudentAddress address;

@OneToMany(mappedBy = "student")
private Set<StudentMarksDetails> marksDetails;


public Student(){

}

public Student(String rollno, String firstname, String lastname,
String course, StudentAddress address) {
super();
this.rollno = rollno;
this.firstname = firstname;
this.lastname = lastname;
this.course = course;
//this.address = address;
}



public int getId() {
return id;
}

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

public String getRollno() {
return rollno;
}

public void setRollno(String rollno) {
this.rollno = rollno;
}

public String getFirstname() {
return firstname;
}

public void setFirstname(String firstname) {
this.firstname = firstname;
}

public String getLastname() {
return lastname;
}

public void setLastname(String lastname) {
this.lastname = lastname;
}

public String getCourse() {
return course;
}

public void setCourse(String course) {
this.course = course;
}

/*public StudentAddress getAddress() {
return address;
}

public void setAddress(StudentAddress address) {
this.address = address;
}
*/
public Set<StudentMarksDetails> getMarksDetails() {
return marksDetails;
}

public void setMarksDetails(Set<StudentMarksDetails> marksDetails) {
this.marksDetails = marksDetails;
}



}

StudentMarksDetails.java
package com.tutorialsdesk.hibernate.bean;

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

@Entity
@Table(name = "STUDENT_MARKS_DETAILS")
public class StudentMarksDetails {

@Id
@GeneratedValue
@Column(name = "test_id")
private long testId;

@Column(name = "subject")
private String subject;

@Column(name = "max_marks")
private String maxMarks;

@Column(name = "marks_obtained")
private String marksObtained;

@Column(name = "result")
private String result;

@ManyToOne
@JoinColumn(name = "student_id")
private Student student;

public StudentMarksDetails() {
}

public StudentMarksDetails(String subject, String maxMarks, String marksObtained,
String result) {
this.subject = subject;
this.maxMarks = maxMarks;
this.marksObtained = marksObtained;
this.result = result;
}

public long getTestId() {
return testId;
}

public void setTestId(long testId) {
this.testId = testId;
}

public String getSubject() {
return subject;
}

public void setSubject(String subject) {
this.subject = subject;
}

public String getMaxMarks() {
return maxMarks;
}

public void setMaxMarks(String maxMarks) {
this.maxMarks = maxMarks;
}

public String getMarksObtained() {
return marksObtained;
}

public void setMarksObtained(String marksObtained) {
this.marksObtained = marksObtained;
}

public String getResult() {
return result;
}

public void setResult(String result) {
this.result = result;
}

public Student getStudent() {
return student;
}

public void setStudent(Student student) {
this.student = student;
}

}

Adding Hibernate Configuration file

The hibernate.cfg.xml is as follows:
<?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="hibernate.connection.driver_class">net.sourceforge.jtds.jdbc.Driver</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.connection.url">jdbc:jtds:sqlserver://localhost:1433/yourdbname</property>
<property name="hibernate.connection.username">username</property>
<property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
<property name="connection.pool_size">1</property>
<property name="hbm2ddl.auto">create</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<mapping class="com.tutorialsdesk.hibernate.bean.Student"/>
<mapping class="com.tutorialsdesk.hibernate.bean.StudentMarksDetails"/>
<!-- <mapping class="com.tutorialsdesk.hibernate.bean.StudentAddress"/> -->
</session-factory>
</hibernate-configuration>

In the above file we have set the database connection to SQL Server database . The show_sql option, if set to true will display all the executed SQL queries on the console. The property hbm2ddl.auto , if set to create, creates the schema, destroying the previous data.

Note : In case you want to use any other database then, you need to change these properties – “dialect”, “connection.driver_class”, “connection.url”, “connection.username”, and “connection.password”.

Also we have added the Annotation based entity classes Student.java and StudentMarksDetails.java to the above file.

Create Utility class

Next, we will write a utility class to take care of Hibernate start up and retrieve the session easily. We will write the file HibernateUtil.java as below:
package com.tutorialsdesk.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;


public class HibernateUtil {

private static final SessionFactory sessionFactory = buildSessionFactory();

private static SessionFactory buildSessionFactory() {
try {
return new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}

public static SessionFactory getSessionFactory() {
return sessionFactory;
}

public static void shutdown() {
getSessionFactory().close();
}


}


Main AnnotationTest class

This class tests the one-to-one relationship by creating and listing the student details and corresponding addresses as below:
package com.tutorialsdesk.hibernate;

import java.util.ArrayList;
import java.util.Set;

import org.hibernate.*;

import com.tutorialsdesk.hibernate.bean.Student;
import com.tutorialsdesk.hibernate.bean.StudentAddress;
import com.tutorialsdesk.hibernate.bean.StudentMarksDetails;

public class AnnotationTest {
public static void main(String[] args) {

AnnotationTest test=new AnnotationTest();
StudentAddress sa1 = new StudentAddress("C-42","Noida","UP","IN");
StudentAddress sa2 = new StudentAddress("D-61","Agra","UP","IN");
Student s1=new Student("CS1","Ankit","Yadav","MCA",sa1);
Student s2=new Student("CS2","Rahul","Jena","B.Tech",sa1);
StudentMarksDetails marksDetails1 = new StudentMarksDetails("Maths", "100", "87","Passed");
StudentMarksDetails marksDetails2 = new StudentMarksDetails("Science", "100", "90","Passed");
StudentMarksDetails marksDetails3 = new StudentMarksDetails("English", "100", "85","Passed");
StudentMarksDetails marksDetails4 = new StudentMarksDetails("Maths", "100", "87","Passed");
StudentMarksDetails marksDetails5 = new StudentMarksDetails("Science", "100", "90","Passed");
StudentMarksDetails marksDetails6 = new StudentMarksDetails("English", "100", "85","Passed");

marksDetails1.setStudent(s1);
marksDetails2.setStudent(s1);
marksDetails3.setStudent(s1);
marksDetails4.setStudent(s2);
marksDetails5.setStudent(s2);
marksDetails6.setStudent(s2);


sa1.setStudent(s1);
//s1.setAddress(sa1);

sa2.setStudent(s2);
//s2.setAddress(sa2);


test.saveStudent(s1);
test.saveStudent(s2);

test.saveMarks(marksDetails1);
test.saveMarks(marksDetails2);
test.saveMarks(marksDetails3);
test.saveMarks(marksDetails4);
test.saveMarks(marksDetails5);
test.saveMarks(marksDetails6);

test.getStudent();
System.out.println("successfully saved");

}
public void saveStudent(Student student) {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();

session.save(student);

session.getTransaction().commit();

}
public void saveMarks(StudentMarksDetails marksDetails) {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();

session.save(marksDetails);

session.getTransaction().commit();

}
public void updateStudent(Student student) {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();

session.merge(student);

session.getTransaction().commit();
}

public void deleteStudent(Student student) {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();

session.delete(student);

session.getTransaction().commit();
}

public void getStudent() {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();

@SuppressWarnings("unchecked")
ArrayList<Student> list = (ArrayList<Student>) session.createQuery("from Student").list();
if (list != null) {
for (int i = 0; i < list.size(); i++) {
System.out.println("User ID : " + list.get(i).getId());
System.out.println("User First Name : "+ list.get(i).getFirstname());
System.out.println("User Last Name : "+ list.get(i).getLastname());
System.out.println("User Roll No : " + list.get(i).getRollno());
System.out.println("User Course : " + list.get(i).getCourse());
// System.out.println("User Address : " + list.get(i).getAddress().getAddress() + ","+ list.get(i).getAddress().getCity() +"\n"+ list.get(i).getAddress().getState() +"\n"+ list.get(i).getAddress().getCountry());

}
}
session.getTransaction().commit();
}

}

Hibernate One-To-Many Mapping Using Java Annotations Tutorial with Examples

Hope we are able to explain you Hibernate One-To-Many Mapping Using Java Annotations, if you have any questions or suggestions please write to us using contact us form.(Second Menu from top left).

Please share us on social media if you like the tutorial.

Source:http://www.tutorialsdesk.com/2014/11/hibernate-one-to-many-mapping-using.html

Tidak ada komentar:

Posting Komentar