【问题标题】:JPA overwrite record with auto_increment primary keyJPA 使用 auto_increment 主键覆盖记录
【发布时间】:2018-11-06 14:21:56
【问题描述】:

我已经搜索过,但没有找到适合我的。我有一个像这样的实体类,亲爱的:

@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

一些帮助将不胜感激

【问题讨论】:

  • 您应该使用 GenerationType.AUTO 而不是 IDENTITY。还要确保你有 spring.jpa.hibernate.ddl-auto = update in application.properties

标签: java mysql spring hibernate jpa


【解决方案1】:

首先,将您的 int 更改为 Long。您可以省略该策略,因为对于 MySQL,GenerationType.IDENTITYGenerationType.AUTO 相同,相当于只需添加 @GeneratedValue

@Id @GeneratedValue
private Long id;

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2011-03-21
      • 1970-01-01
      • 1970-01-01
      • 2012-12-21
      • 1970-01-01
      • 2011-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多