Spring ORM - 快速指南



Spring ORM - 概述

Spring 框架与 ORM 框架(如 Hibernate、Java 持久性 API (JPA)、Java 数据对象 (JDO) 和 iBATIS SQL Maps)很好地集成。Spring 提供资源管理、数据访问对象 (DAO) 实现和事务策略。Spring 允许通过依赖项管理配置 ORM 库功能。Spring 维护统一的 DAO 异常层次结构以及其支持的所有 ORM 库的通用事务管理。

Spring IoC 容器有助于 ORM 配置和轻松部署。以下是使用 Spring 框架创建 ORM DAO 的主要好处。

  • 易于测试 - 使用 Spring IoC,可以轻松配置 ORM 实现。每个持久性单元都可以独立测试。

  • 通用数据访问异常 - Spring 将 ORM 工具异常包装到一个通用运行时异常 DataAccessException 中。这种方法有助于在适当的层处理大多数持久性异常(不可恢复)。无需处理 ORM 特定的样板 catch/throws/异常声明。

  • 通用资源管理 - Spring 应用程序上下文轻松管理持久性对象及其配置。例如,Hibernate SessionFactory 实例、JPA EntityManagerFactory 实例、JDBC DataSource 实例、iBatis SQL Maps 配置对象和其他相关对象。Spring 本身处理本地和 JTA 事务管理。

  • 集成事务管理 - Spring AOP 可用于使用声明性 AOP 样式拦截器包装 ORM 代码,方法是使用 @Transaction 注解或在 XML 配置文件中指定事务 AOP 建议。Spring 处理事务语义、异常处理、回滚等。Spring 允许交换事务管理器而不会影响 ORM 代码。

Spring ORM - 环境设置

本章将指导您如何准备开发环境以开始使用 Spring 框架。它还将教您如何在设置 Spring 框架之前在您的机器上设置 JDK、Maven 和 Eclipse -

设置 Java 开发工具包 (JDK)

您可以从 Oracle 的 Java 网站下载最新版本的 SDK - Java SE 下载。 您将在下载的文件中找到安装 JDK 的说明,请按照给定的说明安装和配置设置。最后,设置 PATH 和 JAVA_HOME 环境变量以引用包含 java 和 javac 的目录,通常分别为 java_install_dir/bin 和 java_install_dir。

如果您正在运行 Windows 并已将 JDK 安装在 C:\jdk-11.0.11 中,则必须将以下行放入您的 C:\autoexec.bat 文件中。

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

或者,在 Windows NT/2000/XP 上,您需要右键单击“我的电脑”,选择“属性”→“高级”→“环境变量”。然后,您需要更新 PATH 值并单击“确定”按钮。

在 Unix(Solaris、Linux 等)上,如果 SDK 安装在 /usr/local/jdk-11.0.11 中并且您使用的是 C shell,则需要将以下内容放入您的 .cshrc 文件中。

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

或者,如果您使用集成开发环境 (IDE),如 Borland JBuilder、Eclipse、IntelliJ IDEA 或 Sun ONE Studio,则需要编译并运行一个简单的程序以确认 IDE 知道您已在何处安装了 Java。否则,您需要按照 IDE 文档中给出的说明进行正确的设置。

设置 Eclipse IDE

本教程中的所有示例都是使用 Eclipse IDE 编写的。因此,我们建议您在您的机器上安装最新版本的 Eclipse。

要安装 Eclipse IDE,请从 www.eclipse.org/downloads/ 下载最新的 Eclipse 二进制文件。下载安装后,将二进制分发版解压缩到一个方便的位置。例如,在 Windows 上的 C:\eclipse 中,或在 Linux/Unix 上的 /usr/local/eclipse 中,最后适当地设置 PATH 变量。

可以通过在 Windows 机器上执行以下命令来启动 Eclipse,或者您可以简单地双击 eclipse.exe

%C:\eclipse\eclipse.exe 

可以通过在 Unix(Solaris、Linux 等)机器上执行以下命令来启动 Eclipse -

$/usr/local/eclipse/eclipse

成功启动后,如果一切正常,则应显示以下结果 -

Eclipse Home page

安装 MySQL 数据库

当然,您最需要的是一个实际运行的数据库,其中包含您可以查询和修改的表。

  • MySQL DB - MySQL 是一个开源数据库。您可以从 MySQL 官方网站 下载它。我们建议下载完整的 Windows 安装程序。

    此外,下载并安装 MySQL Administrator 以及 MySQL Query Browser。 这些是基于 GUI 的工具,将使您的开发更加轻松。

    最后,下载并解压缩 MySQL Connector/J(MySQL JDBC 驱动程序)到一个方便的目录中。在本教程中,我们将假设您已将驱动程序安装在 C:\Program Files\MySQL\mysql-connector-java-5.1.8 中。

    相应地,将 CLASSPATH 变量设置为 C:\Program Files\MySQL\mysql-connector-java-5.1.8\mysql-connector-java-5.1.8-bin.jar。您的驱动程序版本可能因您的安装而异。

设置数据库凭据

当我们安装 MySQL 数据库时,其管理员 ID 设置为 root,并且它提供设置您选择的密码的权限。

使用 root ID 和密码,您可以创建另一个用户 ID 和密码,或者您可以使用 root ID 和密码进行 JDBC 应用程序。

有各种数据库操作,如数据库创建和删除,这需要管理员 ID 和密码。

如果您没有足够的权限创建新用户,则可以要求您的数据库管理员 (DBA) 为您创建一个用户 ID 和密码。

创建数据库

要创建 TUTORIALSPOINT 数据库,请使用以下步骤 -

步骤 1

打开一个 命令提示符 并更改为安装目录,如下所示 -

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

注意 - mysqld.exe 的路径可能因系统上 MySQL 的安装位置而异。您还可以查看有关如何启动和停止数据库服务器的文档。

步骤 2

如果数据库服务器尚未运行,则通过执行以下命令启动它。

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

步骤 3

通过执行以下命令创建 TUTORIALSPOINT 数据库 -

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

注意 - mysqld.exe 的路径可能因系统上 MySQL 的安装位置而异。您还可以查看有关如何启动和停止数据库服务器的文档。

要全面了解 MySQL 数据库,请学习 MySQL 教程

设置 Maven

在本教程中,我们使用 maven 来运行和构建基于 spring 的示例。请按照 Maven - 环境设置 安装 maven。

Spring ORM - 创建项目

使用 eclipse,选择 文件新建 Maven 项目。勾选 创建简单项目(跳过原型选择) 并单击下一步。

New Maven Project

输入详细信息,如下所示

Project Details

单击“完成”按钮,将创建一个新项目。

Project Structure

现在,我们的项目已准备就绪,让我们在下一章中在 pom.xml 中添加以下依赖项。

  • Spring 框架

  • Hibernate

  • MySQL 连接器

  • 其他相关依赖项。

Spring ORM - Maven Hibernate

让我们在 pom.xml 中添加以下依赖项。

  • Spring 框架

  • Hibernate

  • MySQL 连接器

  • 其他相关依赖项。

根据以下内容更新 pom.xml。

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>
   <groupId>com.tutorialspoint</groupId>
   <artifactId>springorm</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>Spring ORM</name>
   <description>Spring ORM Test Project</description>
   <properties>
      <org.springframework.version>4.3.7.RELEASE</org.springframework.version>
      <org.hibernate.version>5.2.9.Final</org.hibernate.version>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <java.version>1.8</java.version>    
   </properties>
   <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.hibernate</groupId>
         <artifactId>hibernate-core</artifactId>
         <version>${org.hibernate.version}</version>
      </dependency>
      <dependency>
         <groupId>org.hibernate</groupId>
         <artifactId>hibernate-entitymanager</artifactId>
         <version>${org.hibernate.version}</version>
      </dependency>
      <dependency>
         <groupId>org.apache.commons</groupId>
         <artifactId>commons-dbcp2</artifactId>
         <version>2.1.1</version>
      </dependency>
      <dependency>
         <groupId>mysql</groupId>
         <artifactId>mysql-connector-java</artifactId>
         <scope>runtime</scope>
         <version>8.0.13</version>
      </dependency>	
      <dependency>
         <groupId>com.sun.activation</groupId>
         <artifactId>javax.activation</artifactId>
         <version>1.2.0</version>
      </dependency>
      <dependency>
         <groupId>javax.xml.bind</groupId>
         <artifactId>jaxb-api</artifactId>
         <version>2.3.1</version>
      </dependency>
      <dependency>
         <groupId>org.glassfish.jaxb</groupId>
         <artifactId>jaxb-runtime</artifactId>
         <version>2.3.1</version>
         <scope>runtime</scope>
      </dependency>
   </dependencies>
   <build>
      <plugins>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
               <source>${java.version}</source>
               <target>${java.version}</target>
            </configuration>
         </plugin>
      </plugins>
   </build>
</project>

现在右键单击项目名称。选择 Maven更新项目 以下载所需的依赖项。

Spring ORM - 持久化 Hibernate

persistence.xml 定义了与 hibernate 相关的各个方面,如下所示。

  • 持久性单元 - 包含所有详细信息的持久性单元。其名称用于在 Spring 上下文中获取引用。

  • 提供程序 - org.hibernate.jpa.HibernatePersistenceProvider 类将用作提供程序。

  • 数据库 url 和凭据 - 在 properties 部分,我们传递数据库相关的值。

  • show_sql - 显示生成的 sql 查询

  • hbm2ddl - 允许 hibernate 创建表。

在 src -> main -> resources -> META-INF 文件夹中创建 persistence.xml。

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="Hibernate_JPA">
   <description> Spring Hibernate JPA Configuration Example</description>
   <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
   <properties>
      <property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver" />
      <property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/tutorialspoint?useSSL=false" />
      <property name="javax.persistence.jdbc.user" value="root" />
      <property name="javax.persistence.jdbc.password" value="root@123" />
      <property name="hibernate.show_sql" value="true" />
      <property name="hibernate.hbm2ddl.auto" value="create" />
   </properties>
   </persistence-unit>
</persistence>

Spring ORM - 更新项目

让我们在项目中相关包中添加以下类。

Project Structure

要持久化到数据库中的 Employee 类。

Employee.java

package com.tutorialspoint.jpa.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.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 类,用于对数据库执行操作。

EmployeeDao.java

package com.tutorialspoint.jpa.dao;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaQuery;
import javax.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 类,用于使用 Employee DAO 类。

EmployeeService.java

package com.tutorialspoint.jpa.service;

import java.util.List;
import javax.transaction.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();
   }
}

Spring 框架要使用的应用程序配置。

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("Hibernate_JPA");
      return factoryBean;
   }
   @Bean
   public JpaTransactionManager geJpaTransactionManager() {
      JpaTransactionManager transactionManager = new JpaTransactionManager();
      transactionManager.setEntityManagerFactory(geEntityManagerFactoryBean().getObject());
      return transactionManager;
   }
}

运行和测试功能的主要应用程序。

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 - 运行 & 测试 Hibernate

现在在 eclipse 中,右键单击 MainApp.java,选择 以...运行 上下文菜单,然后选择 Java 应用程序。检查 eclipse 中的控制台日志。您可以看到以下日志 -

...
Sep 27, 2021 9:16:52 AM org.springframework.orm.jpa.LocalEntityManagerFactoryBean createNativeEntityManagerFactory
INFO: Building JPA EntityManagerFactory for persistence unit 'Hibernate_JPA'
Sep 27, 2021 9:16:52 AM org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [name: Hibernate_JPA...]
...
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
Hibernate: drop table if exists Employees
Sep 27, 2021 9:16:54 AM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@2264ea32] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate: create table Employees (id integer not null auto_increment, DESIGNATION varchar(255), NAME varchar(255), SALARY double precision, primary key (id)) engine=MyISAM
Sep 27, 2021 9:16:54 AM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@58740366] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Sep 27, 2021 9:16:54 AM org.hibernate.tool.schema.internal.SchemaCreatorImpl applyImportSources
INFO: HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@4b74b35'
Sep 27, 2021 9:16:54 AM org.springframework.orm.jpa.LocalEntityManagerFactoryBean buildNativeEntityManagerFactory
INFO: Initialized JPA EntityManagerFactory for persistence unit 'Hibernate_JPA'
Hibernate: insert into Employees (DESIGNATION, NAME, SALARY) values (?, ?, ?)
Hibernate: insert into Employees (DESIGNATION, NAME, SALARY) values (?, ?, ?)
Hibernate: insert into Employees (DESIGNATION, NAME, SALARY) values (?, ?, ?)
Sep 27, 2021 9:16:55 AM org.hibernate.hql.internal.QueryTranslatorFactoryInitiator initiateService
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select employee0_.id as id1_0_, employee0_.DESIGNATION as DESIGNAT2_0_, employee0_.NAME as NAME3_0_, employee0_.SALARY as SALARY4_0_ from Employees employee0_
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

Sep 27, 2021 9:16:55 AM org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
INFO: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@18eed359: startup date [Mon Sep 27 09:16:51 IST 2021]; root of context hierarchy
Sep 27, 2021 9:16:55 AM org.springframework.orm.jpa.LocalEntityManagerFactoryBean destroy
INFO: Closing JPA EntityManagerFactory for persistence unit 'Hibernate_JPA'
Sep 27, 2021 9:16:55 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://127.0.0.1:3306/tutorialspoint?useSSL=false]

此处项目使用 Spring 配置构建和运行。创建了一个 Employee 表,其中包含三条记录。您可以使用 MySQL 控制台验证这一点。

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

让我们在 pom.xml 中添加以下依赖项。

  • Spring 框架

  • EclipseLink

  • MySQL 连接器

  • 其他相关依赖项。

根据以下内容更新 pom.xml。

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>
   <groupId>com.tutorialspoint</groupId>
   <artifactId>springorm</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>Spring ORM</name>
   <description>Spring ORM Test Project</description>
   <properties>
      <org.springframework.version>4.3.7.RELEASE</org.springframework.version>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <java.version>1.8</java.version>    
   </properties> 	
   <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.eclipse.persistence</groupId>
         <artifactId>eclipselink</artifactId>
         <version>2.5.1</version>
      </dependency>
      <dependency>
         <groupId>org.eclipse.persistence</groupId>
         <artifactId>javax.persistence</artifactId>
         <version>2.0.0</version>
      </dependency>
      <dependency>
         <groupId>javax.transaction</groupId>
         <artifactId>javax.transaction-api</artifactId>
         <version>1.3</version>
      </dependency>
      <dependency>
         <groupId>org.apache.commons</groupId>
         <artifactId>commons-dbcp2</artifactId>
         <version>2.1.1</version>
      </dependency>
      <dependency>
         <groupId>mysql</groupId>
         <artifactId>mysql-connector-java</artifactId>
         <scope>runtime</scope>
         <version>8.0.13</version>
      </dependency>	
      <dependency>
         <groupId>com.sun.activation</groupId>
         <artifactId>javax.activation</artifactId>
         <version>1.2.0</version>
      </dependency>
      <dependency>
         <groupId>javax.xml.bind</groupId>
         <artifactId>jaxb-api</artifactId>
         <version>2.3.1</version>
      </dependency>
      <dependency>
         <groupId>org.glassfish.jaxb</groupId>
         <artifactId>jaxb-runtime</artifactId>
         <version>2.3.1</version>
         <scope>runtime</scope>
      </dependency>
   </dependencies>
   <build>
      <plugins>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
               <source>${java.version}</source>
               <target>${java.version}</target>
            </configuration>
         </plugin>
      </plugins>
   </build>
</project>

现在右键单击项目名称。选择 Maven更新项目 以下载所需的依赖项。

Spring ORM - 持久化 EclipseLink

persistence.xml 定义了与 eclipselink 相关的各个方面,如下所示。

  • 持久性单元 - 包含所有详细信息的持久性单元。其名称用于在 Spring 上下文中获取引用。

  • 提供程序 - org.eclipse.persistence.jpa.PersistenceProvider 类将用作提供程序。

  • 数据库 url 和凭据 - 在 properties 部分,我们传递数据库相关的值。

  • - 注册要持久化的类。

  • eclipselink.ddl-generation - 允许 eclipselink 创建表。

在 src -> main -> resources -> META-INF 文件夹中创建 persistence.xml。

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="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver" />
         <property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/tutorialspoint?useSSL=false" />
         <property name="javax.persistence.jdbc.user" value="root" />
         <property name="javax.persistence.jdbc.password" value="root@123" />
         <property name="eclipselink.logging.level" value="FINE"/>
         <property name="eclipselink.ddl-generation" value="create-tables"/>
      </properties>

   </persistence-unit>
</persistence>

Spring ORM - 更新项目 EclipseLink

现在更新AppConfig.java以使用为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;
   }
}

现在重置数据库。

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 - 测试EclipseLink

现在在 eclipse 中,右键单击 MainApp.java,选择 以...运行 上下文菜单,然后选择 Java 应用程序。检查 eclipse 中的控制台日志。您可以看到以下日志 -

...
Sep 28, 2021 8:56:13 AM org.springframework.orm.jpa.LocalEntityManagerFactoryBean createNativeEntityManagerFactory
INFO: Building JPA EntityManagerFactory for persistence unit 'EclipseLink_JPA'
[EL Config]: metadata: 2021-09-28 08:56:13.763--ServerSession(712627377)--Thread(Thread[main,5,main])--The access type for the persistent class [class com.tutorialspoint.jpa.entity.Employee] is set to [FIELD].
[EL Config]: metadata: 2021-09-28 08:56:13.787--ServerSession(712627377)--Thread(Thread[main,5,main])--The alias name for the entity class [class com.tutorialspoint.jpa.entity.Employee] is being defaulted to: Employee.
[EL Config]: metadata: 2021-09-28 08:56:13.802--ServerSession(712627377)--Thread(Thread[main,5,main])--The column name for element [id] is being defaulted to: ID.
Sep 28, 2021 8:56:13 AM org.springframework.orm.jpa.LocalEntityManagerFactoryBean buildNativeEntityManagerFactory
INFO: Initialized JPA EntityManagerFactory for persistence unit 'EclipseLink_JPA'
[EL Info]: 2021-09-28 08:56:14.102--ServerSession(712627377)--Thread(Thread[main,5,main])--EclipseLink, version: Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5
[EL Fine]: connection: 2021-09-28 08:56:14.403--Thread(Thread[main,5,main])--Detected database platform: org.eclipse.persistence.platform.database.MySQLPlatform
[EL Config]: connection: 2021-09-28 08:56:14.423--ServerSession(712627377)--Connection(741883443)--Thread(Thread[main,5,main])--connecting(DatabaseLogin(
   platform=>MySQLPlatform
   user name=> "root"
   datasource URL=> "jdbc:mysql://127.0.0.1:3306/tutorialspoint?useSSL=false"
))
[EL Config]: connection: 2021-09-28 08:56:14.469--ServerSession(712627377)--Connection(2134915053)--Thread(Thread[main,5,main])--Connected: jdbc:mysql://127.0.0.1:3306/tutorialspoint?useSSL=false
   User: root@localhost
   Database: MySQL  Version: 8.0.23
   Driver: MySQL Connector/J  Version: mysql-connector-java-8.0.13 (Revision: 66459e9d39c8fd09767992bc592acd2053279be6)
[EL Info]: connection: 2021-09-28 08:56:14.539--ServerSession(712627377)--Thread(Thread[main,5,main])--file:/F:/Workspace/springorm/target/classes/_EclipseLink_JPA login successful
[EL Fine]: sql: 2021-09-28 08:56:14.602--ServerSession(712627377)--Connection(2134915053)--Thread(Thread[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: 2021-09-28 08:56:14.836--ClientSession(181326224)--Connection(2134915053)--Thread(Thread[main,5,main])--INSERT INTO Employees (DESIGNATION, NAME, SALARY) VALUES (?, ?, ?)
   bind => [Technical Manager, Julie, 10000.0]
[EL Fine]: sql: 2021-09-28 08:56:14.855--ClientSession(181326224)--Connection(2134915053)--Thread(Thread[main,5,main])--SELECT LAST_INSERT_ID()
[EL Fine]: sql: 2021-09-28 08:56:14.883--ClientSession(1573125303)--Connection(2134915053)--Thread(Thread[main,5,main])--INSERT INTO Employees (DESIGNATION, NAME, SALARY) VALUES (?, ?, ?)
   bind => [Senior Manager, Robert, 20000.0]
[EL Fine]: sql: 2021-09-28 08:56:14.885--ClientSession(1573125303)--Connection(2134915053)--Thread(Thread[main,5,main])--SELECT LAST_INSERT_ID()
[EL Fine]: sql: 2021-09-28 08:56:14.893--ClientSession(2054787417)--Connection(2134915053)--Thread(Thread[main,5,main])--INSERT INTO Employees (DESIGNATION, NAME, SALARY) VALUES (?, ?, ?)
   bind => [Software Engineer, Anil, 5000.0]
[EL Fine]: sql: 2021-09-28 08:56:14.896--ClientSession(2054787417)--Connection(2134915053)--Thread(Thread[main,5,main])--SELECT LAST_INSERT_ID()
[EL Fine]: sql: 2021-09-28 08:56:14.929--ServerSession(712627377)--Connection(2134915053)--Thread(Thread[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

Sep 28, 2021 8:56:14 AM org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
INFO: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@5383967b: startup date [Tue Sep 28 08:56:12 IST 2021]; root of context hierarchy
[EL Config]: connection: 2021-09-28 08:56:14.935--ServerSession(712627377)--Connection(2134915053)--Thread(Thread[main,5,main])--disconnect
Sep 28, 2021 8:56:14 AM org.springframework.orm.jpa.LocalEntityManagerFactoryBean destroy
INFO: Closing JPA EntityManagerFactory for persistence unit 'EclipseLink_JPA'
[EL Info]: connection: 2021-09-28 08:56:14.936--ServerSession(712627377)--Thread(Thread[main,5,main])--file:/F:/Workspace/springorm/target/classes/_EclipseLink_JPA logout successful
[EL Config]: connection: 2021-09-28 08:56:14.936--ServerSession(712627377)--Connection(741883443)--Thread(Thread[main,5,main])--disconnect

此处项目使用 Spring 配置构建和运行。创建了一个 Employee 表,其中包含三条记录。您可以使用 MySQL 控制台验证这一点。

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>
广告