64

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

3 Answers 3

125

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

Sign up to request clarification or add additional context in comments.

4 Comments

Just a question: Will CollectionTable automatically create a table called "Nicknames" if it is not created?
@BigDude if you let your schema be generated / updated by hibernate, then I'm guessing yes. But it's been almost 10 years since I used hibernate :-)
you're right, I tried it out and if I let Hibernate handle the creating/updating process, it will create and update the table defined within CollectionTable for me :) Thanks!
@ThiagoSuchorski I hardly ever use relational databases. But if I did, I'd probably use jooq.
3

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

1 Comment

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.