【问题标题】:Hibernate one-to-many list with list index as part of the key休眠一对多列表,列表索引作为键的一部分
【发布时间】:2013-10-14 14:48:37
【问题描述】:

我有两张桌子:

CREATE TABLE product
(
  id serial NOT NULL,
  -- some other columns
  CONSTRAINT product_pkey PRIMARY KEY (id )
);

CREATE TABLE product_image
(
  product_id bigint NOT NULL,
  order integer NOT NULL,
  width integer NOT NULL,
  -- some other columns
  CONSTRAINT product_image_pk PRIMARY KEY (product_id , order ),
  CONSTRAINT product_image_product_fk FOREIGN KEY (product_id)
  REFERENCES product (id) 
);

我想这样映射:

public class Product {
  ...
  List<Image> images;
  ...
}

public class Image {
  ...
  int width;
  ...
}

基本上,我希望 Product 类有一个 Image 对象列表,其中包含图像表中除订单和产品 ID 之外的所有字段(如果可能的话)。该列表应根据 order 字段进行排序。

理想情况下,我根本不想处理订单。我只想让休眠使用产品列表中的顺序。我需要图像类中的产品和订单字段吗?

谁能指出我的注释应该是什么样的正确方向,或者映射这类事情的最佳方法是什么?我真的不能在数据库中做任何事情,但我对 java 模型持开放态度。

谢谢!

编辑:

我试过这个:

@Entity
@Table(name = "product_image")
public class Image implements Comparable<Image>{

    @Id
    @Column(name = "order")
    private Integer order;

    @Id
    @ManyToOne
    @JoinColumn(name="product_id")
    private Product product;
}

@Entity
@Table(name = "product")
public class Product {

    @OneToMany(mappedBy="product", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @Sort(type = SortType.COMPARATOR, comparator = Image.class)
    @OrderColumn(name = "order")
    private List<Image> images;
}

它适用于读取数据,但此代码失败:

List<Image> images = new ArrayList<Image>();
Image i = new Image();
i.setProduct(product);
images.add(i);      
product.setImages(images);

session.save(product);

因为 order 仍然为空。

【问题讨论】:

    标签: hibernate list indexing annotations one-to-many


    【解决方案1】:

    Hibernate 支持像 java.util.SortedMapjava.util.SortedSet 这样的排序集合。并且注释@Sort 允许您设置compartor 进行排序。 Check out the reference document.

    首先定义您自己的 Comparator 类进行排序。覆盖 compare 方法以根据 Image 类中的 order 值对 Set 进行排序。

    class ImageComparator<Image> implements Comparator<Image> {
    
        @Override
        public int compare(Image o1, Image o2) {
            // implement compare method
        }
    }
    

    完成后,使用 @Sort 注释定义您的 Product 类,以包含您的自定义比较器 ImageComparator 类。

    public class Product {
        ...
        @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
        @JoinColumn(name = "id")
        @Sort(type = SortType.COMPARATOR, comparator = ImageComparator.class)
        SortedSet<Image> images;
        ...
    }
    

    现在您将对images 列表进行排序。

    【讨论】:

    • 所以你是说我需要在 Image 类中有一个明确的 order 字段,我可以使用它来进行排序?
    • 我的理解是你想按Image表中的order字段排序。
    • 是的,但我真的不希望图像知道它在产品图像列表中的索引。这可能吗?
    • 在 Image 类中将 order 声明为私有,并且不向 order 提供任何设置器。然后代替单独的 Comparator 类,实现 Comparator 并覆盖 Image 类本身中的 compare 方法。这样order 将无法从 Image 类中访问。
    • 然后hibernate是根据列表索引设置字段,当我添加一个对象到列表中的时候? (对不起这个问题,但我现在不能尝试)
    猜你喜欢
    • 1970-01-01
    • 2011-10-25
    • 1970-01-01
    • 2011-03-26
    • 2014-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多