有人知道如何在实体中使用JPA 2.1创建Set
String
类型吗?我希望它作为目录工作,因此不存在重复的值(如枚举)。
我试过了:
@ElementCollection(fetch = FetchType.EAGER, targetClass = String.class)
@CollectionTable(
name = "transactions_labels",
joinColumns = @JoinColumn(name = "id"),
foreignKey = @ForeignKey(name = "transaction_id"),
uniqueConstraints = @UniqueConstraint(columnNames = "label", name = "unique_label")
)
@Column(name = "label")
public Set<String> labels;
不幸的是,这会在transactions_labels
表格中创建重复项,其中多个条目在transactions_labels.label
中包含相同的值。
我希望JPA在插入新值之前检查该值是否存在。
这可能吗?
JPA坚持:
TransactionEntity transactionEntity = new TransactionEntity();
entityManager.persist(transactionEntity);
[...]
transactionEntity.labels = new HashSet<>();
transactionEntity.labels.add("some_tag_1");
transactionEntity.labels.add("some_tag_2");
transactionEntity.labels.add("some_tag_3");
[...]
entityManager.getTransaction().commit();
Hibernate生成的SQL(删除了一些字段):
Hibernate:
insert
into
transactions
([...])
values
(?, ?, ?, ?, ?, ?, ?, ?)
Hibernate:
update
transactions
set
[...]
where
id=?
Hibernate:
insert
into
transactions_labels
(id, label)
values
(?, ?)
Hibernate:
insert
into
transactions_labels
(id, label)
values
(?, ?)
Hibernate:
insert
into
transactions_labels
(id, label)
values
(?, ?)