java - List 或 Set<String> 的 JPA 映射

标签 java hibernate maven jpa orm

作为 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/

相关文章:

eclipse - 在 Eclipse 中设置 Scala Lift 项目

java - 让 Maven 和 module-info 协同工作

java - 使用 Mockito 匹配对象数组

java - Spring 与 Java 反射

java - 处理 XML 时发生错误“无法加载类 [org.springframework.transaction.annotation.AnnotationTransactionAttributeSource]

java - 用于 Spring Boot 的 GraphQL Java 客户端

javascript - 我一直坚持在 javascript 中进行 AES 加密,然后在 JAVA spring 中进行解密

java - 对于类型 TreeMap<MyTime,Integer> ,方法 heavenEntry(MyTime) 未定义

java - 使用基于映射键的 HQL 选择值

SQl 查询到 hibernate 查询