在 hibernate 中更新对象的字段
我有一个对象 A
映射到数据库中的表 A
class A {
Integer id;
String field2,field2;field3 ,... fieldN;
//lots of other attribute
}
现在我想编写一个仅更新单个字段的 DAO api。一种方法是我可以先加载对象然后更改我需要的属性,然后使用合并 api
//start transcation
A a = session.load(A.class, id);
A.setfieldP(newValue)
session.merge(A)
//commit transcation
现在如果我使用以下代码
//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
现在第二种方法除 id 和 fieldP 之外的所有字段都设置为 null
1)现在还有其他方法吗?
2)我可以使用更新而不是合并吗?
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您需要一次更新大量实体,最有效的方法是使用查询:
这允许您更改字段值,而无需将一个或多个实体加载到内存中。
最佳实践是使用命名查询和命名参数 - 上面的实现只是一个示例。
If you need to update lots of entities at once the most efficient way is to use a query:
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.
我通常更喜欢 session.get 与 session.load,因为 session.get 将返回 null 与抛出异常相反,但这取决于您想要的行为。
加载对象,设置字段并调用其中任何一个
是标准方法,尽管
只要对象尚未分离,您也可以使用,在您的情况下,它不会被分离。 这是一篇很好的文章解释了merge 和 saveOrUpdate 的差异。
在第二个示例中,您正在编辑对象的主键?这通常是不好的形式,您应该删除并插入而不是更改主键。
I usually prefer session.get vs session.load, as session.get will return null as opposed to throwing an exception, but it depends on the behavior you want.
loading the object, setting your field, and calling either
is the standard way, although you can also use
as long as the object hasn't been detached, which in your case, it won't have been detached. Here is a good article explaining the differences in merge and saveOrUpdate.
In your second example, you are editing the primary key of the object? This is generally bad form, you should delete and insert instead of changing the primary key.
使用 JPA 你可以这样做。
Using JPA you can do it this way.
这里的另一项优化可能是使用实体的动态更新设置为 true。这将确保每当有更新时,只有更改的字段才会更新。
One more optimization here could be using dynamic-update set to true for the entity. This will make sure that whenever there is an update, only field(s) which are changed only gets updated.