在Hibernate事务中添加Select语句 [英] Putting Select Statement on Hibernate Transaction

查看:258
本文介绍了在Hibernate事务中添加Select语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于Hibernate我一直在阅读一段时间,但我似乎无法理解关于 Transaction 的一个概念。



在我访问的某些网站上, Select 语句处于这种交易模式。

  public List< Book> readAll(){
Session session = HibernateUtil.getSessionFactory()
.getCurrentSession();
session.beginTransaction();
列表< Book> booksList = session.createQuery(from Book)。list();
session.getTransaction()。commit();
返回booksList;
}

在某些网站上,它并不主张使用选择语句:

  public List< Book> readAll(){
Session session = HibernateUtil.getSessionFactory()
.getCurrentSession();
列表< Book> booksList = session.createQuery(from Book)。list();
返回booksList;
}

我正在考虑应该遵循哪一个。在 Select >语句中是否需要交易?

解决方案

用例。

在典型的CRUD风格的web应用程序中,常见的实体配置是使用版本控制和乐观锁定。 (hibernate annotation docs)如果应用程序是使用乐观锁定,脏读可能不那么重要,并且不需要将select放入事务中。



当脏读不可接受时,则事务对于选择是适当的。大多数情况下,在这种情况下,选择将与需要完全一致的数据修改一起完成。


I have been reading for a while regarding Hibernate but I can't seem to understand one concept regarding Transaction.

On some sites that I have visit, Select statements are in transaction mode like this.

public List<Book> readAll() {
    Session session = HibernateUtil.getSessionFactory()
            .getCurrentSession();
    session.beginTransaction();
    List<Book> booksList = session.createQuery("from Book").list();
    session.getTransaction().commit();
    return booksList;
}

While on some site, it does not advocate the use of transaction on Select statements:

public List<Book> readAll() {
    Session session = HibernateUtil.getSessionFactory()
            .getCurrentSession();
    List<Book> booksList = session.createQuery("from Book").list();
    return booksList;
}

I am thinking which one should I follow. Are transactions needed on Select Statements or not?

解决方案

It depends on the use case.

In a typical CRUD style web application a common entity configuration is to use versioning and optimistic locking. (hibernate annotation docs) If the application is using optimistic locking, dirty reads are probably not that important, and there is no need to put the select in a transaction.

When dirty reads are not acceptable, then a transaction for the select is appropriate. Most of the time, with that kind of scenario, the select will be done in conjunction with some data modification that requires full consistency for a point in time.

这篇关于在Hibernate事务中添加Select语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆