Spring ORM - Quick Guide



Spring ORM - Overview

The Spring Framework integrates well with ORM frameworks like Hibernate, Java Persistence API (JPA), Java Data Objects (JDO) and iBATIS SQL Maps. Spring provides resource management, data access object (DAO) implementations, and transaction strategies. Spring allows to configure ORM library features through dependency management. Spring maintains a uniform DAO Exception hiearchies and a generic transaction management for all the ORM libraries it supports.

Key Benefits of Spring ORM

Spring IoC container facilitates ORM configurations and easy deployment. Following are the key benefits of using Spring framework to create ORM DAO.

  • Easy to Test − Using spring IoC, an ORM implementation can be easily configured. Each piece of persistence unit can be tested in isolation.

  • Common Data Access Exception − Spring wraps ORM Tools exceptions to a common runtime exception as DataAccessException. This approach helps to handle most persistence exception (non-recoverable) in appropriate layers. No need to handle ORM specific boilerplate catch/throws/exception declarations.

  • General Resource Management − Spring application contexts manages persistence objects, their configurations easily. For example, Hibernate SessionFactory instances, JPA EntityManagerFactory instances, JDBC DataSource instances, iBatis SQL Maps configuration objects and other related objects. Spring handles the local as well JTA transaction management by itself.

  • Integrated transaction management − Spring AOP can be used to wrap an ORM code with a declarative AOP styled interceptor either using @Transaction annotation or by specifying transaction AOP advice in XML configuration file. Spring handles transaction semantics, exception handling, rollback and so on. Spring allows to swap transaction managers without affecting the ORM code.

Spring ORM - Environment Setup

Spring ORM - Environment Setup

This chapter will guide you on how to prepare a development environment to start your work with Spring and its ORM Capabilities. It will also teach you how to set up JDK on your machine before you set up spring −

Setup Java Development Kit (JDK)

You can download the latest version of SDK from Oracle's Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively.

If you are running Windows and have installed the JDK in C:\jdk-24, you would have to put the following line in your C:\autoexec.bat file.

set PATH=C:\jdk-24;%PATH% 
set JAVA_HOME=C:\jdk-24

Alternatively, on Windows NT/2000/XP, you will have to right-click on My Computer, select Properties → Advanced → Environment Variables. Then, you will have to update the PATH value and click the OK button.

On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk-24 and you use the C shell, you will have to put the following into your .cshrc file.

setenv PATH /usr/local/jdk-24/bin:$PATH 
setenv JAVA_HOME /usr/local/jdk-24

Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, you will have to compile and run a simple program to confirm that the IDE knows where you have installed Java. Otherwise, you will have to carry out a proper setup as given in the document of the IDE.

Popular Java Editors

To write your Java programs, you need a text editor. There are many sophisticated IDEs available in the market. But for now, you can consider one of the following −

  • Notepad − On Windows machine, you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad.

  • Netbeans − It is a Java IDE that is open-source and free, which can be downloaded from www.netbeans.org/index.html.

  • Eclipse − It is also a Java IDE developed by the eclipse open-source community and can be downloaded from www.eclipse.org.

Install Eclipse

In this chapter, we will explain how to set Spring environment in Eclipse IDE. Before proceeding with the installation, make sure that you already have Eclipse installed in your system. If not, download and install Eclipse.

For more information on Eclipse, please refer our Eclipse Tutorial

Install MySQL Database

The most important thing you will need, of course is an actual running database with a table that you can query and modify.

  • MySQL DB − MySQL is an open source database. You can download it from MySQL Official Site. We recommend downloading the full Windows installation.

    In addition, download and install MySQL Administrator as well as MySQL Query Browser. These are GUI based tools that will make your development much easier.

    Finally, download and unzip MySQL Connector/J (the MySQL JDBC driver) in a convenient directory. For the purpose of this tutorial we will assume that you have installed the driver at C:\Program Files\MySQL\mysql-connector-java-8.0.23.

    Accordingly, set CLASSPATH variable to C:\Program Files\MySQL\mysql-connector-java-8.0.23\mysql-connector-java-8.0.23-bin.jar. Your driver version may vary based on your installation.

Set Database Credential

When we install MySQL database, its administrator ID is set to root and it gives provision to set a password of your choice.

Using root ID and password you can either create another user ID and password, or you can use root ID and password for your JDBC application.

There are various database operations like database creation and deletion, which would need administrator ID and password.

If you do not have sufficient privilege to create new users, then you can ask your Database Administrator (DBA) to create a user ID and password for you.

Create Database

To create the TUTORIALSPOINT database, use the following steps −

Step 1

Open a Command Prompt and change to the installation directory as follows −

C:\>
C:\>cd Program Files\MySQL\bin
C:\Program Files\MySQL\bin>

Note − The path to mysqld.exe may vary depending on the install location of MySQL on your system. You can also check documentation on how to start and stop your database server.

Step 2

Start the database server by executing the following command, if it is already not running.

C:\Program Files\MySQL\bin>mysqld
C:\Program Files\MySQL\bin>

Step 3

Create the TUTORIALSPOINT database by executing the following command −

C:\Program Files\MySQL\bin> create database TUTORIALSPOINT;

Note − The path to mysqld.exe may vary depending on the install location of MySQL on your system. You can also check documentation on how to start and stop your database server.

For a complete understanding on MySQL database, study the MySQL Tutorial.

Set Maven

In this tutorial, we are using maven to run and build the spring based examples. Follow the Maven - Environment Setup to install maven.

Spring ORM - Create Project

Using eclipse, select FileNew Maven Project. Tick the Create a simple project(skip archetype selection) and click Next.

New Maven Project

Enter the details, as shown below:

Project Details

Click on Finish button and an new project will be created.

Project Structure

Add dependencies for ORM

Now as we've our project ready, let add following dependencies in pom.xml in next chapter.

  • Spring Framework

  • Hibernate

  • MySQL Connector

  • Other related dependencies.

Spring ORM - Maven Hibernate

Let's add following dependencies in pom.xml.

  • Spring Framework

  • Hibernate

  • MySQL Connector

  • Other related dependencies.

Update the pom.xml as per below content.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" 
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>s
   <groupId>com.tutorialspoint</groupId>
   <artifactId>springorm</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>Spring ORM</name>
   <description>Spring ORM Test Project</description>
   <properties>
      <java.version>24</java.version>
      <org.springframework.version>7.0.0-M9</org.springframework.version>
      <org.hibernate.version>6.6.29.Final</org.hibernate.version>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
   </properties>
   <build>      
      <plugins>
         <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.7.0</version>
            <configuration>
               <source>${java.version}</source>
               <target>${java.version}</target>
            </configuration>
         </plugin>
      </plugins>
   </build>
   <dependencies>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-context</artifactId>
         <version>${org.springframework.version}</version>
         <scope>compile</scope>
      </dependency>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-orm</artifactId>
         <version>${org.springframework.version}</version>
      </dependency>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-jdbc</artifactId>
         <version>${org.springframework.version}</version>
      </dependency>
      <dependency>
         <groupId>org.hibernate</groupId>
         <artifactId>hibernate-core</artifactId>
         <version>${org.hibernate.version}</version>
      </dependency>
      <dependency>
         <groupId>jakarta.persistence</groupId>
         <artifactId>jakarta.persistence-api</artifactId>
         <version>3.2.0</version>
      </dependency>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-tx</artifactId>
         <version>${org.springframework.version}</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>
      <dependency>
         <groupId>mysql</groupId>
         <artifactId>mysql-connector-java</artifactId>
         <scope>runtime</scope>
         <version>8.0.33</version>
      </dependency>	
   </dependencies>
</project>

Now right click on the project name. Select MavenUpdate Project to download the required dependencies.

Spring ORM - Persistence Hibernate

Hibernate Persistence Unit defines the various aspects related to data persistence like following.

  • Persistence Unit − A persistence unit containing all the details. It's name is used to get reference in spring context.

  • Database url and credentials − In properties section, we pass the database related values.

  • show_sql − to show the generated sql queries

  • hbm2ddl − to allow hibernate to create tables.

Create persistence configuration as AppConfig.

AppConfig.java

package com.tutorialspoint.jpa;

import java.util.Properties;

import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.hibernate.HibernateTransactionManager;
import org.springframework.orm.jpa.hibernate.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@ComponentScans(value = { @ComponentScan("com.tutorialspoint.jpa.dao"),
@ComponentScan("com.tutorialspoint.jpa.service") })
public class AppConfig {
   @Bean
   public LocalSessionFactoryBean sessionFactory() {
      LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
      sessioFactory.setDataSource(dataSource());
      sessionFactory.setPackagesToScan("com.tutorialspoint.jpa.entity");
      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/tutorialspoint");
      dataSource.setUsername("guest");
      dataSource.setPassword("guest123");
      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", "create");
      return properties;
   }

   @Bean
   public HibernateTransactionManager transactionManager() {
      HibernateTransactionManager txManager = new HibernateTransactionManager();
      txManager.setSessionFactory(sessionFactory().getObject());
      return txManager;
   }
}

Spring ORM - Update Project

Let's add the following classes in the project in the relevant packages.

Project Structure

Employee class to be persisted in database.

Employee.java

package com.tutorialspoint.jpa.entity;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

@Entity
@Table(name = "Employees")
public class Employee {
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY) 	
   private int id;

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

   @Column(name = "SALARY")
   private double salary;

   @Column(name = "DESIGNATION")
   private String designation;

   public Employee( ) {
   }

   public Employee(String name, double salary, String designation) {
      this.name = name;
      this.salary = salary;
      this.designation = designation;
   }
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public double getSalary() {
      return salary;
   }
   public void setSalary(double salary) {
      this.salary = salary;
   }
   public String getDesignation() {
      return designation;
   }
   public void setDesignation(String designation) {
      this.designation = designation;
   }
}

Employee DAO class to do operations on database.

EmployeeDao.java

package com.tutorialspoint.jpa.dao;

import java.util.List;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Root;
import org.springframework.stereotype.Repository;
import com.tutorialspoint.jpa.entity.Employee;

@Repository
public class EmployeeDao {
   @PersistenceContext
   private EntityManager em;

   public void add(Employee employee) {
      em.persist(employee);
   }
   public List<Employee> listEmployees() {
      CriteriaQuery<Employee> criteriaQuery = em.getCriteriaBuilder().createQuery(Employee.class);
      @SuppressWarnings("unused")
      Root<Employee> root = criteriaQuery.from(Employee.class);
      return em.createQuery(criteriaQuery).getResultList();
   }
}

Employee Service class to use Employee DAO class.

EmployeeService.java

package com.tutorialspoint.jpa.service;

import java.util.List;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tutorialspoint.jpa.dao.EmployeeDao;
import com.tutorialspoint.jpa.entity.Employee;

@Service
public class EmployeeService {
   @Autowired
   private EmployeeDao employeeDao;

   @Transactional
   public void add(Employee employee) {
      employeeDao.add(employee);
   }
   @Transactional()
   public List<Employee> listEmployees() {
      return employeeDao.listEmployees();
   }
}

Application Configuration to be used by Spring framework.

AppConfig.java

package com.tutorialspoint.jpa;

import java.util.Properties;

import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.hibernate.HibernateTransactionManager;
import org.springframework.orm.jpa.hibernate.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@ComponentScans(value = { @ComponentScan("com.tutorialspoint.jpa.dao"),
@ComponentScan("com.tutorialspoint.jpa.service") })
public class AppConfig {
   @Bean
   public LocalSessionFactoryBean sessionFactory() {
      LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
      sessioFactory.setDataSource(dataSource());
      sessionFactory.setPackagesToScan("com.tutorialspoint.jpa.entity");
      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/tutorialspoint");
      dataSource.setUsername("guest");
      dataSource.setPassword("guest123");
      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", "create");
      return properties;
   }

   @Bean
   public HibernateTransactionManager transactionManager() {
      HibernateTransactionManager txManager = new HibernateTransactionManager();
      txManager.setSessionFactory(sessionFactory().getObject());
      return txManager;
   }
}

Main Application to run and test the functionalities.

MainApp.java

package com.tutorialspoint.jpa;

import java.sql.SQLException;
import java.util.List;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.tutorialspoint.jpa.entity.Employee;
import com.tutorialspoint.jpa.service.EmployeeService;

public class MainApp {
   public static void main(String[] args) throws SQLException {
      AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
      EmployeeService employeeService = context.getBean(EmployeeService.class);

      employeeService.add(new Employee("Julie", 10000, "Technical Manager"));
      employeeService.add(new Employee("Robert", 20000, "Senior Manager"));
      employeeService.add(new Employee("Anil", 5000, "Software Engineer"));

      // Get Persons
      List<Employee> employees = employeeService.listEmployees();
      for (Employee employee : employees) {
         System.out.println("Id : "+employee.getId());
         System.out.println("Name : "+employee.getName());
         System.out.println("Salary = "+employee.getSalary());
         System.out.println("Designation = "+employee.getDesignation());
         System.out.println();
      }
      context.close();
   }
}

Spring ORM - Run & Test Hibernate

Now in eclipse, right click on the MainApp.java, select Run As context menu, and select Java Application. Check the console logs in the eclipse. You can see the below logs −

Oct 05, 2025 6:08:40 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate ORM core version 6.6.29.Final
Oct 05, 2025 6:08:41 PM org.hibernate.cache.internal.RegionFactoryInitiator initiateService
INFO: HHH000026: Second-level cache disabled
Oct 05, 2025 6:08:41 PM org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl constructDialect
WARN: HHH90000025: MySQL8Dialect does not need to be specified explicitly using 'hibernate.dialect' (remove the property setting and it will be selected by default)
Oct 05, 2025 6:08:41 PM org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl logSelectedDialect
WARN: HHH90000026: MySQL8Dialect has been deprecated; use org.hibernate.dialect.MySQLDialect instead
Oct 05, 2025 6:08:41 PM org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator logConnectionInfo
INFO: HHH10001005: Database info:
	Database JDBC URL [Connecting through datasource 'org.springframework.jdbc.datasource.DriverManagerDataSource@31ea9581']
	Database driver: undefined/unknown
	Database version: 8.0
	Autocommit mode: undefined/unknown
	Isolation level: undefined/unknown
	Minimum pool size: undefined/unknown
	Maximum pool size: undefined/unknown
Oct 05, 2025 6:08:42 PM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000489: No JTA platform available (set 'hibernate.transaction.jta.platform' to enable JTA platform integration)
Hibernate: drop table if exists Employees
Hibernate: create table Employees (SALARY float(53), id integer not null auto_increment, DESIGNATION varchar(255), NAME varchar(255), primary key (id)) engine=InnoDB
Hibernate: insert into Employees (DESIGNATION,NAME,SALARY) values (?,?,?)
Hibernate: insert into Employees (DESIGNATION,NAME,SALARY) values (?,?,?)
Hibernate: insert into Employees (DESIGNATION,NAME,SALARY) values (?,?,?)
Hibernate: select e1_0.id,e1_0.DESIGNATION,e1_0.NAME,e1_0.SALARY from Employees e1_0
Id : 1
Name : Julie
Salary = 10000.0
Designation = Technical Manager

Id : 2
Name : Robert
Salary = 20000.0
Designation = Senior Manager

Id : 3
Name : Anil
Salary = 5000.0
Designation = Software Engineer

Here project is built and run using spring configurations. A table Employee is created and have three records. You can verify the same using MySQL console.

Enter password: ********
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 41
Server version: 8.0.23 MySQL Community Server - GPL

Copyright (c) 2000, 2021, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> use tutorialspoint;
Database changed
mysql> select * from employees;
+----+-------------------+--------+--------+
| id | DESIGNATION       | NAME   | SALARY |
+----+-------------------+--------+--------+
|  1 | Technical Manager | Julie  |  10000 |
|  2 | Senior Manager    | Robert |  20000 |
|  3 | Software Engineer | Anil   |   5000 |
+----+-------------------+--------+--------+
3 rows in set (0.00 sec)

mysql>

Spring ORM - Maven EclipseLink

Let's add following dependencies in pom.xml.

  • Spring Framework

  • EclipseLink

  • MySQL Connector

  • Other related dependencies.

Update the pom.xml as per below content.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" 
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>s
   <groupId>com.tutorialspoint</groupId>
   <artifactId>springorm</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>Spring ORM</name>
   <description>Spring ORM Test Project</description>
   <properties>
      <java.version>24</java.version>
      <org.springframework.version>7.0.0-M9</org.springframework.version>
      <org.eclipselink.version>5.0.0-B10</org.eclipselink.version>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
   </properties>
   <build>      
      <plugins>
         <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.7.0</version>
            <configuration>
               <source>${java.version}</source>
               <target>${java.version}</target>
            </configuration>
         </plugin>
      </plugins>
   </build>
   <dependencies>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-context</artifactId>
         <version>${org.springframework.version}</version>
         <scope>compile</scope>
      </dependency>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-orm</artifactId>
         <version>${org.springframework.version}</version>
      </dependency>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-jdbc</artifactId>
         <version>${org.springframework.version}</version>
      </dependency>
      <dependency>
         <groupId>org.eclipse.persistence</groupId>
         <artifactId>org.eclipse.persistence.jpa</artifactId>
         <version>${org.eclipselink.version}</version>
      </dependency>
      <dependency>
         <groupId>jakarta.persistence</groupId>
         <artifactId>jakarta.persistence-api</artifactId>
         <version>3.2.0</version>
      </dependency>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-tx</artifactId>
         <version>${org.springframework.version}</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>
      <dependency>
         <groupId>mysql</groupId>
         <artifactId>mysql-connector-java</artifactId>
         <scope>runtime</scope>
         <version>8.0.33</version>
      </dependency>	
   </dependencies>
</project>

Now right click on the project name. Select MavenUpdate Project to download the required dependencies.

Spring ORM - Persistence EclipseLink

persistence.xml defines the various aspects related to eclipselink like following.

  • Persistence Unit − A persistence unit containing all the details. It's name is used to get reference in spring context.

  • provider − org.eclipse.persistence.jpa.PersistenceProvider class will be used as provider.

  • Database url and credentials − In properties section, we pass the database related values.

  • class − to register the class to be persisted.

  • eclipselink.ddl-generation − to allow eclipselink to create tables.

Create persistence.xml in src -> main > resources > META-INF folder.

persistence.xml

<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
   http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd" version="2.1">

   <persistence-unit name="EclipseLink_JPA">
      <description> Spring EclipseLink JPA Configuration Example</description>
      <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
      <class>com.tutorialspoint.jpa.entity.Employee</class>
      <properties>
         <property name="jakarta.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver" />
         <property name="jakarta.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/tutorialspoint" />
         <property name="jakarta.persistence.jdbc.user" value="guest" />
         <property name="jakarta.persistence.jdbc.password" value="guest123" />
         <property name="eclipselink.logging.level" value="FINE"/>
         <property name="eclipselink.ddl-generation" value="create-tables"/>
      </properties>

   </persistence-unit>
</persistence>

Spring ORM - Update Project EclipseLink

Now update the AppConfig.java to use the persistence unit created for EclipseLink.

AppConfig.java

package com.tutorialspoint.jpa;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalEntityManagerFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@ComponentScans(value = { @ComponentScan("com.tutorialspoint.jpa.dao"),
   @ComponentScan("com.tutorialspoint.jpa.service") })
   public class AppConfig {

   @Bean
   public LocalEntityManagerFactoryBean geEntityManagerFactoryBean() {
      LocalEntityManagerFactoryBean factoryBean = new LocalEntityManagerFactoryBean();
      factoryBean.setPersistenceUnitName("EclipseLink_JPA");
      return factoryBean;
   }
   @Bean
   public JpaTransactionManager geJpaTransactionManager() {
      JpaTransactionManager transactionManager = new JpaTransactionManager();
      transactionManager.setEntityManagerFactory(geEntityManagerFactoryBean().getObject());
      return transactionManager;
   }
}

Now reset the database.

mysql> use tutorialspoint
Database changed
mysql> delete from employees;
Query OK, 3 rows affected (0.02 sec)

mysql> drop table employees;
Query OK, 0 rows affected (0.17 sec)

mysql>

Spring ORM - Test EclipseLink

Now in eclipse, right click on the MainApp.java, select Run As context menu, and select Java Application. Check the console logs in the eclipse. You can see the below logs −

[EL Fine]: server: 2025.10.05 20:40:59.850--Thread(Thread[#3,main,5,main])--Configured server platform: org.eclipse.persistence.platform.server.NoServerPlatform
[EL Config]: metadata: 2025.10.05 20:40:59.978--ServerSession(743778731)--Thread(Thread[#3,main,5,main])--The access type for the persistent class [class com.tutorialspoint.jpa.entity.Employee] is set to [FIELD].
[EL Config]: metadata: 2025.10.05 20:40:59.990--ServerSession(743778731)--Thread(Thread[#3,main,5,main])--The alias name for the entity class [class com.tutorialspoint.jpa.entity.Employee] is being defaulted to: Employee.
[EL Config]: metadata: 2025.10.05 20:40:59.999--ServerSession(743778731)--Thread(Thread[#3,main,5,main])--The column name for element [id] is being defaulted to: ID.
Oct 05, 2025 8:41:00 PM org.springframework.orm.jpa.LocalEntityManagerFactoryBean buildNativeEntityManagerFactory
INFO: Initialized JPA EntityManagerFactory for persistence unit 'EclipseLink_JPA'
[EL Info]: 2025.10.05 20:41:00.239--ServerSession(743778731)--Thread(Thread[#3,main,5,main])--EclipseLink, version: Eclipse Persistence Services - 5.0.0-B10.v202508250733-7403fb4d27505a202052781d38a7d5324ff916bd
[EL Fine]: connection: 2025.10.05 20:41:00.838--Thread(Thread[#3,main,5,main])--Detected database platform: org.eclipse.persistence.platform.database.MySQLPlatform
[EL Fine]: connection: 2025.10.05 20:41:00.850--ServerSession(743778731)--Connection(1270383967)--Thread(Thread[#3,main,5,main])--connecting(DatabaseLogin(
	platform=>MySQLPlatform
	user name=> "guest"
	datasource URL=> "jdbc:mysql://localhost:3306/tutorialspoint"
))
[EL Config]: connection: 2025.10.05 20:41:00.909--ServerSession(743778731)--Connection(65982709)--Thread(Thread[#3,main,5,main])--Connected: jdbc:mysql://localhost:3306/tutorialspoint
	User: guest@localhost
	Database: MySQL  Version: 8.0.43
	Driver: MySQL Connector/J  Version: mysql-connector-j-8.0.33 (Revision: 7d6b0800528b6b25c68b52dc10d6c1c8429c100c)
[EL Fine]: connection: 2025.10.05 20:41:00.986--ServerSession(743778731)--Thread(Thread[#3,main,5,main])--/file:/C:/Users/mahes/eclipse-workspace/springorm/target/classes/_EclipseLink_JPA login successful
[EL Fine]: 2025.10.05 20:41:01.005--Thread(Thread[#3,main,5,main])--JsonPlatformProvider class org.eclipse.persistence.pgsql.PostgreSQLJsonPlatformProvider was not found
[EL Fine]: 2025.10.05 20:41:01.006--Thread(Thread[#3,main,5,main])--JsonPlatformProvider class org.eclipse.persistence.platform.database.oracle.json.OracleJsonPlatformProvider was not found
[EL Fine]: 2025.10.05 20:41:01.006--Thread(Thread[#3,main,5,main])--JsonPlatformProvider class org.eclipse.persistence.json.DefaultJsonPlatformProvider was not found
[EL Fine]: sql: 2025.10.05 20:41:01.041--ServerSession(743778731)--Connection(65982709)--Thread(Thread[#3,main,5,main])--CREATE TABLE Employees (ID INTEGER AUTO_INCREMENT NOT NULL, DESIGNATION VARCHAR(255), NAME VARCHAR(255), SALARY DOUBLE, PRIMARY KEY (ID))
[EL Fine]: sql: 2025.10.05 20:41:01.191--ClientSession(827248723)--Connection(65982709)--Thread(Thread[#3,main,5,main])--INSERT INTO Employees (DESIGNATION, NAME, SALARY) VALUES (?, ?, ?)
	bind => [Technical Manager, Julie, 10000.0]
[EL Fine]: sql: 2025.10.05 20:41:01.214--ClientSession(1866403758)--Connection(65982709)--Thread(Thread[#3,main,5,main])--INSERT INTO Employees (DESIGNATION, NAME, SALARY) VALUES (?, ?, ?)
	bind => [Senior Manager, Robert, 20000.0]
[EL Fine]: sql: 2025.10.05 20:41:01.224--ClientSession(1948835427)--Connection(65982709)--Thread(Thread[#3,main,5,main])--INSERT INTO Employees (DESIGNATION, NAME, SALARY) VALUES (?, ?, ?)
	bind => [Software Engineer, Anil, 5000.0]
[EL Fine]: sql: 2025.10.05 20:41:01.253--ServerSession(743778731)--Connection(65982709)--Thread(Thread[#3,main,5,main])--SELECT ID, DESIGNATION, NAME, SALARY FROM Employees
Id : 1
Name : Julie
Salary = 10000.0
Designation = Technical Manager

Id : 2
Name : Robert
Salary = 20000.0
Designation = Senior Manager

Id : 3
Name : Anil
Salary = 5000.0
Designation = Software Engineer

Oct 05, 2025 8:41:01 PM org.springframework.orm.jpa.LocalEntityManagerFactoryBean destroy
INFO: Closing JPA EntityManagerFactory for persistence unit 'EclipseLink_JPA'
[EL Fine]: connection: 2025.10.05 20:41:01.262--ServerSession(743778731)--Connection(65982709)--Thread(Thread[#3,main,5,main])--disconnect
[EL Fine]: connection: 2025.10.05 20:41:01.263--ServerSession(743778731)--Thread(Thread[#3,main,5,main])--/file:/C:/Users/mahes/eclipse-workspace/springorm/target/classes/_EclipseLink_JPA logout successful
[EL Fine]: connection: 2025.10.05 20:41:01.264--ServerSession(743778731)--Connection(1270383967)--Thread(Thread[#3,main,5,main])--disconnect

Here project is built and run using spring configurations. A table Employee is created and have three records. You can verify the same using MySQL console.

Enter password: ********
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 41
Server version: 8.0.23 MySQL Community Server - GPL

Copyright (c) 2000, 2021, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> use tutorialspoint;
Database changed
mysql> select * from employees;
+----+-------------------+--------+--------+
| id | DESIGNATION       | NAME   | SALARY |
+----+-------------------+--------+--------+
|  1 | Technical Manager | Julie  |  10000 |
|  2 | Senior Manager    | Robert |  20000 |
|  3 | Software Engineer | Anil   |   5000 |
+----+-------------------+--------+--------+
3 rows in set (0.00 sec)

mysql>
Advertisements