简体   繁体   English

在Hibernate 5.x中使用本机查询(更新查询)执行查询

[英]Execute query with native query (update query) in Hibernate 5.x

I am currently upgrading our application and we are migrating from Hibernate 3.x and Spring/Spring Security 3.x to Hibernate 5.x and Spring/Spring Security 5.x respectively. 我目前正在升级我们的应用程序,我们分别从Hibernate 3.xSpring / Spring Security 3.x迁移到Hibernate 5.xSpring / Spring Security 5.x. We had some methods that executed native sql update queries (example 1), but after upgrading to 5.x the methods started throwing TransactionRequiredException: Executing an update/delete query exceptions. 我们有一些方法执行本机sql更新查询(例1),但升级到5.x后 ,方法开始抛出TransactionRequiredException:执行更新/删除查询异常。 Well I tried adding the @Transactional annotation on the methods but it doesn't seem to help. 好吧,我尝试在方法上添加@Transactional注释,但它似乎没有帮助。 I will share the old method and the upgraded method (example 2). 我将分享旧方法和升级方法(示例2)。

I don't understand how it is not working on the new version, did Hibernate change the way they treat native sql queries? 我不明白它是如何处理新版本的,Hibernate是否改变了它们对待本机sql查询的方式? Thanks for the responses. 谢谢你的回复。

Example 1 例1

public void myTestMethod() {
    String sql = "Update myTable set State = 1";
    Session session = getSessionFactory().openSession();
    Query query = session.createSQLQuery(sql);
    query.executeUpdate();
    session.close();
}

Example 2 例2

public void myTestMethod() {
    String sql = "Update myTable set State = 1";
    Session session = sessionFactory.openSession();
    Query query = session.createNativeQuery(sql);
    query.executeUpdate();
    session.close();
}

What am I doing wrong here? 我在这做错了什么? How can I execute this update without changing much in the methods (we have thousands of methods implemented). 如何在不改变方法的情况下执行此更新(我们已实现了数千种方法)。 The sessionFactory in the example 2 is injected with @Inject annotation. 示例2中的sessionFactory注入了@Inject注释。

Try to use @Transactional over your methods and use getCurrentSession() instead of the openSession() 尝试在方法上使用@Transactional并使用getCurrentSession()而不是openSession()

And your code has session.close() statement which doesn't make sense any more, since the connection was already closed and managed by the spring. 并且您的代码具有session.close()语句,该语句不再有意义,因为连接已经被spring关闭和管理。 Try removing the session.close() statement and try again 尝试删除session.close()语句,然后重试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM