我正在开发一个必须部署在多个环境中的应用程序,使用不同的 RDBMS,即 MySQL、MariaDB 和 Oracle。这意味着不同的 ID 生成模式(自动递增与序列)。
JPA 应该允许从 RDBMS 进行抽象。但是,我不知道如何配置 @Id
字段,以便它可以同时使用自动递增和序列。
// Auto-increment
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// Sequence
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
private Long id;
最佳答案
引用资料,我找到了答案,好像有些公司遇到了同样的困难。目前已有答案here .
主要思想是:
- 使用
SEQUENCE
生成策略设计您的实体; - 提供覆盖基于 Java 的注释映射的 JPA XML 映射文件;
- 在使用 MySQL(或其他序列不兼容的 RDBMS)运行时加载此映射文件。
这是可能的,因为:
XML metadata may be used as an alternative to these annotations, or to override or augment annotations
— JPA 2.1 specification, 11.1 Annotations for Object/Relational Mapping
例如,引用我上面链接的文章的例子,实体将是:
@Entity(name = "Post")
@Table(name = "post")
public class Post {
@Id
@GeneratedValue(
generator = "sequence",
strategy = GenerationType.SEQUENCE
)
@SequenceGenerator(
name = "sequence",
allocationSize = 10
)
private Long id;
private String title;
//Getters and setters omitted for brevity sake
}
映射文件是:
<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings
xmlns="http://xmlns.jcp.org/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence/orm orm_2_1.xsd"
version="2.1"
>
<package>com.vladmihalcea.book.hpjp.hibernate.identifier.global</package>
<entity class="Post" access="FIELD">
<attributes>
<id name="id">
<generated-value strategy="IDENTITY"/>
</id>
</attributes>
</entity>
</entity-mappings>
有关技术方面以及为什么不使用 AUTO
策略的更多信息,请参阅 the article .
关于mysql - 有没有办法使用@GeneratedValue 使其同时适用于序列和自动递增?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50841647/