[英]Configure Hibernate globally to use GenerationType.IDENTITY
Since Spring Boot 2 use Hibernate 5 the @GeneratedValue
default strategy GenerationType.AUTO
for my MySQL 5.7 database results in GenerationType.SEQUENCE
emulated in a separate table, since MySQL 5.7 doesn't support sequences. 由于Spring Boot 2使用了Hibernate 5,我的MySQL 5.7数据库的
@GeneratedValue
默认策略GenerationType.AUTO
导致GenerationType.SEQUENCE
在单独的表中模拟,因为MySQL 5.7不支持序列。
I want all of my tables' primary ids to be generated using GenerationType.IDENTITY
. 我希望所有表的主要ID均使用
GenerationType.IDENTITY
。
Is there a global way to set this to be the default strategy, so I don't explicitly have to select the GenerationType.IDENTITY
strategy each time I use @GeneratedValue
on a field? 是否有全局方法将其设置为默认策略,所以我不必每次在字段上使用
@GeneratedValue
时都必须明确选择GenerationType.IDENTITY
策略?
An easy way to use the same generator by all your entities is to have a @MappedSuperclass
that defines the @Id
field and uses what generation strategy you wish, then extending that class in your entities. 所有实体使用同一生成器的一种简单方法是拥有一个
@MappedSuperclass
,它定义@Id
字段并使用所需的生成策略,然后在您的实体中扩展该类。
You can additionally define other attributes besides the primary key you want your entities to have. 除了您想要实体拥有的主键之外,您还可以定义其他属性。 You can also define additional
@MappedSuperclass
classes if you want to have different "types" of entities, ie ones with just the pk defined, or with additional fields like created
or updated
. 您也可以定义附加
@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
}
You could try creating your own annotation and using it instead of @GeneratedValue
您可以尝试创建自己的注释并使用它代替
@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 "";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.