注意:Spring中使用Hibernate

编程技术  /  houtizong 发布于 3年前   78
1. 建议使用Hiberante进行Session和Transaction的管理
    将需要进行事务的多个原子DAO设置到Service里,在Service层进行事务控制和会话控制。
    设置一个基础的dao,即baseDAO 且继承之HibernateDaoSupport,而业务对象原子DAO,持有一个baseDAO的引用,通过setter注射设置到业务DAO中。
    多个原子DAO,通过setter注射到Service层。

2. 在显示层,一对多显示时,提示Session关闭的问题
    两个解决方法:
    1)在one-to-many设置lazy=false,即不延迟加载子对象,但这样可能会带来性能的问题,特别是父子关系模型是树状结构时。
    2)使用Hibernate提供的openSessiojnInView技术,即在视图层开启和关闭Session,在service层进行Transaction管理,这个较为简单,只需要设置一个filter即可,在web.xml中配置
<filter>
  <filter-name>hibernateFilter</filter-name>
  <filter-class>
org.springframework.orm.hibernate.support.OpenSessionInViewFilter
</filter-class>
</filter>
<filter-mapping>
  <filter-name>hibernateFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>


需要注意的是,OpenSessionInViewFilter在调用过程中,需要引用Spring的ApplicationContext,而该对象实例必须是保存在ServletContext中的,因此需要在web.xml中处始化Spring的环境,增加配置如下:
<context-param>
             <param-name>contextConfigLocation</param-name>
             <param-value>/WEB-INF/spring/applicationContext-hibernate.xml</param-value>
        </context-param>
     <servlet>
     <servlet-name>context</servlet-name>
             <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
             <load-on-startup>1</load-on-startup>
     </servlet>

其中

<servlet-name>context</servlet-name>
             <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
             <load-on-startup>1</load-on-startup>
     </servlet>


表示在启动时,进行Spring环境的处始化,因此以后如果要引用Spring中的某个bean实例

如下代码即可

org.springframework.context.ApplicationContext ctx = (org.springframework.context.ApplicationContext)application.getAttribute(org.springframework.web.context.WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);


然后调用ctx.getBean返回bean实例

Spring不只是AOP和IOC,更提供了大量的可重用技术,譬如request中的重设编码,Spring提供了相应的Filter:org.springframework.web.filter.CharacterEncodingFilter 通过直接配置,即可解决Web应用中POST的中文乱码问题,JMS的org.springframework.jms 包  JavaMail的org.springframework.mail包等等,更多的,请参看Spring的reference,

Spring能改善现有代码结构,大量的减少hard code,加快开发进度;

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!

留言需要登陆哦

技术博客集 - 网站简介:
前后端技术:
后端基于Hyperf2.1框架开发,前端使用Bootstrap可视化布局系统生成

网站主要作用:
1.编程技术分享及讨论交流,内置聊天系统;
2.测试交流框架问题,比如:Hyperf、Laravel、TP、beego;
3.本站数据是基于大数据采集等爬虫技术为基础助力分享知识,如有侵权请发邮件到站长邮箱,站长会尽快处理;
4.站长邮箱:[email protected];

      订阅博客周刊 去订阅

文章归档

文章标签

友情链接

Auther ·HouTiZong
侯体宗的博客
© 2020 zongscan.com
版权所有ICP证 : 粤ICP备20027696号
PHP交流群 也可以扫右边的二维码
侯体宗的博客