hibernate查询某一个对象后,执行createSQLQuery查询出现的问题

最近工作中碰到了一个奇怪问题,特别做下笔记:

user表里的数据,是1,1和2,2,分别为id和name字段。

代码如下:

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




public class Test {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from hibernate.cfg.xml
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void main(String[] args) {
Session session = sessionFactory.openSession();
Transaction tr = session.beginTransaction();
tr.begin();
User user = (User) session.load(User.class, 1);
user.setName("2");
session.saveOrUpdate(user);
int num = (Integer) session.createSQLQuery("select count(*) num from user where name = 2 ").addScalar("num", Hibernate.INTEGER).uniqueResult();
System.out.println(num);
tr.commit();
}

打印结果:

Hibernate: select user0_.id as id0_0_, user0_.name as name0_0_ from user user0_ where user0_.id=?
Hibernate: select count(*) num from user where name = 2
1
Hibernate: update user set name=? where id=?

也就是说通过session.createSQLQuery这个方法并没有先去更新user对象,所以结果还是1,而我想要的结果是2,所以会出现这样错误

修改代码 :





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




public class Test {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from hibernate.cfg.xml
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void main(String[] args) {
Session session = sessionFactory.openSession();
Transaction tr = session.beginTransaction();
tr.begin();
User user = (User) session.load(User.class, 1);
user.setName("2");
session.saveOrUpdate(user);
int num = (Integer) session.createQuery("from User where name = 2 ").list().size();
System.out.println(num);
tr.commit();
}
}

执行结果:

Hibernate: select user0_.id as id0_0_, user0_.name as name0_0_ from user user0_ where user0_.id=?
Hibernate: update user set name=? where id=?
Hibernate: select user0_.id as id0_, user0_.name as name0_ from user user0_ where user0_.name=2
2

这里就是先更新了user对象后,再来查询了,所以这种情况是正确的

总结:如果跟新了查出来的对象,saveorupdate了,然后用session.createSQLQuery方法的时候,也是查询不到修改的对象的,从打印语句可以看出来:

先查询了,然后再更新了哦,所以会出现问题的

你可能感兴趣的:(Hibernate)