Home > database >  How can I make an auto-incremental id in springBoot
How can I make an auto-incremental id in springBoot

Time:11-30

I am learning spring boot but in the part of creating the models for the creation in mysql, but I need the id field to be auto-incremental, does anyone know how I can do it?

`

package com.pruebas.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Persona {
    
    
    @Id 
    private Integer id;
    

    @Column
    private String title;
    
    @Column 
    private String description;
    
    
    //Getter and setter

    public Integer getId() {
        return id;
    }
    
    public void setId(Integer id) {
        this.id = id;
    }
    
    public String getTitle() {
        return title;
    }
    
    public void setTitle(String title) {
        this.title = title;
    }
    
    public String getDescription() {
        return description;
    }
    
    public void setDescription(String description) {
        this.description = description;
    }

    
    
}

`

I was looking for some property and I even put in the part of id AUTO_INCREMENT how the query would be done in MySql

CodePudding user response:

You can use below annotation in your document

@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;

CodePudding user response:

You can add auto_increment to the column in your mysql ddl and you can use @GeneratedValue annotation in your entity class on top of the related attribute.

For example in your case;

@Id 
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
  • Related