休眠,插入或更新时不选择 [英] Hibernate, insert or update without select
问题描述
我有一个属于某些类别的产品对象,即经典的多对一关系.
I have a products objects which belongs to certain categories i.e. classical many to one relationship.
@Entity
public class Product{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long id;
String name;
Double price;
@ManyToOne(fetch = FetchType.LAZY)
Category category;
...
}
@Entity
public class Category implements Identifiable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
...
}
我想插入和更新产品而无需预先选择类别.像这样:
I want to insert and update products without preselecting categories. Like this:
Product product = dao.get(productId);
Category category = dao.get(categoryId);
product.setCategory(category);
dao.update(product);
或
Product product = new Product(somename);
Category category = dao.get(categoryId);
product.setCategory(category);
dao.insert(product);
是否可以在不选择类别的情况下进行更新和插入?我不想为此使用HQL或直接查询.
Is it possible to update and insert without category selecting? I don't want to use HQL or direct queries for that.
推荐答案
session.load()专门用于此类情况.以下:
session.load() exists specifically for cases like this. The following:
Category category = session.load(categoryId);
product.setCategory(category);
不会命中数据库.但是,如果没有提供给定ID的类别,它将在稍后阶段(刷新期间或多或少)引发异常.
will not hit the database. It will, however, throw an exception at a later stage (during flush, more or less) if there is no category available with given id.
使用load()
比merge()
更快,并且没有副作用(级联等)
Using load()
is faster than merge()
and has no side-effects (cascading, etc...)
这篇关于休眠,插入或更新时不选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!