简体   繁体   中英

How to set initial value for @Id @GeneratedValue in Spring JPA for MySQL?

I can not figure out how to set the initial value for the @GenerateValue @Id .

I have tried using GenerationType.SEQUENCE but that is not allowed in MySQL . How can I set the initial value to be used for the @GenerateValue ?

Using both AUTO and TABLE I can still not get the initial value to start at anything but 1

Thank you

Code using 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() {

    }
}

Code using 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() {

    }
}

** UPDATE **

The problem was related to not setting hibernate.id.new_generator_mappings=true;

https://docs.jboss.org/hibernate/stable/annotations/reference/en/html/ch01.html

Application.properties for Sring Boot:

spring.jpa.properties.hibernate.id.new_generator_mappings=true

You could try and use the @TableGenerator (JPA has a @TableGenerator annotation in which you can set an initial value). The initialValue can be used to seed the values

Example here : http://www.java2s.com/Code/Java/JPA/SetInitialValueOfTableGenerator.htm

this worked for me:

@Id
@GenericGenerator(
    name = "customers-sequence-generator",
    strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
    parameters = {
            @Parameter(name = "sequence_name", value = "customers_sequence"),
            @Parameter(name = "initial_value", value = "1000"),
            @Parameter(name = "increment_size", value = "1")
    })
@GeneratedValue(generator = "customers-sequence-generator")
@Column(nullable=false, updatable=false)
@JsonProperty("id")
private long id;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM