Hibernate映射集合(JDK以及嵌入式值类)

  • JDK内置的集合类型有Set、List、Collection、Map四种
//Set与Collection的区别在于是否允许重复元素,java未提供Collection的实现。
//任意的值类型集合映,都需要@ElementCollection,其有两个属性fetch以及targetClass,其中targetClass在集合不是泛型集合时是必须指定的。
//通过@CollectionTable来指定映射表的表名以及数据库名。

    //映射Set or HashSet
    @ElementCollection(fetch = FetchType.LAZY)
    @CollectionTable(name="e",catalog = "world")
    Set<E> sets;

    //映射List,需要使用@OrderColumn额外指定一个序号列,否则元素无序,从该list中删除一个元素时,所有拥有相同外键(实体)数据库行都将重新移位排列
    @ElementCollection(fetch = FetchType.LAZY)
    @CollectionTable(name="e",catalog = "world")
    @OrderColumn(name = "index")
    List<E> sets;

    //映射Collection,需要使用hibernate的@CollectionId,用于指定一个额外的代理键,用于添加重复元素。
    @ElementCollection
    @CollectionTable(name = "IMAGE")
    @Column(name = "FILENAME")
    @org.hibernate.annotations.CollectionId(
            columns = @Column(name = "IMAGE_ID"),
            type = @org.hibernate.annotations.Type(type = "long"),
            generator = Constants.ID_GENERATOR)
    private Collection<E> es;

    //Map or HashMap,需额外指定@MapKeyColumn作为键列
    @ElementCollection(fetch = FetchType.LAZY)
    @CollectionTable(name="e",catalog = "world")
    @MapKeyColumn(name = "key")//正常情况使用该注解
    //@MapKeyEnumerated,若键值为enum则使用该注解
    //@MapKeyTemporal,若键值为Date等则使用该注解
    Map<E> sets;

    //SortedSet or SortedMap,需使用@SortNatural或@SortComparator,二者均在内存中进行再次排序
    方法一使用@SortNatural,则调用compareTo方法进行比较
    方法二使用@SortComparator,需要传入一个Comparator进行比较。
  • 映射Embeddable类型集合的属性
//最关键的是该组件集合中的任何一个元素都依赖于当前实体,当实体保存/删除/更新时,都会执行相应级联操作。
//除了可以通过@AttributeOverrides来重写属性外,与JDK值类并无太大区别。
posted @ 2016-04-12 22:51  fcat  阅读(442)  评论(0编辑  收藏  举报