get测试代码如下:
public class Test { public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml"); SessionFactory sessionFactory=(SessionFactory) ac.getBean("sessionFactory"); Session session=sessionFactory.openSession(); User user1=(User) session.get(User.class, 3); System.out.println("-----------"); System.out.println(user1); } }
输出结果是:
Hibernate:
select
user0_.id as id0_0_,
user0_.name as name0_0_
from
mydb.user user0_
where
user0_.id=?
-----------
User [id=3, name=sara3]
load测试代码
public class Test { public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml"); SessionFactory sessionFactory=(SessionFactory) ac.getBean("sessionFactory"); Session session=sessionFactory.openSession(); User user2=(User) session.load(User.class,2); System.out.println("********"); System.out.println(user2); session.close(); } }
输出结果:
********
Hibernate:
select
user0_.id as id0_0_,
user0_.name as name0_0_
from
mydb.user user0_
where
user0_.id=?
User [id=2, name=sara2]
可以看出get方法直接发出sql语句,从数据库加载,没有延迟。load方法只有真正用到对象的内容时才会发出sql语句
接下来再用两个测试用例
get测试用例
public class Test { public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml"); SessionFactory sessionFactory=(SessionFactory) ac.getBean("sessionFactory"); Session session=sessionFactory.openSession(); User user1=(User) session.get(User.class, 3); System.out.println("-----------"); System.out.println(user1.getClass()); session.close(); } }
输出结果是:
Hibernate:
select
user0_.id as id0_0_,
user0_.name as name0_0_
from
mydb.user user0_
where
user0_.id=?
-----------
class com.db.entity.User
load测试代码:
public class Test { public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml"); SessionFactory sessionFactory=(SessionFactory) ac.getBean("sessionFactory"); Session session=sessionFactory.openSession(); User user2=(User) session.load(User.class,2); System.out.println("********"); System.out.println(user2.getClass()); session.close(); } }
输出结果是:
********
class com.db.entity.User_$$_javassist_0
结论:
get方法会在调用之后立即向数据库发出sql语句(不考虑缓存的情况下),返回持久化对象;而load方法会在调用后返回一个代理对象,该代理对象只保存了实体对象的id,直到使用对象的非主键属性时才会发出sql语句