Spring ORM Example using Hibernate Last Updated : 23 Jul, 2025 Comments Improve Suggest changes Like Article Like Report Spring ORM is a module of the Java Spring framework used to implement the ORM(Object Relational Mapping) technique. It can be integrated with various mapping and persistence frameworks like Hibernate, Oracle Toplink, iBatis, etc. for database access and manipulation. This article covers an example of the integration of the Spring ORM module with Hibernate framework.Prerequisites:Java ProgrammingSpring Framework (Core, Context, and JDBC modules)Hibernate or any other ORM toolMaven for dependency managementA relational database like MYSQL, PostgreSQL or H2Key Components of Spring ORMSpring ORM provides various classes and interfaces for integrating Spring applications with the Hibernate framework. Some useful classes in Spring ORM are:LocalSessionFactoryBean: Configures Hibernate's SessionFactory.HibernateTransactionManager: Manages transactions for Hibernate.SessionFactory: Used to create Hibernate Session instances for database operations.Note: HibernateTemplate, which was widely used in older versions, is now deprecated. Modern applications use SessionFactory directly with @Transactional annotations.Step-by-Step ImplementationStep 1: Add DependenciesWe will use Maven for dependency management. We need to add the following dependencies to the pom.xml file.Key Dependencies with Versions:DependencyVersionSpring ORM (spring-orm)6.1.0Spring Context (spring-context)6.1.0Spring JDBC (spring-jdbc)6.1.0Hibernate Core (hibernate-core)6.4.0MySQL Connector/J (mysql-connector-j)8.1.0Jakarta Persistence API (jakarta.persistence-api)3.1.0Spring Transaction Management (spring-tx)6.1.0JUnit 5 (junit-jupiter-api, junit-jupiter-engine)5.10.0pom.xml: XML <project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>spring-orm-hibernate-example</artifactId> <version>1.0-SNAPSHOT</version> <properties> <java.version>17</java.version> </properties> <dependencies> <!-- Spring ORM --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>6.1.0</version> </dependency> <!-- Spring Context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>6.1.0</version> </dependency> <!-- Spring JDBC --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>6.1.0</version> </dependency> <!-- Hibernate Core --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>6.4.0</version> </dependency> <!-- MySQL Connector/J --> <dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <version>8.1.0</version> </dependency> <!-- Jakarta Persistence API (JPA) --> <dependency> <groupId>jakarta.persistence</groupId> <artifactId>jakarta.persistence-api</artifactId> <version>3.1.0</version> </dependency> <!-- Spring Transaction Management --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>6.1.0</version> </dependency> <!-- Testing Dependencies --> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>5.10.0</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>5.10.0</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <!-- Compiler Plugin for Java 17 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.11.0</version> <configuration> <source>${java.version}</source> <target>${java.version}</target> </configuration> </plugin> <!-- Maven Surefire Plugin for Testing --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.2.0</version> <configuration> <forkCount>1</forkCount> <reuseForks>false</reuseForks> </configuration> </plugin> </plugins> </build> </project> Note: The project is configured for Java 17 version. if you are using a different version, update the <java.version> property.If you are using Jakarta EE 9 or latest, make sure all javax.persistence imports are replaced with jakarta.persistence.The maven-surefire-plugin is configured to run Junit 5 tests.Step 2: Create Entity ClassNow, we are going to define an entity class that maps to a database table. For example let's create a Student entity.Student.java: Java package com.example.model; import jakarta.persistence.*; @Entity @Table(name = "students") public class Student { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "name", nullable = false) private String name; @Column(name = "email", unique = true) private String email; // Getters and Setters 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 getEmail() { return email; } public void setEmail(String email) { this.email = email; } } Note: If you are using Jakarta EE 9 or later. Use jakarta.persistence instead of javax.persistence.Step 3: Configure Hibernate and SpringUse Java-based configuration to set up Hibernate and Spring. Create a configuration class. Java package com.example.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.orm.hibernate5.LocalSessionFactoryBean; import org.springframework.orm.hibernate5.HibernateTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.sql.DataSource; import java.util.Properties; @Configuration @EnableTransactionManagement public class HibernateConfig { @Bean public LocalSessionFactoryBean sessionFactory() { LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); sessionFactory.setDataSource(dataSource()); sessionFactory.setPackagesToScan("com.example.model"); sessionFactory.setHibernateProperties(hibernateProperties()); return sessionFactory; } @Bean public DataSource dataSource() { org.springframework.jdbc.datasource.DriverManagerDataSource dataSource = new org.springframework.jdbc.datasource.DriverManagerDataSource(); dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://localhost:3306/mydb"); dataSource.setUsername("root"); dataSource.setPassword("password"); return dataSource; } private Properties hibernateProperties() { Properties properties = new Properties(); properties.put("hibernate.dialect", "org.hibernate.dialect.MySQL8Dialect"); properties.put("hibernate.show_sql", "true"); properties.put("hibernate.hbm2ddl.auto", "update"); return properties; } @Bean public HibernateTransactionManager transactionManager() { HibernateTransactionManager txManager = new HibernateTransactionManager(); txManager.setSessionFactory(sessionFactory().getObject()); return txManager; } } Step 4: Create DAO Interface and ImplementationDefine a DAO (Data Access Object) interface and its implementationDAO Interface: Java package com.example.dao; import com.example.model.Student; import java.util.List; public interface StudentDao { void save(Student student); Student findById(Long id); List<Student> findAll(); void update(Student student); void delete(Long id); } DAO Implementation: Java package com.example.dao; import com.example.model.Student; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Repository @Transactional public class StudentDaoImpl implements StudentDao { @Autowired private SessionFactory sessionFactory; @Override public void save(Student student) { Session session = sessionFactory.getCurrentSession(); session.save(student); } @Override public Student findById(Long id) { Session session = sessionFactory.getCurrentSession(); return session.get(Student.class, id); } @Override public List<Student> findAll() { Session session = sessionFactory.getCurrentSession(); return session.createQuery("FROM Student", Student.class).getResultList(); } @Override public void update(Student student) { Session session = sessionFactory.getCurrentSession(); session.update(student); } @Override public void delete(Long id) { Session session = sessionFactory.getCurrentSession(); Student student = session.get(Student.class, id); if (student != null) { session.delete(student); } } } Step 5: Test the ApplicationCreate a main class to test the CRUD operations Java package com.example; import com.example.config.HibernateConfig; import com.example.dao.StudentDao; import com.example.model.Student; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import java.util.List; public class MainApp { public static void main(String[] args) { // Initialize Spring context AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(HibernateConfig.class); StudentDao studentDao = context.getBean(StudentDao.class); // Insert a new student with ID 101 and name "Nisha" Student student1 = new Student(); // Manually set ID for demonstration student1.setId(101L); student1.setName("Nisha"); studentDao.save(student1); System.out.println("Student inserted: " + student1); // Update the student's name to "Priya" student1.setName("Priya"); studentDao.update(student1); System.out.println("Student updated: " + student1); // Retrieve the student with ID 101 Student retrievedStudent = studentDao.findById(101L); System.out.println("Retrieved Student: " + retrievedStudent); // Insert additional students for demonstration Student student2 = new Student(); // Manually set ID for demonstration student2.setId(102L); student2.setName("Danish"); studentDao.save(student2); Student student3 = new Student(); // Manually set ID for demonstration student3.setId(103L); student3.setName("Sneha"); studentDao.save(student3); // Retrieve all students before deletion System.out.println("All Students Before Deletion:"); List<Student> studentsBeforeDeletion = studentDao.findAll(); studentsBeforeDeletion.forEach(System.out::println); // Delete the student with ID 102 studentDao.delete(102L); System.out.println("Student with ID 102 deleted."); // Retrieve all students after deletion System.out.println("All Students After Deletion:"); List<Student> studentsAfterDeletion = studentDao.findAll(); studentsAfterDeletion.forEach(System.out::println); // Close the Spring context context.close(); } } Output:Insertion:Updation:Retrieval (Get):Retrieval (Get All) After Deletion:Deletion: Comment More infoAdvertise with us P payalrathee35 Follow Improve Article Tags : Springboot Technical Scripter 2022 Java-Spring Java-Hibernate Similar Reads Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance 10 min read Spring Boot Basics and PrerequisitesIntroduction to Spring BootSpring is one of the most popular frameworks for building enterprise applications, but traditional Spring projects require heavy XML configuration, making them complex for beginners.Spring Boot solves this problem by providing a ready-to-use, production-grade framework on top of Spring. It eliminate 4 min read Difference between Spring and Spring BootSpring Spring is an open-source lightweight framework that allows Java developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier 4 min read Spring - Understanding Inversion of Control with ExampleSpring IoC (Inversion of Control) Container is the core of the Spring Framework. It creates and manages objects (beans), injects dependencies and manages their life cycles. It uses Dependency Injection (DI), based on configurations from XML files, Java-based configuration, annotations or POJOs. Sinc 6 min read Spring - IoC ContainerThe Spring framework is a powerful framework for building Java applications. It can be considered a collection of sub-frameworks, also referred to as layers, such as Spring AOP, Spring ORM, Spring Web Flow, and Spring Web MVC. We can use any of these modules separately while constructing a Web appli 2 min read BeanFactory vs ApplicationContext in SpringThe Spring Framework provides two core packages that enable Inversion of Control (IoC) and Dependency Injection (DI):org.springframework.beansorg.springframework.contextThese packages define Spring containers that manage the lifecycle and dependencies of beans.Spring offers two main containers1. Bea 6 min read Spring Boot CoreSpring Boot - ArchitectureSpring Boot is built on top of the Spring Framework and follows a layered architecture. Its primary goal is to simplify application development by providing auto-configuration, embedded servers and a production-ready environment out of the box.The architecture of Spring Boot can be divided into seve 2 min read Spring Boot - AnnotationsAnnotations in Spring Boot are metadata that simplify configuration and development. Instead of XML, annotations are used to define beans, inject dependencies and create REST endpoints. They reduce boilerplate code and make building applications faster and easier. Core Spring Boot Annotations 1. @Sp 5 min read Spring Boot ActuatorDeveloping and managing an application are the two most important aspects of the applicationâs life cycle. It is very important to know what is going on beneath the application. Also, when we push the application into production, managing it gradually becomes critically important. Therefore, it is a 5 min read How to create a basic application in Java Spring BootSpring Boot is the most popular Java framework that is used for developing RESTful web applications. In this article, we will see how to create a basic Spring Boot application.Spring Initializr is a web-based tool using which we can easily generate the structure of the Spring Boot project. It also p 3 min read Spring Boot - Code StructureThere is no specific layout or code structure for Spring Boot Projects. However, there are some best practices followed by developers that will help us too. You can divide your project into layers like service layer, entity layer, repository layer,, etc. You can also divide the project into modules. 3 min read Spring Boot - SchedulingSpring Boot provides the ability to schedule tasks for execution at a given time period with the help of @Scheduled annotation. This article provides a step by step guideline on how we can schedule tasks to run in a spring boot application Implementation:It is depicted below stepwise as follows: St 4 min read Spring Boot - LoggingLogging in Spring Boot plays a vital role in Spring Boot applications for recording information, actions, and events within the app. It is also used for monitoring the performance of an application, understanding the behavior of the application, and recognizing the issues within the application. Spr 8 min read Exception Handling in Spring BootException handling in Spring Boot helps deal with errors and exceptions present in APIs, delivering a robust enterprise application. This article covers various ways in which exceptions can be handled and how to return meaningful error responses to the client in a Spring Boot Project. Key Approaches 8 min read Spring Boot with REST APISpring Boot - Introduction to RESTful Web ServicesRESTful Web Services REST stands for REpresentational State Transfer. It was developed by Roy Thomas Fielding, one of the principal authors of the web protocol HTTP. Consequently, REST was an architectural approach designed to make the optimum use of the HTTP protocol. It uses the concepts and verbs 5 min read Spring Boot - REST ExampleIn modern web development, most applications follow the Client-Server Architecture. The Client (frontend) interacts with the server (backend) to fetch or save data. This communication happens using the HTTP protocol. On the server, we expose a bunch of services that are accessible via the HTTP proto 4 min read How to Create a REST API using Java Spring Boot?Representational State Transfer (REST) is a software architectural style that defines a set of constraints for creating web services. RESTful web services allow systems to access and manipulate web resources through a uniform and predefined set of stateless operations. Unlike SOAP, which exposes its 4 min read How to Make a Simple RestController in Spring Boot?A RestController in Spring Boot is a specialized controller that is used to develop RESTful web services. It is marked with the @RestController annotation, which combines @Controller and @ResponseBody. This ensures that the response is automatically converted into JSON or XML, eliminating the need f 2 min read JSON using Jackson in REST API Implementation with Spring BootWhen we build REST APIs with Spring Boot, we need to exclude NULL values from the JSON responses. This is useful when we want to optimize the data being transferred, making the response more compact and easier to process for the client.In this article, we are going to learn the approach that is used 4 min read Spring Boot with Database and Data JPA Spring Boot with H2 DatabaseH2 Database in Spring Boot is an embedded, open-source, and in-memory database. It is a relational database management system written in Java. It is a client/server application. It stores data in memory, not persist the data on disk. Here we will be discussing how can we configure and perform some b 6 min read Spring Boot - JDBCSpring Boot JDBC is used to connect the Spring Boot application with JDBC by providing libraries and starter dependencies. Spring Boot JDBC has a level of control over the SQL queries that are being written. Spring Boot JDBC has simplified the work of Spring JDBC by automating the work and steps by 8 min read Advantages of Spring Boot JDBCSpring JDBC is used to build the Data Access Layer of enterprise applications, it enables developers to connect to the database and write SQL queries and update data to the relational database. The code related to the database has to be placed in DAO classes. SpringJDBC provides a class called JdbcT 3 min read Spring Boot - CRUD OperationsCRUD stands for Create, Read/Retrieve, Update, and Delete and these are the four basic operations that we perform on persistence storage. CRUD is data-oriented and the standardized use of HTTP methods or there is a term for this called HTTP action verbs. HTTP has a few action verbs or methods that w 7 min read Spring Boot - MongoRepository with ExampleSpring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and se 5 min read Spring Boot JpaRepository with ExampleSpring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and se 9 min read Spring Boot - CrudRepository with ExampleSpring Boot's CrudRepository is a part of the Spring Data JPA framework, which provides convenient methods for performing CRUD (Create, Read, Update, Delete) operations on entities in a relational database. CrudRepository is an interface that extends the basic Repository interface and adds generic C 5 min read Spring Boot with KafkaSpring Boot Kafka Producer ExampleSpring Boot is one of the most popular and most used frameworks of Java Programming Language. It is a microservice-based framework and to make a production-ready application using Spring Boot takes very less time. Spring Boot makes it easy to create stand-alone, production-grade Spring-based Applica 3 min read Spring Boot Kafka Consumer ExampleSpring Boot is one of the most popular and most used frameworks of Java Programming Language. It is a microservice-based framework and to make a production-ready application using Spring Boot takes very less time. Spring Boot makes it easy to create stand-alone, production-grade Spring-based Applica 3 min read Spring Boot | How to consume JSON messages using Apache KafkaApache Kafka is a stream processing system that lets you send messages between processes, applications, and servers. In this article, we will see how to publish JSON messages on the console of a Spring boot application using Apache Kafka. In order to learn how to create a Spring Boot project, refer 3 min read Spring Boot | How to consume string messages using Apache KafkaApache Kafka is a publish-subscribe messaging queue used for real-time streams of data. A messaging queue lets you send messages between processes, applications, and servers. In this article we will see how to send string messages from apache kafka to the console of a spring boot application. Appro 3 min read Spring Boot | How to publish String messages on Apache KafkaApache Kafka is a publish-subscribe messaging system. A messaging queue lets you send messages between processes, applications, and servers. In this article, we will see how to send string messages to Apache Kafka in a spring boot application. In order to learn how to create a spring boot project, r 2 min read Spring Boot | How to publish JSON messages on Apache KafkaApache Kafka is a publish-subscribe messaging system. A messaging queue lets you send messages between processes, applications, and servers. In this article, we will see how to send JSON messages to Apache Kafka in a spring boot application. In order to learn how to create a spring boot project, ref 4 min read Spring Boot with AOPSpring Boot - AOP(Aspect Oriented Programming)The Java applications are developed in multiple layers, to increase security, separate business logic, persistence logic, etc. A typical Java application has three layers namely they are Web layer, the Business layer, and the Data layer. Web layer: This layer is used to provide the services to the e 4 min read How to Implement AOP in Spring Boot Application?AOP(Aspect Oriented Programming) breaks the full program into different smaller units. In numerous situations, we need to log, and audit the details as well as need to pay importance to declarative transactions, security, caching, etc., Let us see the key terminologies of AOP Aspect: It has a set of 10 min read Spring Boot - Difference Between AOP and OOPAOP(Aspect-Oriented Programming) complements OOP by enabling modularity of cross-cutting concerns. The Key unit of Modularity(breaking of code into different modules) in Aspect-Oriented Programming is Aspect. one of the major advantages of AOP is that it allows developers to concentrate on business 3 min read Spring Boot - Difference Between AOP and AspectJSpring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and se 3 min read Spring Boot - Cache ProviderThe Spring Framework provides support for transparently adding caching to an application. The Cache provider gives authorization to programmers to configure cache explicitly in an application. It incorporates various cache providers such as EhCache, Redis, Guava, Caffeine, etc. It keeps frequently a 6 min read Like