作为 ORM 的新手,我想找到一种方法来为实体中的字符串列表(或一组)定义一个简单的(意味着没有额外的实体)映射。我找到了这个样本:
import java.util.Set;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Book {
@Id
@GeneratedValue
private Long id;
@ElementCollection
@CollectionTable(name = "tags")
private Set<String> tags;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Set<String> getTags() {
return tags;
}
public void setTags(Set<String> tags) {
this.tags = tags;
}
}
这似乎符合我的需要。但是,使用 Eclipse 的 hibernate3-maven-plugin:2.2:hbm2ddl
处理此类时,我最终遇到以下错误:
[ERROR] Failed to execute goal org.codehaus.mojo:hibernate3-maven-plugin:2.2:hbm2ddl (default) on project test-database: Execution default of goal org.codehaus.mojo:hibernate3-maven-plugin:2.2:hbm2ddl failed: Could not determine type for: java.util.Set, at table: Book, for columns: [org.hibernate.mapping.Column(tags)] -> [Help 1]
指定 @ElementCollection(targetClass=String.class)
没有帮助。将列定义添加到 tags
字段 (@Column(name = "tags", columnDefinition="character varying (255)", nullable = false)
) 会导致构建成功但生成此 SQL:
create table Book (
id int8 not null,
tags character varying (255) not null,
primary key (id)
);
这不是我想要的,因为我期望最终得到一个链接到 books 表的 tags
表。有人能指出我正确的方向吗?谢谢。
最佳答案
@ElementCollection 已在 JPA v 2.0 中引入:您所做的映射是正确的。但是请确保您使用的 maven hibernate 插件版本正确。从 3.5 版开始,Hibernate 本身与 JPA 2.0 兼容。
关于java - List 或 Set<String> 的 JPA 映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31967221/