我正在使用spring-data和hibernate创建表并插入Data。从不同的线程中,我发现JPARepository(来自CRUDRepository)的save方法仅在记录已存在的情况下才更新记录。以下是我找到一些信息的线程之一:
https://stackoverflow.com/a/40608937/10356053
我有一个正在复制记录的实体(即使对象相同,jpa仍将其视为新插入内容)。我不太确定发生了什么或该问题的解决方案。任何建议表示赞赏。以下是我创建的实体:
CustomerEntity.java:
@Getter
@Setter
@Table(name = "Customers")
@Entity
public class CustomersEntity extends BasicEntity {
@Id
@GeneratedValue(generator = "UUID")
@GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
@Column(name = "CustomerId", updatable = false, nullable = false)
private UUID customerid;
//and some other fields
}
BasicEntity.java:
@Getter
@Setter
public class BasicEntity implements serializable {
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "created_at", updatable = false)
@CreatedDate
private Date createdAt;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "updated_at")
@LastModifiedDate
private Date updatedAt;
}
Repository.java
@Repository
public interface Repositorty extends JpaRepository<CustomersEntity, UUID> {
}
当我们尝试保存上述实体时:
repository.save(customerEntity)
将作为新记录保留在数据库中。任何建议都是有帮助的。我在想这是由于父类的createdTime和updatedTime吗?如果是,我们如何避免这种情况? TIA。
答案 0 :(得分:1)
将columnDefinition = "BINARY(16)"
添加到客户ID的@Column
属性中。
@Getter
@Setter
@Table(name = "Customers")
@Entity
public class CustomersEntity extends BasicEntity {
@Id
@GeneratedValue(generator = "UUID")
@GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
@Column(name = "CustomerId", updatable = false, nullable = false, columnDefinition = "BINARY(16)")
private UUID customerid;
//and some other fields
}
没有它的customer_id
列使用256个字节(在MySQL中),这很可能导致UUID公式在随后保存相同实体对象(解释重复创建)时失败。