我正在使用带有JPA注释实体的Hibernate,而我期望更新“raw_text
”实体字段的下一个代码不会更改它。如何实现预期的行为?
@Override
public void updatePageWithText(String pageName, String rawText) {
Session session = HibernateUtils.getInstance().openSession();
String hql = "FROM WikiPage M WHERE M.name = :name";
Query query = session.createQuery(hql);
query.setParameter("name",pageName);
WikiPage res = null;
try {
res = (WikiPage) query.list().get(0);
res.setRawText(rawText);
session.update(res);
session.flush();
}
catch (IndexOutOfBoundsException e) {}
finally {
session.close();
}
}
答案 0 :(得分:1)
更新必须在事务内部,必须在会话关闭之前提交(或在发生错误时回滚)。使用以下代码尝试:
@Override
public void updatePageWithText(String pageName, String rawText) {
Session session = null;
Transaction tx = null;
WikiPage res = null;
try {
session = HibernateUtils.getInstance().openSession();
tx = session.beginTransaction();
String hql = "FROM WikiPage M WHERE M.name = :name";
Query query = session.createQuery(hql);
query.setParameter("name",pageName);
res = (WikiPage) query.list().get(0);
res.setRawText(rawText);
session.update(res);
tx.commit;
}
catch (IndexOutOfBoundsException e) {}
catch (Exception ex) {
if (tx!=null) {
tx.rollback();
}
throw ex;
}
finally {
session.close();
}
}
在以下链接中,您可以找到有关hibernate中事务处理的更多信息(如果是非托管上下文,可能就是您的情况):https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/transactions.html#transactions-demarcation-nonmanaged
答案 1 :(得分:1)
你也可以使用@Modifying来注释@query以定义存储库中的接口。
@Modifying
@Query(" UPDATE WikiPage w set name = :name ")
public void updateName(@Param("name")String name);
Jpa Repsitory(http://docs.spring.io/spring-data/jpa/docs/1.6.4.RELEASE/reference/html/jpa.repositories.html)中的更多细节,章节2.3.7修改查询
答案 2 :(得分:1)
请尝试以下操作:
@Override
public void updatePageWithText(String pageName, String rawText) {
Session session = HibernateUtils.getInstance().openSession();
Transaction transaction=session.beginTransaction();
String hql = "FROM WikiPage M WHERE M.name = :name";
Query query = session.createQuery(hql);
query.setParameter("name",pageName);
WikiPage res = null;
try {
res = (WikiPage) query.list().get(0);
res.setRawText(rawText);
transaction.commit();
}
catch (IndexOutOfBoundsException e) {
transaction.rollback();
}
finally {
session.close();
}
}
Note :
当您从查询中获取WikiPage时,它仍然是一个附加实体,因此您无需触发session.update()
,committing
transaction
即可。< / p>