如何在没有额外的联接表的情况下使用Hibernate / JPA映射List <string>?

时间:2018-11-01 20:32:36

标签: java hibernate jpa

我要问的问题很简单,但似乎找不到答案。我使用的是Spring Data JPA,我有一个JDBC / JPA DataSource(这是PostgreSQL,但这没关系),它已预先加载了数据,而我只是想从中读取数据。

如何构造POJO,以便可以拥有不需要额外联接表的List<String>字段?这是我拥有的示例实体类:

@Entity
@Table(name = "pojo", schema = "pojoschema")
public class POJO {
  @Id
  @Column(name = "id", columnDefinition = "uuid")
  private String id;

  @Column(name = "a_string", columnDefinition = "text")
  private String aString;

  @Column(name = "strings", columnDefinition = "text[]")
  @ElementCollection
  private List<String> strings;

  // getters/setters
}

这样做我得到一个org.postgresql.util.PSQLException: ERROR: relation "pojo_strings" does not exist

为什么休眠方式认为我想要的String位于另一个表中?如何解决此问题?我只是试图通过JPA将PostgreSQL text[]列映射回POJO中的List<String>

1 个答案:

答案 0 :(得分:1)

在这些情况下,方法是使用jpa的AttributeConverter,如下所示:

@Converter
public class StringToListConverter implements AttributeConverter<List<String>, String> {

  @Override
  public String convertToDatabaseColumn(List<String> list) {
    return String.join(",", list); 
  }

  @Override
  public List<String> convertToEntityAttribute(String joined) {
    return new ArrayList<>(Arrays.asList(joined.split(",")));
  }

}

并在您的实体字段中使用注释Converter

@Entity
@Table(name = "pojo", schema = "pojoschema")
public class POJO {
  @Id
  @Column(name = "id", columnDefinition = "uuid")
  private String id;

  @Column(name = "a_string", columnDefinition = "text")
  private String aString;

  @Column(name = "strings")
  @Convert(converter = StringToListConverter.class)
  private List<String> strings;

  // getters/setters
}