1

(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 Answer 1

5

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.

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

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.