d setExternalSessionFactory(Session aSession){ setSessionFactory(session.getSessionFactory()); } public Person save(Person aPerson) { if(aPerson != null) super.save(person); return person; } } 因为HibernateTemplate类继承于HibernateAccessor类,我们就可以从任何Session对象中建立SessionFactory。这是Spring小组的一个高灵活性的设计,使得重用现有代码更加容易。
也许你并没有使用Spring而是采用完全不同的方法。如果你不喜欢Spring的一来注射,你也可以通过JNDI查找Session对象:
清单8:
import net.sf.hibernate.Session;public class PersonDAO { // This example assumes that there is a Hibernate // Session object at the following JNDI location // on a Tomcat 5.5 server: // java:/comp/env/obj/hibernateSession private Session session; public PersonDAO(){ try { Context initCtx = new InitialContext(); Context envCtx = (Context) initCtx.lookup("java:comp/env"); session = (Session)envCtx.lookup("obj/hibernateSession"); }catch(Exception e) { e.printStackTrace(); } } public Person save(Person aPerson) { if(aPerson != null) session.save(person); return person; } } 以上的例子依赖于应用服务器来使得Hibernate Session对象可用。在容器之外使用的最简单方法就是添加一个带Session参数的构造函数,如下所示:
清单9:
import net.sf.hibernate.Session; public class PersonDAO { // This example assume上一页 [1] [2] [3] [4] [5] [6] [7] 下一页
|