由于Spring 2使用Hibernate 5,所以我的@GeneratedValue 5.7数据库的GenerationType.AUTO默认策略会在单独的表中模拟GenerationType.SEQUENCE,因为MySQL 5.7不支持序列。
我希望使用GenerationType.IDENTITY生成所有表的主I。
是否有一种全局方法将其设置为默认策略,因此每次在字段中使用GenerationType.IDENTITY策略时都不必显式地选择@GeneratedValue策略?
发布于 2018-07-02 11:53:54
所有实体使用相同生成器的一种简单方法是有一个@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
}发布于 2018-07-02 11:48:35
您可以尝试创建自己的注释,并使用它而不是@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 "";
}https://stackoverflow.com/questions/51135345
复制相似问题