[英]How to use a UUID field without being a primary key with JPA?
I have an entity that need to have an unique key (not primary) of UUID type.我有一个需要 UUID 类型的唯一键(不是主键)的实体。
@Entity
public class MyEntity {
@Id
@NotNull
@GeneratedValue(strategy = SEQUENCE, generator = "seq_entity")
@SequenceGenerator(name = "seq_entity", sequenceName = "seq_entity", allocationSize = 1)
private Long id;
@NotNull
@Type(type = "pg-uuid")
@Column(name = "uu_id", unique = true)
private UUID uuid;
@NotNull
@Size(max = 30)
private String name;
// gets and sets
}
When I persist this entity how can be seen below in my DAO class:当我坚持这个实体时,如何在我的 DAO 类中看到:
@Transactional
public class EntityDAO {
@Inject
private EntityManager em;
public void insert(MyEntity myEntity) { //myEntity comes only with name attribute
myEntity.setUUID(UUID.randomUUID()); //I'd like to generate automatically by the database
em.persist(myEntity);
}
}
Is ocurring the inserting in the database but the following error appears on the console:正在数据库中发生插入但控制台上出现以下错误:
09:09:43,529 SEVERE [br.gov.frameworkdemoiselle.exception] (http-/127.0.0.1:8080-1) Erro interno do servidor: org.yaml.snakeyaml.error.YAMLException: No JavaBean properties found in java.util.UUID
at org.yaml.snakeyaml.introspector.PropertyUtils.getProperties(PropertyUtils.java:97)
at org.yaml.snakeyaml.introspector.PropertyUtils.getProperties(PropertyUtils.java:87)
at org.yaml.snakeyaml.representer.Representer.getProperties(Representer.java:243)
You need to Map the UID to String.您需要将 UID 映射到字符串。 You need to use a UserType if there is no standard mapping from UID to String.如果没有从 UID 到 String 的标准映射,则需要使用 UserType。
Or alternativly just use String instead of UUID for the attribute.或者,只使用 String 而不是 UUID 作为属性。
You can read the alternatives of mapping UUID in chapter 3.10 of Hibernate documentation您可以在Hibernate 文档的第 3.10 章中阅读映射 UUID 的替代方案
You can use EntityListener instead of setting the ID in the service you can set it in the @PrePersist method.您可以使用 EntityListener 而不是在服务中设置 ID,您可以在 @PrePersist 方法中设置它。
@Entity
public class MyEntity {
@PrePersist
private assignUIID(){
myEntity.setUUID(UUID.randomUUID());
}
}
After several searches, here are some proposals:经过多次搜索,这里有一些建议:
Ex1例1
@Id
@Column(columnDefinition = "BINARY(16)")
private UUID id = UUID.randomUUID();
Ex2例2
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid")
@Column(columnDefinition = "CHAR(32)")
private String id;
Link : enter link description here链接:在此处输入链接描述
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.