上一节使用了sessionFactory.getCurrentSession().get(Person.class, Integer.parseInt(id));这样一句查询方法,但实际上更常用的是sessionFactory.getCurrentSession().load(Person.class, Integer.parseInt(id));即使用load代替get。
这两个方法都能从数据库中按ID标识查询数据记录,区别在于load是属于延迟加载数据。这个延迟加载的意思就是,在执行load方法时并不会直接发出sql语句去查询数据库,而只是生成了一个暂时的对象返回出来。而如果使用get,就是直接使用sql语句从数据库里查询真实的数据并放入对象中返回出来。
load返回的暂时的对象称为代理对象,代理对象里面存的数据就只有ID属性,其他属性都会是空的,只有当程序中再次使用这个对象时,hibernate才会发sql语句从数据库里查询数据。这样做的好处就是一定程度提高应用程序的性能,减小点数据查询的开销浪费,因为也许查询之后应用程序根本就不会用到这个对象的数据。
验证这个过程,可以在applicationContext.xml中配置sessionFactory,给hibernateProperties属性增加一个prop key="hibernate.show_sql",值为true。重启Tomcat服务器,,如果使用sessionFactory.getCurrentSession().get()方法,就会看到有sql在控制台Console中打印出来。
Hibernate: select person0_.id as id1_0_0_, person0_.gender as gender2_0_0_, person0_.hobby as hobby3_0_0_, person0_.information as informat4_0_0_, person0_.name as name5_0_0_, person0_.nation as nation6_0_0_, person0_.password as password7_0_0_ from new_table person0_ where person0_.id=? Hibernate: update new_table set gender=?, hobby=?, information=?, name=?, nation=?, password=? where id=? |
这时如果改用,如果使用sessionFactory.getCurrentSession().load()方法,并且把findPersonById方法下面的语句去掉,再修改表单提交时就没有sql语句打印出来了。
@RequestMapping(value = "/modify") public Object modify(HttpServletRequest request, HttpServletResponse response, PersonForm personForm) { try { String id = personForm.getId(); Person person = personService.findPerson(id); // person.setNation(personForm.getNation()); // person.setInformation(personForm.getInformation()); // person.setGender(personForm.getGender()); // person.setHobby(personForm.getHobby()); // // person.setName(personForm.getName()); // person.setPassword(personForm.getPassword()); // // personService.modify(person); // // request.getSession().setAttribute("person", person); } catch (Exception e) { e.printStackTrace(); } return "default"; }