Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
979 views
in Technique[技术] by (71.8m points)

hibernate - Convert list in entity to single string column in database

I have a VARCHAR field in my database, and the value of this field is val1,val2,val3.

Is it possible to set this into an ArrayList<String> attribute of an entity using comma as split delimiter?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you use JPA 2.1, then you can create an AttributeConverter:

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

  @Override
  public String convertToDatabaseColumn(List<String> list) {
    // Java 8
    return String.join(",", list); 
    // Guava
    return Joiner.on(',').join(list); 
  }

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

}

You can use this converter in your entity:

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

For before JPA 2.1 you could do this by hand:

@Entity
private MyEntity {
  ...
  private String strings;

  public List<String> getStrings() {
    return Arrays.asList(strings.split(","));
  }

  public void setStrings(List<String> list) {
    strings = String.join(",", list);
  }
}

I wrap Arrays.asList in an ArrayList in the converter, because the result is stored in the attribute and any change to that list will be written back to the database - thus I need a changeable list (I can't add anything to the result of Arrays.asList). In the before 2.1 solution the result is not connected with the attribute and a changeable list would not be synchronized with the attribute.

To query for an entity that contains a specific item in such an attribute, see my answer here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...