TeaOverflow
TeaOverflow

Reputation: 2578

How to persist a List of Strings in Hibernate?

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

Upvotes: 64

Views: 85466

Answers (3)

E Ciotti
E Ciotti

Reputation: 4955

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 io.hypersistence/hypersistence-utils-hibernate-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

Upvotes: 3

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298838

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

Upvotes: 125

Nirmal- thInk beYond
Nirmal- thInk beYond

Reputation: 12054

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

Upvotes: 3

Related Questions