With the Hibernate ORM Framework for some time now, review the load and get in seesion.
A, get does not support lazy,load support lazy.
Second, the use of Get load data, if there is no matching data, return null, and load throws an exception.
Example of Get:
1public void testGetMethod() {
2 Session session = null;
3 try {
4 session = HibernateUtils.getSession();
5 session.beginTransaction();
6
7 //马上发出查询sql,加载User对象
8 User user = (User)session.get(User.class, "402880d01b9bf210011b9bf2c2ff0002");
9 System.out.println("user.name=" + user.getName());
10
11 user.setName("张三");
12 session.getTransaction().commit();
13 }catch(Exception e) {
14 e.printStackTrace();
15 session.getTransaction().rollback();
16 }finally {
17 HibernateUtils.closeSession(session);
18 }
19 }
PS: When executing line 8th statements, if the database has related records, immediately emit the SQL statement, even if there is no Line 9th user.getname () method call, if there is no matching records return a null.
Load Method Example:
1public void testLoadMethod() {
2 Session session = null;
3 try {
4 session = HibernateUtils.getSession();
5 session.beginTransaction();
6
7 //不会发出查询sql,因为load方法实现了lazy(懒加载或延迟加载)
8 //延迟加载:只有真正使用这个对象的时候,才加载(发出sql语句)
9 //hibernate延迟加载实现原理是代理方式
10 User user = (User)session.load(User.class, "402880d01b9bf210011b9bf2b2ff0002");
11 System.out.println("user.name=" + user.getName());
12 user.setName("李四");
13 session.getTransaction().commit();
14 }catch(Exception e) {
15 e.printStackTrace();
16 session.getTransaction().rollback();
17 }finally {
18 HibernateUtils.closeSession(session);
19 }
20 }
PS: In the execution to 10 code when the SQL statement is not immediately issued, because the load implementation of lazy delay loading, delay loading only real use of the object when the load, issued a SQL statement, the key is 11 code. If the ID inside the load method is not relevant in the database table, a objectnotfoundexception exception is emitted.
PSPs: You can use debug to track changes to related variables and objects by setting breakpoints, so you can clearly understand both the load and get methods.