CRUD Operation Example
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<!-- Assume hibernatedb as the database name -->
<property name="hibernate.connection.url">
jdbc:mysql://localhost/hibernatedb
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">
root
</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">
true
</property>
<!-- Drop and re-create the
database schema on startup -->
<property name="hbm2ddl.auto">
update
</property>
<!-- List of class mapping files -->
<mapping class="com.tkhts.Student"/>
</session-factory>
</hibernate-configuration>
package com.tkhts;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
/*This annotation will create
table in database with name Student*/
@Entity
public class Student
{
@Id @GeneratedValue(strategy=GenerationType.AUTO)
/**This variable store the student id*/
private Long studentId;
/** This variable store the student name*/
private String studentName;
public Long getStudentId() {
return studentId;
}
public void setStudentId(Long studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
@Override
public String toString() {
return "Student [studentName="
+ studentName + "]";
}
}
package com.tkhts.test;
import org.apache.log4j.chainsaw.Main;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.tkhts.Student;
public class Test {
private static SessionFactory sesssionFactory;
public static void main(String args[]){
sesssionFactory = new
Configuration().configure()
.buildSessionFactory();
Session session =
sessionfactory.openSession();
session.beginTransaction();
/*inserting data into database*/
for(long i=1;i<=10;i++)
{
Student student=new Student();
student.setStudentName("student "+i);
session.save(student);
}
session.getTransaction().commit();
session.close();
/*reading data from database*/
session = sessionfactory.openSession();
session.beginTransaction();
for(long i=1;i<=10;i++)
{
Student student=
(Student)session.get(Student.class,i);
System.out.println
("student name =
"+student.getStudentName());
}
session.getTransaction().commit();
session.close();
/*updating data in a table*/
session = sessionfactory.openSession();
session.beginTransaction();
Student student=(Student)session.load(Student.class,1L);
student.setStudentName("updated student");
/* This method update the row in the table*/
session.update(student);
session.getTransaction().commit();
session.close();
System.out.println("student name updated...");
/*deleting row from a table*/
session = sessionfactory.openSession();
session.beginTransaction();
student=(Student)session.load(Student.class,2L);
/** This method delete the
row from the table*/
session.delete(student);
session.getTransaction().commit();
session.close();
}
}
@Embeddable and @Embedded Example
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name=
"hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<!-- Assume hibernatedb as the database name -->
<property name="hibernate.connection.url">
jdbc:mysql://localhost/hibernatedb
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">
root
</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">
true
</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">
create
</property>
<!-- List of class mapping files -->
<mapping class="com.tkhts.Student"/>
<mapping class="com.tkhts.StudentAddress"/>
</session-factory>
</hibernate-configuration>
package com.tkhts;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @Entity annotation will create table
* in database with name StudentDTO
* and with field name studentId and
* studentName both fields are instance variable
* of this class
* @Id create's the primary key like studentId
* in this class
* @GeneratedValue annotation generate the
* studentId number automatically
*/
@Entity
@Table(name="STUDENT_TABLE")
public class Student {
@Id @GeneratedValue(strategy=GenerationType.AUTO)
private Long studentId;
private String studentName;
@Embedded
private StudentAddress address;
public StudentAddress getAddress() {
return address;
}
public void setAddress(StudentAddress address) {
this.address = address;
}
public Long getStudentId() {
return studentId;
}
public void setStudentId(Long studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
}
package com.tkhts;
import javax.persistence.Embeddable;
@Embeddable
public class StudentAddress {
private String city;
private String state;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
package com.tkhts.test;
import net.sf.ehcache.hibernate.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.tkhts.StudentAddress;
import com.tkhts.Student;
public class HibernateTest {
/**
* This class has a main method
* which opens a session
* and inserting the value to
* the table in database.
*/
public static void main(String[] args) {
Student student=new Student();
student.setStudentName("first user");
StudentAddress address=new StudentAddress();
address.setCity("delhi");
address.setState("UP");
student.setAddress(address);
SessionFactory sesssionFactory= new
Configuration().configure().buildSessionFactory();
//create the session
Session session=sesssionFactory.openSession();
session.beginTransaction();
session.save(student);
session.getTransaction().commit();
//commit or rollBack the transaction
session.close();
System.out.println("record added...") ;
}
}
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.php#StaticLoggerBinder for further details. Hibernate: insert into STUDENT_TABLE (city, state, studentName) values (?, ?, ?) record added...
Inheritance Example
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name=
"hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<!-- Assume hibernatedb as the database name -->
<property name="hibernate.connection.url">
jdbc:mysql://localhost/hibernatedb
</property>
<property name=
"hibernate.connection.username">
root
</property>
<property name=
"hibernate.connection.password">
root
</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">
true
</property>
<!-- Drop and re-create the
database schema on startup -->
<property name="hbm2ddl.auto">
create
</property>
<!-- List of class mapping files -->
<mapping class="com.tkhts.Account"/>
<mapping class="com.tkhts.CurrentAccount"/>
<mapping class="com.tkhts.SavingAccount"/>
</session-factory>
</hibernate-configuration>
package com.tkhts;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Account {
@Id @GeneratedValue(strategy=GenerationType.AUTO)
private Integer acountId;
private String customerName;
private Integer accountNo;
public Integer getAccountNo() {
return accountNo;
}
public void setAccountNo(Integer accountNo) {
this.accountNo = accountNo;
}
public Integer getAcountId() {
return acountId;
}
public void setAcountId(Integer acountId) {
this.acountId = acountId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
}
package com.tkhts;
import javax.persistence.Entity;
@Entity
public class CurrentAccount extends Account{
private Integer rateOfInterest;
public Integer getRateOfInterest() {
return rateOfInterest;
}
public void setRateOfInterest
(Integer rateOfInterest) {
this.rateOfInterest = rateOfInterest;
}
}
package com.tkhts;
import javax.persistence.Entity;
@Entity
public class SavingAccount extends Account{
private Integer rateOfInterest;
public Integer getRateOfInterest() {
return rateOfInterest;
}
public void setRateOfInterest
(Integer rateOfInterest) {
this.rateOfInterest = rateOfInterest;
}
}
package com.tkhts.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.tkhts.Account;
import com.tkhts.CurrentAccount;
import com.tkhts.SavingAccount;
/**
* This class has a main method which opens a session,
* create database and inserts the value to the table
* in database
* @author shalabh
*/
public class HibernateTest {
public static void main(String[] args) {
Account account=new Account();
account.setCustomerName("customer first");
account.setAccountNo(1001);
SavingAccount savingAccount =
new SavingAccount();
savingAccount.setRateOfInterest(5);
CurrentAccount currentAccount=
new CurrentAccount();
currentAccount.setRateOfInterest(3);
/**
* creating the Session object to start the new
* session to perform the operation
*/
SessionFactory sesssionFactory=
new Configuration()
.configure().buildSessionFactory();
Session session=sesssionFactory.openSession();
/** this begins a new transaction */
session.beginTransaction();
/** this save the object */
session.save(account);
session.save(savingAccount);
session.save(currentAccount);
/**this commits the transaction*/
session.getTransaction().commit();
/** close the session*/
session.close();
System.out.println("record added...") ;
}
}
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.php#StaticLoggerBinder for further details. Hibernate: insert into Account (accountNo, customerName, DTYPE) values (?, ?, 'Account') Hibernate: insert into Account (accountNo, customerName, rateOfInterest, DTYPE) values (?, ?, ?, 'SavingAccount') Hibernate: insert into Account (accountNo, customerName, rateOfInterest, DTYPE) values (?, ?, ?, 'CurrentAccount') record added...
One To One Relationship Example
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name=
"hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<!-- Assume hibernatedb as the database name -->
<property name="hibernate.connection.url">
jdbc:mysql://localhost/hibernatedb
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">
root
</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">
true
</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">
create
</property>
<!-- List of class mapping files -->
<mapping class="com.tkhts.Student"/>
<mapping class="com.tkhts.Course"/>
</session-factory>
</hibernate-configuration>
package com.tkhts;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
@Entity
public class Student {
@Id @GeneratedValue(strategy=GenerationType.AUTO)
private Long studentId;
private String studentName;
@OneToOne //use for one to one relation
@JoinColumn(name="course_id")
private Course course;
public Course getCourse() {
return course;
}
public void setCourse(Course course) {
this.course = course;
}
public Long getStudentId() {
return studentId;
}
public void setStudentId(Long studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
}
package com.tkhts;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Course {
@Id @GeneratedValue(strategy=GenerationType.AUTO)
private int coueseId;
private String courseName;
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public int getCoueseId() {
return coueseId;
}
public void setCoueseId(int coueseId) {
this.coueseId = coueseId;
}
}
package com.tkhts.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.tkhts.Course;
import com.tkhts.Student;
public class HibernateTest {
public static void main(String[] args) {
Student student=new Student();
student.setStudentName("first user");
Course course=new Course();
course.setCourseName("MCA");
student.setCourse(course);
SessionFactory sesssionFactory= new
Configuration().configure()
.buildSessionFactory();
Session session=sesssionFactory.openSession();
//create the session
session.beginTransaction();
session.save(student);
session.save(course);
session.getTransaction().commit();
//commit or rollBack the transaction
session.close();
System.out.println("record added...") ;
}
}
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.php#StaticLoggerBinder for further details. Hibernate: insert into Student (course_id, studentName) values (?, ?) Hibernate: insert into Course (courseName) values (?) Hibernate: update Student set course_id=?, studentName=? where studentId=? record added...
One To many And Many To One Relationship Example
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name=
"hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<!-- Assume hibernatedb as the database name -->
<property name="hibernate.connection.url">
jdbc:mysql://localhost/hibernatedb
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">
root
</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">
true
</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">
create
</property>
<!-- List of class mapping files -->
<mapping class="com.tkhts.Student"/>
<mapping class="com.tkhts.Address"/>
</session-factory>
</hibernate-configuration>
package com.tkhts;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.BatchSize;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
@Entity
@Table(name="student")
public class Student {
@Id
@GeneratedValue
private int id;
private String studentName;
@OneToMany
private List
address = new ArrayList();
public List getAddress() {
return address;
}
public void setAddress(List address) {
this.address = address;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
package com.tkhts;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
@Entity
public class Address {
@Id
@GeneratedValue
private int Id;
private String city;
private String state;
@ManyToOne
private Student student;
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public int getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
package com.tkhts.test;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.tkhts.Address;
import com.tkhts.Student;
public class Test {
public static void main(String[] args) {
Student student=new Student();
student.setStudentName("peter");
Address residentialAddress = new Address();
residentialAddress.setCity("mumbai");
residentialAddress.setState("maharashtra");
residentialAddress.setStudent(student);
Address collegeAddress = new Address();
collegeAddress.setCity("ahmedabad");
collegeAddress.setState("gujarat");
collegeAddress.setStudent(student);
student.getAddress().add(residentialAddress);
student.getAddress().add(collegeAddress);
SessionFactory sessionfactory = new
Configuration().configure()
.buildSessionFactory();
Session session = sessionfactory.openSession();
session.beginTransaction();
session.save(student);
session.save(residentialAddress);
session.save(collegeAddress);
session.getTransaction().commit();
session.close();
}
}
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.php#StaticLoggerBinder for further details. Hibernate: insert into student (studentName) values (?) Hibernate: insert into Address (city, state, student_id) values (?, ?, ?) Hibernate: insert into Address (city, state, student_id) values (?, ?, ?) Hibernate: insert into student_Address (student_id, address_Id) values (?, ?) Hibernate: insert into student_Address (student_id, address_Id) values (?, ?)
Many To Many Relationship Example
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name=
"hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<!-- Assume hibernatedb as the database name -->
<property name="hibernate.connection.url">
jdbc:mysql://localhost/hibernatedb
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">
root
</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">
true
</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">
create
</property>
<!-- List of class mapping files -->
<mapping class="com.tkhts.Student"/>
<mapping class="com.tkhts.Teacher"/>
</session-factory>
</hibernate-configuration>
package com.tkhts;
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
@Entity
public class Student {
@Id @GeneratedValue(strategy=GenerationType.AUTO)
private Long studentId;
private String studentName;
/**
* This annotation tell hibernate that this
* is many to many relationship mapping
*/
@ManyToMany(mappedBy="student")
private Collection teacher=new ArrayList();
public Collection getTeacher() {
return teacher;
}
public void setTeacher(Collection teacher) {
this.teacher = teacher;
}
public Long getStudentId() {
return studentId;
}
public void setStudentId(Long studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
}
package com.tkhts;
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
@Entity
public class Teacher {
@Id @GeneratedValue
(strategy=GenerationType.AUTO)
private int teacherId;
private String teacherName;
/**
* This annotation tell hibernate
* that this is many to
* many relationship mapping
*/
@ManyToMany
/**
* This annotation create the joinTable name and
* JoinColumn name user define
*/
@JoinTable(joinColumns=
@JoinColumn(name="TEACHER_ID"),
inverseJoinColumns=@JoinColumn
(name="STUDENT_ID"))
/** student is a ArrayList that
store the list of students*/
private Collection student=new ArrayList();
public Collection getStudent() {
return student;
}
public void setStudent(Collection student) {
this.student = student;
}
public int getTeacherId() {
return teacherId;
}
public void setTeacherId(int teacherId) {
teacherId = teacherId;
}
public String getTeacherName() {
return teacherName;
}
public void setTeacherName
(String teacherName) {
teacherName = teacherName;
}
}
package com.tkhts.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.tkhts.Student;
import com.tkhts.Teacher;
/**
* This class has a main method which opens a session,
* create database and inserts the value to the table in
* database
*
* @author shalabh
*/
public class HibernateTest {
public static void main(String[] args) {
Teacher teacher1=new Teacher();
teacher1.setTeacherName("first teacher");
Teacher teacher2=new Teacher();
teacher2.setTeacherName("second teacher");
Student student1=new Student();
student1.setStudentName("first student");
Student student2=new Student();
student2.setStudentName("second student");
teacher1.getStudent().add(student1);
teacher2.getStudent().add(student2);
student1.getTeacher().add(teacher1);
student2.getTeacher().add(teacher2);
/**
* creating the Session object to start the new
* session to perform the operation
*/
SessionFactory sessionfactory =
new Configuration().configure()
.buildSessionFactory();
Session session=sessionfactory.openSession();
session.beginTransaction();
session.save(student1);
session.save(student2);
session.save(teacher1);
session.save(teacher2);
session.getTransaction().commit();
session.close();
System.out.println("record added...") ;
}
}
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.php#StaticLoggerBinder for further details. Hibernate: insert into Student (studentName) values (?) Hibernate: insert into Student (studentName) values (?) Hibernate: insert into Teacher (teacherName) values (?) Hibernate: insert into Teacher (teacherName) values (?) Hibernate: insert into Teacher_Student (TEACHER_ID, STUDENT_ID) values (?, ?) Hibernate: insert into Teacher_Student (TEACHER_ID, STUDENT_ID) values (?, ?) record added...


