I have several classes in the same project in which the id is always autogenerated. However in this specific case the value of my id happens to be always null. I'm really wondering what is wrong, because after some changes it stopped working. And comparing it with the other classes the code seems to be the same.
package com.checkin.model.entity;
import javax.persistence.*;
@Entity
public class Checkin {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false)
private String date;
public Checkin(){
}
public Checkin(String date){
this.date = date;
System.out.println(this.id);
System.out.println(this.getId());
}
public Long getId() {return id;}
public void setId(Long id) {this.id = id;}
public String getDate() {return date;}
public void setDate(String date) {this.date = date;}
}
This is the repository where the objects are saved:
package com.checkin.model.repository;
import com.checkin.model.entity.Checkin;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository("checkinRepository")
public interface CheckinRepository extends CrudRepository {
Checkin findById(Long id);
}
and finally this is the result that I get from Postman
解决方案
In this case, what you want to check is if the H2 database id column has the attribute to generate IDs. I am guessing it does not. I dont use AUTO much myself so I am assuming if your Auto works for other Entities then those are setup correctly.
You may need to do one of the following:
migration here
update column in H2
recreate the table