java 更新休眠中的一些列值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11815104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
updating some column values in hibernate
提问by Anand
I have a table in which there are 14 columns. Now I have a object corresponds to the table in which I have only 5 values to be updated.
I am using saveOrUpdate method to either save/update the row. The issue is that when I use this method to update those 5 columns, all other 9 column values are set to null.
One solution is that I write update sql query to do the same but I want to use Hibernate API's not sql queries.
Is there any way to achieve that?
我有一个表,其中有 14 列。现在我有一个对象对应于我只有 5 个要更新的值的表。
我正在使用 saveOrUpdate 方法来保存/更新行。问题是,当我使用此方法更新这 5 列时,所有其他 9 列值都设置为 null。
一种解决方案是我编写更新 sql 查询来执行相同的操作,但我想使用 Hibernate API 的而不是 sql 查询。
有什么方法可以实现吗?
回答by JB Nizet
Foo objectToUpdate = (Foo) session.get(Foo.class, idOfObjectToUpdate);
objectToUpdate.setField1(newValue1);
objectToUpdate.setField2(newValue2);
No need to call saveOrUpdate()
or merge()
: the object is attached, so everything is flushed and committed at the end of the transaction.
无需调用saveOrUpdate()
or merge()
: 对象已附加,因此所有内容都在事务结束时刷新并提交。
回答by Nguyen Tan Hung
Use DynamicUpdate on Entity
在实体上使用 DynamicUpdate
Example:
例子:
Query q = session.createQuery("from StockTransaction where tranId = :tranId ");
q.setParameter("tranId", 11);
StockTransaction stockTran = (StockTransaction)q.list().get(0);
stockTran.setVolume(4000000L);
session.update(stockTran);
SQL will be like;
SQL 会像;
Hibernate:
update
mkyong.stock_transaction
set
VOLUME=?
where
TRAN_ID=?
回答by Ashok Parmar
Using Hibernate 5 try below code....
使用 Hibernate 5 试试下面的代码....
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaUpdate<Vehicle> criteria = builder.createCriteriaUpdate(Vehicle.class);
Root<Vehicle> root = criteria.from(Vehicle.class);
criteria.set(root.get("ownername"), "Ashok Parmar");
criteria.where(builder.equal(root.get("vehicleId"), "123"));
session.createQuery(criteria).executeUpdate();
回答by Rakib Hasan
Add @DynamicUpdate annotation on your entity class
在您的实体类上添加 @DynamicUpdate 注释
@Entity
@DynamicUpdate
public class Product implements Serializable {
//rest of the codes are omitted for brevity
}
then update specific column (or columns) value of the table
然后更新表的特定列(或列)值
Product newProduct = session.get(Product.class, id);//here id is the product_id for which you are gonna update
newProduct.setName("Pencil 2B");//new name
session.update(newProduct);
@DynamicUpdate will update only the modified column(s), rest of the columns won't be affected.
@DynamicUpdate 将仅更新修改后的列,其余列不会受到影响。