Hibernate:如何持久化包含Map <string,list <string =“”>&gt; </string,>的Class

时间:2010-09-27 01:25:54

标签: hibernate

我想坚持下面的课程,包括'bar'

Class Foo
{
  Map<String, List<String>> bar;
  // ...
  // other stuff.....
}

我如何在Hibernate中执行此操作? 如果可能,如何在带有注释的Hibernate中执行此操作?

哦,Map键字符串的本质是它们中有少量(5-40),它们在Foo实例中是相同的。 List中的字符串在List和Foo实例之间都是唯一的。

感谢。

1 个答案:

答案 0 :(得分:1)

String和List都不是实体,你应该创建一个包装类来封装你的List

不要忘记setter的

@Entity
public class Foo {

    private MutableInt id = new MutableInt();

    private Map<String, CustomList> customListMap = new HashSet<String, CustomList>();

    @Id
    @GeneratedValue
    public Integer getId() {
        return this.id.intValue();
    }

    public void setId(Integer id) {
        return this.id.setValue(id);
    }

    @OneToMany
    @MapKey(name="key")
    public Map<String, CustomList> getCustomListMap() {
        return customListMap;
    }

    // add convenience method
    public void addBar(String key, String bar) {
        if(customListMap.get(key) == null)
            customListMap.put(key, new CustomList(new CustomListId(id, key)));

        customListMap.get(key).getBar().add(bar);
    }

}

您的自定义CustomList(不要忘记setter's)

@Entity
public class CustomList {

    private CustomListId customListId;

    private List<String> bar;

    private String key;

    @EmbeddedId
    public CustomListId getCustomListId() {
        return customListId;
    }

    @Column(insertable=false, updatable=false)
    public String getKey() {
        return this.key;
    }

    @CollectionOfElements
    @JoinTable(name="BAR")
    public List<String> getBar() {
        return this.bar;
    }

    @Embeddable
    public static class CustomListId implements Serializable {

        private MutableInt fooId = new MutableInt();
        private String key;

        // required no-arg construtor
        public CustomList() {}
        public CustomList(MutableInt fooId, String key) {
            this.fooId = fooId;
            this.key   = key;
        }

        public Integer getFooId() {
            return fooId.intValue();
        }

        public void setFooId(Integer fooId) {
            this.fooId.setValue(fooId);
        }

        // getter's and setter's

        public boolean equals(Object o)  {
            if(!(o instanceof CustomListId))
                return false;

            CustomListId other = (CustomList) o;
            return new EqualsBuilder()
                       .append(getFooId(), other.getFooId())
                       .append(getKey(), other.getKey())
                       .isEquals();
        }

        // implements hashCode

    }

} 

你甚至可以创建一个名为getBar 的自定义方法,它透明地封装你的customListMap ,如下所示

@Entity
public class Foo {

    ...

    public Map<String, List<String>> getBar() {
        Map<String, List<String>> bar = new HashMap<String, List<String>>();

        for(Entry<String, CustomList> e: customListMap())
            bar.put(e.getKey(), e.getValue().getBar());

        return bar;
    }

}