【问题标题】:Hibernate getCurrentSession() do i really need a transaction for a read-only type of query?Hibernate getCurrentSession() 我真的需要一个事务来处理只读类型的查询吗?
【发布时间】:2014-05-25 20:36:40
【问题描述】:

我正在尝试使用 Hibernate,并试图通过使用 API SessionFactory 提供的 getCurrentSession() 来避免会话管理。据我了解,这将为我管理会话。我的问题是当尝试使用它代替openSession() 时,我收到一条错误消息,提示我需要进行活动交易。我在网上看到了相互矛盾的答案,所以我仍然不确定。我正在尝试执行一个只读查询(基本上是一个选择),为什么我需要一个事务呢?

Error message: org.hibernate.HibernateException message: getNamedQuery is not valid without active transaction

更多细节:

Hibernate.cfg.xml - sn-p

<hibernate-configuration>
<session-factory name="hibernateSessionFactory">
    <property name="connection.datasource">jdbc/DPARISC</property>
    <property name="hibernate.dialect">org.hibernate.dialect.DB2Dialect</property>
    <property    name="hibernate.current_session_context_class">org.hibernate.context.ThreadLocalSessionContext</property>
    <property name="hibernate.connection.isolation">1</property>

我们创建 SessionFactory 的方式没有什么特别的

config.buildSessionFactory();

现在问题来了,在 createQuery 上

 Session session = HibernateUtil.getDB2SessionFactory().getCurrentSession();
    Query query = session.createQuery(queryStringBuilder.toString())
        .setParameter("orgId", request.getOrgId().intValue())
        .setParameter("busUnitId", request.getBusinessUnitId().intValue());
    query.setMaxResults(HibernateConstants.MAX_RESULTS);

同样,查询基本上只是一个 Select 语句。当我使用getCurrentSession() 时,我是否需要开始事务然后提交甚至是这样的事情?这不会产生很多开销吗?

【问题讨论】:

    标签: java sql hibernate transactions hibernate-mapping


    【解决方案1】:

    您的问题的简短答案:是和否。

    更长的答案:

    Hibernate 要求您在执行任何操作时打开会话。只有在您确实打开过getCurrentSession() 时,您才能使用它。

    您为什么认为它会产生大量开销?

    【讨论】:

    • 虽然从文档中,我认为 getCurrentSession 会打开一个新会话,如果不存在,或者如果它存在,它会重新使用。我的问题更多是关于交易方面的。如果您在使用 getCurrentSession 后发出查询,为什么我需要将其包装在事务中?
    • 因为没有事务的读取会导致脏读等问题。
    猜你喜欢
    • 1970-01-01
    • 2012-02-02
    • 2011-04-25
    • 1970-01-01
    • 2017-12-30
    • 1970-01-01
    • 2014-01-31
    • 1970-01-01
    • 2018-02-15
    相关资源
    最近更新 更多