【问题标题】:Document field as primary key not working文档字段作为主键不起作用
【发布时间】:2022-08-15 17:52:31
【问题描述】:

我有一个 \"document\" 字段,它需要是主键并且必须是唯一的,但是每次我对同一个文档进行 POST 时,它都会更新文档并且不会发送 BAD_REQUEST

我的实体:

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Table(uniqueConstraints={@UniqueConstraint(columnNames={\"document\"})})
public class Cliente {

    @Id
    @Column(unique=true, updatable = false)
    @NotBlank @NotNull
    private String document;
    @NotBlank
    private String name;
    @NotNull
    private LocalDateTime date;
}

当我尝试使用相同的文档创建新的 POST 时,它只会更新数据库中保存的内容。

\"Hibernate: update client set date=?, name=? where document=?\"

  • 如果文档存在,它将更新,如果不存在,它将插入。 POST 时尝试设置文档新值

标签: spring spring-boot hibernate spring-data-jpa spring-data


【解决方案1】:

问题是 Spring Data JPA 在您调用 Repository#save 时假定您要在传入的实体对象具有 id 属性集时更新现有实体。如果您想确保 Hibernate 尝试执行插入操作,则必须在代码中注入 EntityManager 并调用 EntityManager#persist,在这种情况下,您将得到约束违反异常,正如您所期望的那样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-02
    • 2015-06-22
    • 2012-01-20
    • 2018-07-22
    • 1970-01-01
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多