【问题标题】:Configure Hibernate globally to use GenerationType.IDENTITY全局配置 Hibernate 以使用 GenerationType.IDENTITY
【发布时间】:2018-07-02 19:59:12
【问题描述】:
由于 Spring Boot 2 使用 Hibernate 5,我的 MySQL 5.7 数据库的 @GeneratedValue 默认策略 GenerationType.AUTO 导致 GenerationType.SEQUENCE 在单独的表中模拟,因为 MySQL 5.7 不支持序列。
我希望使用GenerationType.IDENTITY 生成所有表的主 ID。
是否有一种全局方法可以将其设置为默认策略,因此我每次在字段上使用 @GeneratedValue 时不必明确选择 GenerationType.IDENTITY 策略?
【问题讨论】:
标签:
java
spring
hibernate
spring-boot
【解决方案1】:
让所有实体使用同一个生成器的一种简单方法是拥有一个 @MappedSuperclass,它定义了 @Id 字段并使用您希望的生成策略,然后在您的实体中扩展该类。
除了希望实体拥有的主键之外,您还可以定义其他属性。如果您想要拥有不同“类型”的实体,也可以定义额外的 @MappedSuperclass 类,即只定义了 pk 的实体,或者像 created 或 updated 这样的附加字段。
@MappedSuperclass
public class PKEntity {
@Id
@GenericGenerator(name="universal", etc. etc. etc.)
@GeneratedValue(generator="universal")
private Long id;
// Possibly more common columns your entities have
}
【解决方案2】:
您可以尝试创建自己的注释并使用它来代替@GeneratedValue
import javax.persistence.GenerationType;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomGeneratedValue {
GenerationType strategy() default GenerationType.IDENTITY;
String generator() default "";
}