Reputation: 827
I have an entity that need to have an unique key (not primary) of UUID type.
@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:
@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)
Upvotes: 5
Views: 5536
Reputation: 137
After several searches, here are some proposals:
Ex1
@Id
@Column(columnDefinition = "BINARY(16)")
private UUID id = UUID.randomUUID();
Ex2
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid")
@Column(columnDefinition = "CHAR(32)")
private String id;
Link : enter link description here
Upvotes: -2
Reputation: 9482
You need to Map the UID to String. You need to use a UserType if there is no standard mapping from UID to String.
Or alternativly just use String instead of UUID for the attribute.
You can read the alternatives of mapping UUID in chapter 3.10 of Hibernate documentation
You can use EntityListener instead of setting the ID in the service you can set it in the @PrePersist method.
@Entity
public class MyEntity {
@PrePersist
private assignUIID(){
myEntity.setUUID(UUID.randomUUID());
}
}
Upvotes: 3