How to persist a List of Strings in Hibernate?

JavaStringHibernateListAnnotations

Java Problem Overview


I seem to have problems with mapping a List in Hibernate. In our project there a class Card with contains a class Answer with Answer containing a List<String>.

Is a List<String> mappable by Hibernate using annotations? I mean, since it does not have the @Entity annotation?

Regards

Java Solutions


Solution 1 - Java

Use @ElementCollection:

@ElementCollection
@CollectionTable(name="Nicknames", joinColumns=@JoinColumn(name="user_id"))
@Column(name="nickname")
public List<String> getNicknames() { ... } 

Source: 7.2.3. Collections of basic types and embeddable objects

Solution 2 - Java

try

  @org.hibernate.annotations.CollectionOfElements(
        targetElement = java.lang.String.class
    )
    @JoinTable(
        name = "foo",
        joinColumns = @JoinColumn(name = "foo_id")
    )
    @org.hibernate.annotations.IndexColumn(
        name = "POSITION", base = 1
    )
    @Column(name = "baz", nullable = false)
    private List<String> arguments = new ArrayList<String>();

or see this detail example

Solution 3 - Java

If you are happy to store them in the same column as JSON (MySQL, PostgreSQL that also support indexing and binary JSON), you could simply use com.vladmihalcea/hibernate-types-52 library.

@TypeDefs({
    @TypeDef(name = "json", typeClass = JsonType.class)
})
public class YourEntity {
   @Column(nullable = false)
   @Type(type = "json")
   private List<String> fieldName = List.of();
   ...
}

See full guide here

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTeaOverflowView Question on Stackoverflow
Solution 1 - JavaSean Patrick FloydView Answer on Stackoverflow
Solution 2 - JavaNirmal- thInk beYondView Answer on Stackoverflow
Solution 3 - JavaE CiottiView Answer on Stackoverflow