我正在尝试将 ID 中类型为 String 的值插入到数据库中。
@Entity
@Table(name = "xpto_version_map")
public class XptoVersionMap implements Serializable {
@Id
@Column(name = "uniq_name", unique = true, nullable = false)
private String uniq_name;
...
当尝试保存新的 XptoVersionMap() 时,例如:
XptoVersionMap xptoVersionMap = new XptoVersionMap();
xptoVersionMap.setUniqName("XPTO-1");
xptoVersionMap.setValue("value2");
xptoVersionMapRepository.save(xptoVersionMap);
将抛出:
org.springframework.orm.jpa.JpaObjectRetrievalFailureException: Unable to find xxx.api.database.entity.XptoVersionMap with id XPTO-1; nested exception is javax.persistence.EntityNotFoundException: Unable to find xxx.api.database.entity.XptoVersionMap with id XPTO-1.
我尝试了不同的解决方案,但除非我可以进行 native 查询来插入值,否则我无法告诉 Hibernate 我只想检查 @Id (uniq_name) 是否存在(如果不存在)插入新值并且不引发异常。
最佳答案
这就是 Hibernate 默认的工作方式。当您执行保存方法且未设置 ID 时,它会分配自动生成的 ID。如果有 ID,它会尝试更新它(在您的情况下会发生什么)。
save Persists an entity. Will assign an identifier if one doesn't exist. If one does, it's essentially doing an update. Returns the generated ID of the entity.
您可以采取解决方法,例如使用 persist 和 @PrePersist
@PrePersist
void generateId() {
if (uniq_name == null) {
uniq_name = GENERATE_SOME_UNIQUE_ID_SO_IT_DOESN'T_BREAK();
}
}
然后使用 xptoVersionMapRepository.persist(xptoVersionMap);
或者你可以用类似的东西编写你自己的生成器:
@GenericGenerator(name = "my_generator", strategy = "package.CustomGenerator")
@GeneratedValue(generator = "my_generator")
然后创建一个实现 IdentifierGenerator 的类 CustomGenerator 并创建所需的方法。
关于java - 使用非自动生成的 ID 保存在 JPA/Hibernate 中的替代方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50156344/