
- Hibernate - Home
- ORM - Overview
- Hibernate - Overview
- Hibernate - Architecture
- Hibernate - Environment
- Hibernate - Configuration
- Hibernate - Sessions
- Hibernate - Persistent Class
- Hibernate - Mapping Files
- Hibernate - Mapping Types
- Hibernate - Examples
- Hibernate - O/R Mappings
- Hibernate - Cascade Types
- Hibernate - Annotations
- Hibernate - Query Language
- Hibernate - Criteria Queries
- Hibernate - Native SQL
- Hibernate - Caching
- Hibernate - Entity Lifecycle
- Hibernate - Batch Processing
- Hibernate - Interceptors
- Hibernate - ID Generator
- Hibernate - Saving Image
- Hibernate - log4j Integration
- Hibernate - Spring Integration
- Hibernate - Struts 2 Integration
- Hibernate - Web Application
- Mapping Table Examples
- Hibernate - Table Per Hiearchy
- Hibernate - Table Per Concrete Class
- Hibernate - Table Per Subclass
Hibernate - Spring Integration
Spring is an open-source framework for building enterprise-level Java applications. Spring has an applicationContext.xml file. We will use this file to provide all information including database configuration. Since database configuration is included in hibernate.cfg.xml in Hibernate, we will not need it anymore.
In Hibernate, we use StandardServiceRegistry, MetadataSources, SessionFactory to get Session, Transaction. Spring framework provides a HibernateTemplate class, where you just have to call save method to persist in database. HibernateTemplate class resides in org.springframework.orm.hibernate3 package.
Syntax
// create a new student object Student s1 = new Student( 111, "Karan", "Physics"); // save the student object in database using HibernateTemplate instance hibernateTemplate.persist(s1);
Required Libraries
For using HibernateTemplate, you will need the jar file from https://mvnrepository.com/artifact/org.springframework/spring-hibernate3/2.0.8
You will need spring-dao jar from https://mvnrepository.com/artifact/org.springframework/spring-dao/2.0.3
You will also need to put Hibernate-core jar in your CLASSPATH.
Useful Methods of HibernateTemplate Class
Following is the list of important methods of HibernateTemplate Class:
Sr.No. | Method & Description |
---|---|
1 |
void persist(Object entity) Saves the object to the mapped table in database. |
2 |
Serializable save(Object entity) Saves the object to the mapped table record in database and returns id. |
3 |
void saveOrUpdate(Object entity) Saves or Updates the table mapped to the object. If id is entered, it updates the record otherwise saves. |
4 |
void update(Object entity) Updates the table mapped to the object. |
5 |
void delete(Object entity) Deletes the given object mapped to the table in database on the basis of id. |
Example
Let's discuss Spring Hibernate Integration in details with an example.
Create Mapping Class
Let's create the POJO class whose data is to be persisted in the database.
Student.java
package com.tutorialspoint; public class Student { private long id; private String name; private String dept; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDept() { return dept; } public void setDept(String dept) { this.dept = dept; } }
Create DAO Class
Create the DAO class which will be using HibernateTemplate class to create, update and delete student object.
StudentDAO.java
package com.tutorialspoint; import org.springframework.orm.hibernate3.HibernateTemplate; public class StudentDAO{ HibernateTemplate template; public void setTemplate(HibernateTemplate template) { this.template = template; } public void saveStudent(Student s){ template.save(s); } public void updateStudent(Student s){ template.update(s); } public void deleteStudent(Student s){ template.delete(s); } }
Create Mapping XML
Create hibernate mapping for the student object to persist in database.
student.hbm.xml
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="Student" table="student_hib"> <id name="id"> <generator class="assigned"></generator> </id> <property name="name"></property> <property name="dept"></property> </class> </hibernate-mapping>
Create Application Context XML
Create Spring Application Context
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="dataSource" class=" com.mysql.cj.jdbc.MysqlDataSource"> <property name="driverClassName" value=" com.mysql.cj.jdbc.Driver"></property> <property name="url" value=" jdbc:mysql://localhost/TUTORIALSPOINT"></property> <property name="username" value="root"></property> <property name="password" value="guest123"></property> </bean> <bean id="localSessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="mappingResources"> <list> <value>student.hbm.xml</value> </list> </property> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.MySQL8Dialect</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </bean> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory" ref="localSessionFactory"></property> </bean> <bean id="st" class="StudentDAO"> <property name="template" ref="hibernateTemplate"></property> </bean> </beans>
Create Application Class
Finally, we will create our application class with the main() method to run the application. We will use this application to test Spring Hibernate Integration.
PersistStudent.java
package com.tutorialspoint; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; public class PersistStudent { public static void main(String[] args) { Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory factory=new XmlBeanFactory(r); StudentDAO dao=(StudentDAO)factory.getBean("st"); Student s=new Student(); s.setId(190); s.setName("Danny Jing"); s.setDept("Physics"); dao.persistStudent(s); System.out.println(" Successfully persisted the student. Please check your database for results."); } }
Compilation and Execution
Execute PersistStudent binary to run the program.
Output
You would get the following result, and records would be created in the Shape table.
$java PersistStudent Successfully persisted the student. Please check your database for results.
If you check your table, those should have the following records −
mysql> select * from student; mysql> select * from student; +------+------------+---------+ | id | name | dept | +------+------------+---------+ | 190 | Danny Jing | Physics | +------+------------+---------+ 1 row in set (0.00 sec)