Basic Hibernate Example with XML Configuration - onlinetutorialspoint

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorials we are going to see how to implement a basic hibernate application with xml based configuration.
Technologies :
Hibernate-core 5.0
Mysql 5.5.43
NetBeans 8.o
mysql> create database onlinetutorialspoint;

mysql> use onlinetutorialspoint;
Create a student table in onlinetutorialspoint databse.
CREATE TABLE `student` (
`id` INT(10) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NULL DEFAULT NULL,
`rollnumber` INT(10) NULL DEFAULT NULL,
`gender` TINYINT(4) NULL DEFAULT NULL,
`class` VARCHAR(50) NULL DEFAULT NULL,
`lastupdated` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
);
pom.xml
<project>     
    <dependencies>         
        <dependency>             
            <groupId>org.hibernate</groupId>             
            <artifactId>hibernate-core</artifactId>             
            <version>5.0.0.CR1</version>         
        </dependency>         <!-- for JPA, use hibernate-entitymanager instead of hibernate-core -->         
        <dependency>             
            <groupId>org.hibernate</groupId>             
            <artifactId>hibernate-entitymanager</artifactId>             
            <version>4.1.8.Final</version>         
        </dependency>         
        <dependency>             
            <groupId>unknown.binary</groupId>             
            <artifactId>mysql-connector-java-5.1.23-bin</artifactId>             
            <version>SNAPSHOT</version>         
        </dependency>         
        <dependency>             
            <groupId>commons-codec</groupId>             
            <artifactId>commons-codec</artifactId>             
            <version>1.2</version>         
        </dependency>     
    </dependencies> 
</project>
Create HibernateConnector.java, it is responsible to generate singleton session factory objects.
package com.onlinetutorialspoint.config;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateConnector {

private static HibernateConnector me;
private Configuration cfg;
private SessionFactory sessionFactory;

private HibernateConnector() throws HibernateException {

// build the config
cfg = new Configuration();

/**
* Connection Information..
*/
cfg.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
cfg.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/onlinetutorialspoint");
cfg.setProperty("hibernate.connection.username", "root");
cfg.setProperty("hibernate.connection.password", "123456");
cfg.setProperty("hibernate.show_sql", "true");

/**
* Mapping Resources..
*/
cfg.addResource("com/onlinetutorialspoint/pojo/Student.hbm.xml");

sessionFactory = cfg.buildSessionFactory();
}

public static synchronized HibernateConnector getInstance() throws HibernateException {
if (me == null) {
me = new HibernateConnector();
}

return me;
}

public Session getSession() throws HibernateException {
Session session = sessionFactory.openSession();
if (!session.isConnected()) {
this.reconnect();
}
return session;
}

private void reconnect() throws HibernateException {
this.sessionFactory = cfg.buildSessionFactory();
}
}
Create Pojo class with respect the student table.
Student.java
package com.onlinetutorialspoint.pojo;

import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "student", catalog = "onlinetutorialspoint"
)
public class Student implements java.io.Serializable {

private Integer id;
private String name;
private Integer rollnumber;
private Byte gender;
private String class_;
private Date lastupdated;

public Student() {
}

public Student(String name, Integer rollnumber, Byte gender, String class_, Date lastupdated) {
this.name = name;
this.rollnumber = rollnumber;
this.gender = gender;
this.class_ = class_;
this.lastupdated = lastupdated;
}

@Id
@GeneratedValue(strategy = IDENTITY)

@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}

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

@Column(name = "name", length = 50)
public String getName() {
return this.name;
}

public void setName(String name) {
this.name = name;
}

@Column(name = "rollnumber")
public Integer getRollnumber() {
return this.rollnumber;
}

public void setRollnumber(Integer rollnumber) {
this.rollnumber = rollnumber;
}

@Column(name = "gender")
public Byte getGender() {
return this.gender;
}

public void setGender(Byte gender) {
this.gender = gender;
}

@Column(name = "class", length = 50)
public String getClass_() {
return this.class_;
}

public void setClass_(String class_) {
this.class_ = class_;
}

}
Create hbm file with respect to student.java and student table.
Student.hbm.xml
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping>     
    <class name="com.onlinetutorialspoint.pojo.Student" table="student" catalog="onlinetutorialspoint">         
        <id name="id" type="java.lang.Integer">             
            <column name="id" />             
            <generator class="identity" />         
        </id>         
        <property name="name" type="string">             
            <column name="name" length="50" />         
        </property>         
        <property name="rollnumber" type="java.lang.Integer">             
            <column name="rollnumber" />         
        </property>         
        <property name="gender" type="java.lang.Byte">             
            <column name="gender" />         
        </property>         
        <property name="class_" type="string">             
            <column name="class" length="50" />         
        </property>     
    </class> 
</hibernate-mapping>
Create StudentDAO.java to access the Student details.

package com.onlinetutorialspoint.dao;

import com.onlinetutorialspoint.config.HibernateConnector;
import com.onlinetutorialspoint.pojo.Student;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class StudentDAO {

public List<Student> listStudent() {
Session session = null;
try {
session = HibernateConnector.getInstance().getSession();
Query query = session.createQuery("from Student s");

List queryList = query.list();
if (queryList != null && queryList.isEmpty()) {
return null;
} else {
System.out.println("list " + queryList);
return (List<Student>) queryList;
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
session.close();
}
}

public Student findStudentById(int id) {
Session session = null;
try {
session = HibernateConnector.getInstance().getSession();
Query query = session.createQuery("from Student s where s.id = :id");
query.setParameter("id", id);

List queryList = query.list();
if (queryList != null && queryList.isEmpty()) {
return null;
} else {
return (Student) queryList.get(0);
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
session.close();
}
}

public void updateStudent(Student student) {
Session session = null;
try {
session = HibernateConnector.getInstance().getSession();
session.saveOrUpdate(student);
session.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
}

public Student addStudent(Student student) {
Session session = null;
Transaction transaction = null;
try {
session = HibernateConnector.getInstance().getSession();
transaction = session.beginTransaction();
session.save(student);
transaction.commit();
return student;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
session.close();
}
}

public void deleteStudent(int id) {
Session session = null;
try {
session = HibernateConnector.getInstance().getSession();
Transaction beginTransaction = session.beginTransaction();
Query createQuery = session.createQuery("delete from Student s where s.id =:id");
createQuery.setParameter("id", id);
createQuery.executeUpdate();
beginTransaction.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
}

}

package com.onlinetutorialspoint.service;

import com.onlinetutorialspoint.dao.StudentDAO;
import com.onlinetutorialspoint.pojo.Student;
import java.util.List;

public class DbOperations {

StudentDAO studentDAO = new StudentDAO();

public static void main(String[] args) {
DbOperations dbOperations = new DbOperations();
Student createStudent = dbOperations.createStudent();

List<Student> studentList = dbOperations.getStudentList();
if (studentList != null) {
for (Student student : studentList) {
System.out.println("Student Name : " + student.getName());
}
}
dbOperations.updateStudent(createStudent.getId());
Student student = dbOperations.getStudent(createStudent.getId());
if (student != null) {
System.out.println("Student Details After Updation : " + student.getName());
}

dbOperations.deleteStudent(createStudent.getId());

}

public Student createStudent() {
Student s = new Student();
s.setGender(new Byte("1"));
s.setName("John");
s.setClass_("12");
s.setRollnumber(007);
studentDAO.addStudent(s);
return s;
}

public void updateStudent(Integer id) {
Student student = studentDAO.findStudentById(id);
student.setName("online tutorials point");
studentDAO.updateStudent(student);
System.out.println("Student Updated Success");
}

public void deleteStudent(Integer id) {
studentDAO.deleteStudent(id);
System.out.println("Student Deleted Success");
}

public List<Student> getStudentList() {
return studentDAO.listStudent();
}

public Student getStudent(Integer id) {
return studentDAO.findStudentById(id);
}

}
Output :
Student Name : John
Student Updated Success
Student Details After Updation : online tutorials point
Student Deleted Success
Happy Learning 🙂


HibernateMaven

File size: 781 KB
Downloads: 2315


Hibernate Filter Example Xml Configuration
Hibernate 4 Example with Annotations Mysql
hibernate update query example
hbm2ddl.auto Example in Hibernate XML Config
Hibernate session differences between load() and get()
One to One Mapping in Hibernate using foreign key (XML)
Hibernate One To Many Example (XML Mapping)
Hibernate One to One Mapping using primary key (XML)
Hibernate cache first level example
Hibernate Composite Key Mapping Example
Hibernate Many to Many Mapping Example (XML)
Difference between update vs merge in Hibernate example
Hibernate Native SQL Query Example
Different types of Object States in Hibernate
Singleton Hibernate SessionFactory Example

Hibernate Filter Example Xml Configuration
Hibernate 4 Example with Annotations Mysql
hibernate update query example
hbm2ddl.auto Example in Hibernate XML Config
Hibernate session differences between load() and get()
One to One Mapping in Hibernate using foreign key (XML)
Hibernate One To Many Example (XML Mapping)
Hibernate One to One Mapping using primary key (XML)
Hibernate cache first level example
Hibernate Composite Key Mapping Example
Hibernate Many to Many Mapping Example (XML)
Difference between update vs merge in Hibernate example
Hibernate Native SQL Query Example
Different types of Object States in Hibernate
Singleton Hibernate SessionFactory Example






santosh miriyala
November 21, 2017 at 1:25 pm - Reply 

Good article chandrashekhar. Post more articles to perform join using criteria queries.










santosh miriyala
November 21, 2017 at 1:25 pm - Reply 

Good article chandrashekhar. Post more articles to perform join using criteria queries.




Good article chandrashekhar. Post more articles to perform join using criteria queries.
 


Δ
 Hibernate – Introduction
 Hibernate – Advantages
 Hibernate – Download and Setup
 Hibernate – Sql Dialect list
 Hibernate – Helloworld – XML
 Hibernate – Install Tools in Eclipse
 Hibernate – Object States
 Hibernate – Helloworld – Annotations
 Hibernate – One to One Mapping – XML
 Hibernate – One to One Mapping foreign key – XML
 Hibernate – One To Many -XML
 Hibernate – One To Many – Annotations
 Hibernate – Many to Many Mapping – XML
 Hibernate – Many to One – XML
 Hibernate – Composite Key Mapping
 Hibernate – Named Query
 Hibernate – Native SQL Query
 Hibernate – load() vs get()
 Hibernate Criteria API with Example
 Hibernate – Restrictions
 Hibernate – Projection
 Hibernate – Query Language (HQL)
 Hibernate – Groupby Criteria HQL
 Hibernate – Orderby Criteria
 Hibernate – HQLSelect Operation
 Hibernate – HQL Update, Delete
 Hibernate – Update Query
 Hibernate – Update vs Merge
 Hibernate – Right Join
 Hibernate – Left Join
 Hibernate – Pagination
 Hibernate – Generator Classes
 Hibernate – Custom Generator
 Hibernate – Inheritance Mappings
 Hibernate – Table per Class
 Hibernate – Table per Sub Class
 Hibernate – Table per Concrete Class
 Hibernate – Table per Class  Annotations
 Hibernate – Stored Procedures
 Hibernate – @Formula Annotation
 Hibernate – Singleton SessionFactory
 Hibernate – Interceptor
 hbm2ddl.auto Example in Hibernate XML Config
 Hibernate – First Level Cache