Hibernate一对多插入 - 插入<children>插入错误的顺序

时间:2018-03-15 11:29:38

标签: hibernate insert one-to-many

例如,我有两个具有一对多关系的实体。我只写下简单的代码。

Class Category {

   @OneToMany(fetch = FetchType.LAZY, mappedBy = "category")
   @LazyCollection(LazyCollectionOption.EXTRA)
   @Cascade(value = CascadeType.ALL)
   private Set<Product> products;

}

Class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID", unique = true, nullable = false)
    private int id;

    @Column(name = "Name")
    private String name;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "BookingCode", insertable = false, updatable = false)
    private Category category;

}

然后我想用它的产品插入一个类别。例如:

Set<Product> products = new HashSet<>():
Category category = new Category();

Product fProduct = new Product("1", category);
Product sProduct = new Product("2", category);
Product tProduct = new Product("3", category);
Product fProduct = new Product("4", category);

products.add(fProduct);
products.add(sProduct);
products.add(tProduct);
products.add(fProduct);

category.setProducts(products);

session.persist(category);

以上代码正常工作,但产品列表随机插入,与我添加到集合中的顺序不同。

输出产品将是&#34; 3&#34;,&#34; 4&#34;,&#34; 2&#34;,&#34; 1&#34;。

任何人都可以向我解释原因吗?我该如何解决这个问题呢?

0 个答案:

没有答案