(Hibernate)如何使用List <String>的列表语义?

bab*_*ith 1 hibernate list persistent bag semantics

(java1.6,hibernate,mySql)

我正在尝试持久化包含字符串列表的java类.问题是,当我获取它时,我得到一个PersistentBag而不是List或PersistentList.我寻找答案或例子,但我只是更困惑.

我有一个小测试用例,我使用:

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

问题可以看作第一个assertEquals工作,而第二个
(assertEquals(actual,expected);)失败.它发生,因为List被检索为PersistentBag.

所以,你知道这里有什么不对吗?你可以帮我吗?

这是我的代码:

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() ....
*/
}
Run Code Online (Sandbox Code Playgroud)

JB *_*zet 5

要拥有List,Hibernate需要知道如何对列表中的元素进行排序或索引.使用@OrderColumn注释或@OrderBy注释.有关这些注释之间的详细信息和差异,请参阅http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#collections-indexed.

如果你不能订购或索引你的元素,那么你有一个包,而不是一个列表.这是你的equals方法,应该修复以避免考虑元素的顺序.