我不知道如何为 @GenerateValue
@Id
设置初始值。
我试过使用 GenerationType.SEQUENCE
但 MySQL
不允许这样做。如何设置用于 @GenerateValue
的初始值?
同时使用 AUTO
和 TABLE
除了 1
谢谢
代码使用AUTO
@Entity
@Data
@SequenceGenerator(name = "port_gen", sequenceName = "port_gen", initialValue = 4700)
public class AppiumPort {
@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "port_gen")
private Long port;
public AppiumPort() {
}
}
使用 TABLE 的代码
@Entity
@Data
public class AppiumPort {
@TableGenerator(name = "Address_Gen", table = "ID_GEN", pkColumnName = "GEN_NAME", valueColumnName = "GEN_VAL", pkColumnValue = "Addr_Gen", initialValue = 10000, allocationSize = 100)
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "Address_Gen")
private int port;
public AppiumPort() {
}
}
**更新**
问题与没有设置hibernate.id.new_generator_mappings=true有关;
https://docs.jboss.org/hibernate/stable/annotations/reference/en/html/ch01.html
Sring Boot 的 Application.properties:
spring.jpa.properties.hibernate.id.new_generator_mappings=true
最佳答案
您可以尝试使用@TableGenerator(JPA 有一个@TableGenerator 注释,您可以在其中设置初始值)。 initialValue 可用于为值设定种子
此处示例:http://www.java2s.com/Code/Java/JPA/SetInitialValueOfTableGenerator.htm
关于java - 如何在 Spring JPA for MySQL 中为 @Id @GeneratedValue 设置初始值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38537463/