Java JPA GenerationType.Auto 值始终为空
Java JPA GenerationType.Auto value always null
我在同一个项目中有多个 类,其中的 ID 始终是自动生成的。但是,在这种特定情况下,我的 id 的值恰好始终为 null。我真的很想知道出了什么问题,因为经过一些更改后它停止工作了。并将其与其他代码进行比较 类 代码似乎相同。
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;}
}
这是保存对象的存储库:
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, Long> {
Checkin findById(Long id);
}
最后这是我从 Postman 那里得到的结果
enter image description here
生成类型AUTO
设置底层数据库生成ID
http://docs.oracle.com/javaee/6/api/javax/persistence/GenerationType.html#AUTO
在这种情况下,您要检查的是H2数据库id列是否具有生成ID的属性。我猜它不会。我自己不太使用 AUTO,所以我假设如果您的 Auto 对其他 Entities
有效,那么它们设置正确。
您可能需要执行以下操作之一:
- 迁移到这里
- 更新 H2 中的列
- 重新创建 table
我在同一个项目中有多个 类,其中的 ID 始终是自动生成的。但是,在这种特定情况下,我的 id 的值恰好始终为 null。我真的很想知道出了什么问题,因为经过一些更改后它停止工作了。并将其与其他代码进行比较 类 代码似乎相同。
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;}
}
这是保存对象的存储库:
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, Long> {
Checkin findById(Long id);
}
最后这是我从 Postman 那里得到的结果
enter image description here
生成类型AUTO
设置底层数据库生成ID
http://docs.oracle.com/javaee/6/api/javax/persistence/GenerationType.html#AUTO
在这种情况下,您要检查的是H2数据库id列是否具有生成ID的属性。我猜它不会。我自己不太使用 AUTO,所以我假设如果您的 Auto 对其他 Entities
有效,那么它们设置正确。
您可能需要执行以下操作之一:
- 迁移到这里
- 更新 H2 中的列
- 重新创建 table