(Hibernate) How to use List Semantics for a List<String>?

3.3k views Asked by At

(java1.6, hibernate, mySql)

i'm trying to persist a java class that contains a list of strings. the problem is that when i fetch it i get a PersistentBag instead of a List or a PersistentList. i looked for an answer or example but i only got more confused.

i have a small test case that i use:

@Test
public void testFind() {
    FooEntity expected = createFoo();
    FooEntity actual = dao.find(expected.getId());
    assertEquals(expected, actual);
    assertEquals(actual, expected);
}

the problem can be seen as the first assertEquals works while the second one,
(assertEquals(actual, expected);), fails. it happens since the List is retrieved as a PersistentBag.

so, do you know whats wrong here? can you help me on that?

here is my code:

import java.util.ArrayList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "EXAMPLE4_FOO")
public class FooEntity {

    @Id
    @GeneratedValue
    @Column(name = "ID")
    private int id;

    @Column(name = "LIST")
    @ElementCollection(fetch = FetchType.EAGER)
    private List<String> strings = new ArrayList<String>();

    public FooEntity() {
    }

    public int getId() {
    return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public List<String> getStrings() {
    return strings;
    }

    public void setStrings(ArrayList<String> strings) {
        this.strings = strings;
    }

/*
   equals() and hashCode() ....
*/
}
1

There are 1 answers

0
JB Nizet On

To have a List, Hibernate needs to know how to order or index elements of the list. Use the @OrderColumn annotation or the @OrderBy annotation. See http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#collections-indexed for details and differences between those annotations.

If you can't order or index your elements, then you have a bag, not a list. And it's your equals method that should be fixed to avoid taking the order of the elements into consideration.