Hibernate HQL返回陈旧数据?

时间:2013-03-12 13:00:43

标签: java hibernate hql

我的Hibernate HQL查询似乎正在返回陈旧数据。

我有一个名为Account的简单java类,其实例映射到一个数据库表,其中包含两个varchar列,用户名和姓氏。

如果我运行HQL查询,例如:

List<?> accountList = session.createQuery("from Account where surname is null").list();

我按预期返回了一个Account对象列表(表中的某些行确实有null姓氏字段)。

然后我将返回的对象上的姓氏设置为某个非空值:

Iterator<?> accountIter = accountList.iterator();
while (accountIter.hasNext()) {
  Account account = (Account) accountIter.next();
  log("Adding surname of Jones to : " + account.getUsername());
  account.setSurname("Jones");
}

此时,如果我再次运行HQL查询,我希望得到一个空列表(因为所有的姓氏都应该是非空的), 但是我得到了与第一次运行查询时相同的对象。这不是我的预期。

引用Hibernate文档:

http://docs.jboss.org/hibernate/orm/4.1/manual/en-US/html_single/

&#34;完全没有保证Session何时执行JDBC调用, 只有他们执行的顺序。但是,Hibernate确实保证了 Query.list(..)永远不会返回过时或不正确的数据。&#34;

这似乎与我的代码行为相反。查看下面清单4中的程序输出,SQL Update语句在所有select语句之后发生,因此最后一个select返回不正确的数据。 任何人都可以了解正在发生的事情,或者我做错了什么?

如果我使用交易包围姓氏设置,并执行session.saveOrUpdate(account) 这一切都有效,但我认为这不是必需的。

我希望我的代码只在可能的情况下处理域类,并且是免费的 持久性代码尽可能多。

我正在使用Hibernate 4.1.8.Final,使用Java 1.6

我的完整代码清单如下:

清单1:Main.java:

package uk.ac.york.cserv.hibernatetest;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Main {

    private static SessionFactory sf;
    Session session;

    public static void main(String[] args) {
        Main main = new Main();
        main.doExample();
    }

    public Main() {
        sf = new Configuration()
            .configure("hibernate-ora.cfg.xml")
            .buildSessionFactory();
        session = sf.openSession();
    }

    public void closeSession() {
        session.flush();
        session.close();
    }

    public List<?> getAccountList() {
        return session.createQuery("from Account where surname is null").list();
    }

    public void printAccountList(List<?> accountList) {
        Iterator<?> accountIter = accountList.iterator();
        while (accountIter.hasNext()) {
            System.out.println(accountIter.next());
        }
    }

    public void log(String msg) {
        System.out.println(msg);
    }

    public void doExample() {

        log("Print all accounts with null surnames...");
        printAccountList(getAccountList());

        log("Adding surnames to accounts that have null surnames...");
        //session.beginTransaction();
        Iterator<?> accountIter = getAccountList().iterator();
        while (accountIter.hasNext()) {
            Account account = (Account) accountIter.next();
            log("Adding surname of Jones to : " + account.getUsername());
            account.setSurname("Jones");
            //session.saveOrUpdate(account);
        }
        //session.getTransaction().commit();

        log("Again print all accounts that have null surnames (should be none)...");
        printAccountList(getAccountList());

        closeSession();
    }
}

清单2:Account.java:

package uk.ac.york.cserv.hibernatetest;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="ACCOUNTS")
public class Account {

    @Id
    @Column(name = "USERNAME", unique = true, nullable = false)
    private String username;

    @Column(name = "SURNAME")
    private String surname;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    @Override
    public String toString() {
        return "Account [username=" + username + ", surname=" + surname + "]";
    }
}

清单3:Hibernate-ora.cfg.xml:

<hibernate-configuration>

    <session-factory>

        <!-- Database connection settings -->
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="connection.url">jdbc:oracle:thin:@testhost:1521:test</property>
        <property name="connection.username">testschema</property>
        <property name="connection.password">testpassword</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Names of the annotated classes -->
        <mapping class="uk.ac.york.cserv.hibernatetest.Account"/>

    </session-factory>

</hibernate-configuration>

清单4:程序输出:

Print all accounts with null surnames...
Hibernate: select account0_.USERNAME as USERNAME0_, account0_.SURNAME as SURNAME0_ from ACCOUNTS account0_ where account0_.SURNAME is null
Account [username=user2, surname=null]
Adding surnames to accounts that have null surnames...
Hibernate: select account0_.USERNAME as USERNAME0_, account0_.SURNAME as SURNAME0_ from ACCOUNTS account0_ where account0_.SURNAME is null
Adding surname of Jones to : user2
Again print all accounts that have null surnames (should be none)...
Hibernate: select account0_.USERNAME as USERNAME0_, account0_.SURNAME as SURNAME0_ from ACCOUNTS account0_ where account0_.SURNAME is null
Account [username=user2, surname=Jones]
Hibernate: update ACCOUNTS set SURNAME=? where USERNAME=?

1 个答案:

答案 0 :(得分:2)

您正在描述的Hibernate行为没有什么奇怪的

“此时,如果我再次运行HQL查询,我希望得到一个空列表(因为所有的姓氏都应该是非空的),但我会找回与我相同的对象第一次运行查询。这不是我的预期。“

此时,当您再次运行HQL查询时,到目前为止您还没有对数据库做过任何事情。这就是为什么你要获得你所谓的“陈旧”数据的原因,但它实际上是表中尚未修改的最新版本

如果发出saveOrUpdate命令并关闭事务,那么您在Java类中所做的更改将持久保存到数据库,以便新的HQL查询执行显示更新的数据

我认为你误解了Hibernate在这个用例中的工作方式。正是因为“Hibernate确保Query.list(..)永远不会返回过时或不正确的数据。”您会看到来自数据库的数据的更新版本,从数据库的角度来看,您的Java类中的更改是“陈旧”的,并且会被来自原始尚未修改的源的新“新”实际数据所取代