1. 概述

默认情况下,Spring Data 使用 Hibernate 作为 JPA 实现提供者。但 Hibernate 并非唯一选择。

本文将详细介绍如何在 Spring Data JPA 中配置 EclipseLink 作为替代实现方案。整个过程简单直接,只需几个关键步骤即可完成切换。

2. Maven 依赖配置

要在 Spring 项目中使用 EclipseLink,只需在 pom.xml 中添加以下依赖:

<dependency>
    <groupId>org.eclipse.persistence</groupId>
    <artifactId>org.eclipse.persistence.jpa</artifactId>
    <version>2.7.0</version>
</dependency>

⚠️ 重要提醒:Spring Data 默认包含 Hibernate 实现。既然要改用 EclipseLink,我们需要排除 Hibernate 相关依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>

下一步就是告知 Spring 框架使用 EclipseLink 作为 JPA 实现提供者。

3. Spring 配置详解

JpaBaseConfiguration 是 Spring Boot 中定义 JPA 相关 Bean 的抽象类。要自定义配置,我们需要实现以下方法:

  • createJpaVendorAdapter()
  • getVendorProperties()

Spring 为 Hibernate 提供了开箱即用的 HibernateJpaAutoConfiguration,但 EclipseLink 需要我们手动创建配置类。

3.1 创建 JPA 厂商适配器

首先实现 createJpaVendorAdapter() 方法,指定要使用的 JPA 实现:

@Configuration 
public class EclipseLinkJpaConfiguration extends JpaBaseConfiguration { 

    @Override 
    protected AbstractJpaVendorAdapter createJpaVendorAdapter() { 
        return new EclipseLinkJpaVendorAdapter(); 
    }
    
    //...
}

Spring 提供了专门针对 EclipseLink 的 EclipseLinkJpaVendorAdapter 实现,直接使用即可。

3.2 配置厂商特定属性

接下来通过 getVendorProperties() 方法定义 EclipseLink 专有属性:

@Override
protected Map<String, Object> getVendorProperties() {
    HashMap<String, Object> map = new HashMap<>();
    map.put(PersistenceUnitProperties.WEAVING, true);
    map.put(PersistenceUnitProperties.DDL_GENERATION, "drop-and-create-tables");
    return map;
}

org.eclipse.persistence.config.PersistenceUnitProperties 类包含所有可配置属性。本示例中:

  • 启用了字节码增强(Weaving)
  • 设置应用启动时重建数据库表结构

关键点:至此,从默认 Hibernate 切换到 EclipseLink 的核心配置已完成。

踩坑提示:Spring Data 使用标准 JPA API,不依赖厂商特定方法,理论上切换实现不会产生兼容性问题。

4. 总结

本教程展示了如何快速替换 Spring Data 的默认 JPA 实现提供者。从 Hibernate 迁移到 EclipseLink 的过程简单高效,只需:

  1. 添加 EclipseLink 依赖
  2. 排除 Hibernate 依赖
  3. 创建自定义配置类

完整示例代码可在 GitHub 仓库 获取。


原始标题:A Guide to EclipseLink with Spring | Baeldung