在hibernate中更新一个对象的字段 [英] updating a field of a object in hibernate
问题描述
我有一个对象A
,它映射到DB中的 table A
class A {
整数id;
字符串field2,field2; field3,... fieldN;
//很多其他属性
}
现在我想写一个DAO api,只是更新单个字段。一种方法是,我可以先加载对象,然后更改我需要的属性,然后使用合并api
//启动transcation
A a = session.load(A.class,id);
A.setfieldP(newValue)
session.merge(A)
//提交transcation
现在,如果我使用以下代码:
//开始转换
A a = new A ();
a.setId(id); //设置一个对象A在DB
中存在的ID A.setfieldP(newValue)
session.merge(A)
//提交事务
现在第二种方法除id和fieldP之外的所有字段都设为null
$ b $ 1是否还有其他方法?
2)我可以使用update而不是merge吗?
解决方案如果你需要一次更新大量实体,最有效的方式就是使用查询:
$ b $ pre code Query query = session.createQuery(更新EntityName set fieldP ='newValue'
+where id IN(75,76));
query.executeUpdate();
这允许您更改字段值,而无需将实体或实体加载到内存中。
最好的做法是使用命名查询和命名参数 - 上述实现仅仅是一个例子。
I have a object A
which maps to table A
in DB
class A {
Integer id;
String field2,field2;field3 ,... fieldN;
//lots of other attribute
}
Now i want to write a DAO api that just updates a single field.One approach is that i can first load the object then changes the attribute i need and then use merge api
//start transcation
A a = session.load(A.class, id);
A.setfieldP(newValue)
session.merge(A)
//commit transcation
Now if i use following code
//start transcation
A a = new A();
a.setId(id); //set a id by which object A exists in DB
A.setfieldP(newValue)
session.merge(A)
//commit transaction
Now second approach all fields except id and fieldP are set to null
1)Now is there any other approach?
2)Can i use update instead of merge ?
If you need to update lots of entities at once the most efficient way is to use a query:
Query query = session.createQuery("update EntityName set fieldP = 'newValue' "
+ "where id IN (75, 76)");
query.executeUpdate();
This allows you to change field values without loading the entity or entities into memory.
It is best practice is to use named queries and named parameters - the above implementation is just an example.
这篇关于在hibernate中更新一个对象的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!