java 如何在休眠状态下根据 id 更新行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36286036/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 01:12:40  来源:igfitidea点击:

How can I update a row based on id in hibernate

javahibernateoracle11g

提问by Sunny

I am new in hibernate. I am using SesssionFactory to get the session of the transaction and one way which I found after searching is used for setting few fields using set parameter i.e

我是休眠的新手。我正在使用 SessionFactory 来获取事务的会话,我在搜索后发现的一种方法用于使用 set 参数设置几个字段,即

Query query = getCurrentSession().createSQLQuery(
    "UPDATE table_name set field1=:f1 where ID=:id");

query.setParameter("f1", f1);
query.setParameter("id", id);

but I want to update the whole row. I have already set the values in the entity class but is there a way to pass the values of the whole entity class to the database based on the id the id is the primary key for the table which I want to update.

但我想更新整行。我已经在实体类中设置了值,但是有没有办法根据 id 将整个实体类的值传递给数据库,该 id 是我要更新的表的主键。

回答by Oliver Meyer

you already have all data present in the hibernate entity object? Then just call the session directly:

您已经拥有休眠实体对象中的所有数据?然后直接调用会话:

getCurrentSession().save(myEntity);

to create a new object, or

创建一个新对象,或

getCurrentSession().update(myEntity);

to update an existing row.

更新现有行。

If not sure, you can use:

如果不确定,您可以使用:

getCurrentSession().saveOrUpdate(myEntity);

回答by PA001

Take a look at Session#update(or saveOrUpdate). This will allow you to persist a complete, mapped, object to the database.

看看Session#update(或 saveOrUpdate)。这将允许您将完整的映射对象持久化到数据库中。

回答by Thamiar

To be as OO as you can, you can get entity by session.get(entityClass, id); And then after modifying object by setters/getters, you can save it back to the DB using update method :session.update(entity);

为了尽可能面向对象,您可以通过 session.get(entityClass, id); 获取实体;然后通过 setter/getter 修改对象后,您可以使用更新方法将其保存回数据库 :session.update(entity);