Spring Data JPA 配置 ID 自增无效

我的SQL 脚本如下:

启动 Spring boot,Flyway 会自动执行它。

CREATE TABLE speiseplan(
   ID SERIAL PRIMARY KEY,
   NAME varchar(50) NOT NULL,
   PREIS numeric(7,1),
   ART int,
   WOCHENTAG integer,
   CONSTRAINT fk_wochentage FOREIGN KEY(WOCHENTAG) REFERENCES wochentage(ID),
   CONSTRAINT fk_speisenart FOREIGN KEY(ART) REFERENCES speisenart(ID)
);

SpeiseplanEntity 实体类如下:

@Entity
@Table(name = "speiseplan")
public class SpeiseplanEntity {
    @Id
    @Column(name = "id")
    private Integer id;

    @Column(name = "name")
    private String name;
    @Column(name = "preis")
    private BigDecimal preis;
    @Column(name = "art")
    private String art;

    protected SpeiseplanEntity(){}

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public BigDecimal getPreis() {
        return preis;
    }

    public void setPreis(BigDecimal preis) {
        this.preis = preis;
    }

    public String getArt() {
        return art;
    }

    public void setArt(String art) {
        this.art = art;
    }


    @Override
    public String toString() {
        return "SpeiseplanEntity{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", preis=" + preis +
                ", art='" + art + '\'' +
                '}';
    }
}

当我尝试调用 API 保存新的实体对象到数据库时,如果不传 ID 则会出现异常:

Identifier of entity '... .SpeiseplanEntity' must be manually assigned before calling 'persist()'

如果请求 API 的时候手动设置一个 ID 就没有问题:

POST http://localhost:8080/api/speise/createSpeise
Content-Type: application/json

{
  "id": 1,  // 手动设置 ID
  "name": "Test2",
  "preis": "13.5",
  "art": "A"
}

找到问题原因了,我忘记在 @Id 注解下面添加 @GenerateValue 注解。

修改一下,就 Ok 了:

public class SpeiseplanEntity {
    @Id
    // 设置ID自增
    @GeneratedValue(strategy = GenerationType.AUTO) 
    @Column(name = "id")
    private Integer id;

  // 其他代码忽略 ....
}