美文网首页
Spring Mvc懒加载机制

Spring Mvc懒加载机制

作者: 使劲挤海绵 | 来源:发表于2018-06-01 01:05 被阅读48次
    • 在 web.xml中添加:
    <!-- 解决懒加载问题 -->
    
       <filter>
           <filter-name>OpenEntityManagerInViewFilter</filter-name>
           <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
           <init-param>
               <!-- 指定org.springframework.orm.jpa.LocalEntityManagerFactoryBean在spring配置文件中的名称,默认值为entityManagerFactory
                   如果LocalEntityManagerFactoryBean在spring中的名称不是entityManagerFactory,该参数一定要指定,否则会出现找不到entityManagerFactory的例外 -->
               <param-name>entityManagerFactoryBeanName</param-name>
               <param-value>entityManagerFactory</param-value>
           </init-param>
       </filter>
       <filter-mapping>
           <filter-name>OpenEntityManagerInViewFilter</filter-name>
           <url-pattern>/*</url-pattern>
       </filter-mapping>
    
       <context-param>
           <param-name>contextConfigLocation</param-name>
           <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
       </context-param>
    
       <listener>
           <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
       </listener>
       <!-- 解决懒加载问题 -->
    
    • 接下来最重要的是要在操作数据的函数上增加@Transactional注解(javax.transaction.Transactional),例如
    public class CarController {
        private static final String TAG = CarController.class.getSimpleName();
        private static final Logger LOGGER = LoggerFactory.getLogger(CarController.class);
        @Autowired
        private CarRepository mCarRepository;
    
    
        @Transactional
        @RequestMapping(method = RequestMethod.GET)
        public Response<List<CarVo>> list() {
            LOGGER.info(TAG, " car data: list");
    
            Response<List<CarVo>> response = new Response<>();
            response.data = DomainCopyUtil.mapList(mCarRepository.findAll(), CarVo.class);
            LOGGER.info(" car data: " + response.data);
            if(response.data == null) {
                response.setStatusCode(ResponseCode.CODE_GOODS_GET_ALL_ERROR);
            }
            return response;
        }  
    }
    
    

    相关文章

      网友评论

          本文标题:Spring Mvc懒加载机制

          本文链接:https://www.haomeiwen.com/subject/rjxhsftx.html