JPA使用auto_increment主键覆盖记录

时间:2018-11-06 14:21:56

标签: java mysql spring hibernate jpa

我已经搜索过,但找不到我。我有一个类似这样的实体类:

@Entity
public class Report {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;
    @Column(name = "descrizione")
    private String descrizione = null;

    public int getId() {
        return id;
    }

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

    public String getDescrizione() {
        return descrizione;
    }

    public void setDescrizione(String descrizione) {
        this.descrizione = descrizione;
    }   
}

然后使用auto_increment pk将表插入mysql db。但是我不知道为什么auto_increment仅在启动Web服务时才能工作。以后,休眠只覆盖最后一条记录,而无需使用自动递增的主键创建新记录。

进入application.properties,我具有以下配置:

spring.jpa.hibernate.ddl-auto=none
spring.datasource.url=jdbc:mysql://localhost:3306/civicsense?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=AAAAAAA

某些帮助将不胜感激

2 个答案:

答案 0 :(得分:0)

您需要更改:
@GeneratedValue(strategy = GenerationType.IDENTITY)
用于
@GeneratedValue(strategy = GenerationType.AUTO)

并在application.properties中使用:
spring.jpa.hibernate.ddl-auto=update

答案 1 :(得分:0)

首先,将int更改为Long。而且您可以省略该策略,因为对于MySQL,GenerationType.IDENTITYGenerationType.AUTO相同,等同于仅添加@GeneratedValue

@Id @GeneratedValue
private Long id;

此外,您的问题可能是您添加实体的方式。在这种情况下,您可能要使用saveAndFlush(),因为更改将立即在此命令中刷新到DB,这可能会避免您的问题,因为您的实际方法可能未按时提交。