SSH框架整合:延迟加载问题的解决

一、Spring提供了延迟加载的解决方案

1、在SSH整合开发当中哪些地方会出现延迟加载

  • A 、hibernate当中使用load方法查询某一个对象的时候(不常用)

(1)在Dao层使用load方法查询对应的对象

public class CustomerAction extends ActionSupport implements ModelDriven<Customer>{
	//模型驱动使用的对象
	private Customer customer = new Customer();
	@Override
	public Customer getModel() {
		// TODO Auto-generated method stub
		return customer;
	}
	/*
	 * 注入CustomerService
	 */
	private CustomerService customerService;
	public void setCustomerService(CustomerService customerService) {
		this.customerService = customerService;
	}
	public String findById() {	
		Customer customer = customerService.findById(1l);
		System.out.println(customer);
		return NONE;
	}
}

(2)创建Action得到findById返回的值,并使用(Load方法当使用该对象的时候才会发送SQL语句)

public String findById() {		
	Customer customer = customerService.findById(1l);		
	System.out.println(customer);		
	return NONE;
}

(3)测试
在浏览器当中直接访问该action

http://localhost:8080/ssh2/customer_findById.action

报错no session
在这里插入图片描述
(4)解决办法
在web.xml当中配置解决延迟加载的过滤器,
拦截所有访问action的请求,当前action的方法执行前开启session方法执行完关闭session
在这里插入图片描述
(5)测试

http://localhost:8080/ssh2/customer_findById.action

运行没有报错成功获取到数据
在这里插入图片描述
原理图
在这里插入图片描述

  • B、查询到某个对象以后,要显示其关联的对象

在客户关系管理的时候,查询联系人的时候需要显示客户的信息,这个时候就会出现延迟加载
在这里插入图片描述
通过联系人获取客户信息的时候,
当获取完联系人信息之后,session关闭,无法查询到客户信息,
解决方式:在web.xml当中配置解决延迟加载的过滤器,
拦截所有访问action的请求,当前action的方法执行前开启session方法执行完关闭session

猜你喜欢

转载自blog.csdn.net/qq_44757034/article/details/107391292
今日推荐