skip to Main Content

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

2

Answers


  1. You can use below annotation in your document

    @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;
    
    Login or Signup to reply.
  2. 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;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search