Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 728
ALM Avatar asked Nov 09 '22 11:11

ALM


1 Answers

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

like image 162
Ramachandran.A.G Avatar answered Nov 14 '22 23:11

Ramachandran.A.G