Spring 框架整合Struts2 框架和 Hibernate 框架
1. Spring 框架整合 Struts2 框架
// [第一种整合方式(不推荐)](http://www.cnblogs.com/linkworld/p/7718274.html)
// 从 ServletContext 中获取 Service 对象
ServletContext servletContext = ServletActionContext.getServletContext();
WebApplicationContext ac =
WebApplicationContextUtils.getWebApplicationContext(servletContext);
CustomerService cs = (CustomerService)ac.getBean("customerService");
// 调用业务层方法
cs.save(customer);
// 第二种方式: Action 由 Struts2 框架创建
// 因为导入的 struts2-spring-plugin-2.3.24.jar 包自带一个配置文件 struts-plugin.xml,
// 该配置文件中有如下代码:
// <constant name="struts.objectFactory" value="spring"/> 开启一个常量,如果该常量开启,
// 那么下面的常量(位于default.properties 中)就可以使用
// struts.objectFactory.spring.autoWire = name, 该常量可以让 Action 类自动装配Bean对象!
public class CustomerAction extends ActionSupport implements ModelDriven<Customer>{
// 模型驱动,封装请求数据
private Customer customer = new Customer();
public Customer getModel(){
return customer;
}
// Action 类自动装配 Bean 对象,需要提供 set 方法
private CustomerService customerService;
public void setCustomerService(CustomerService customerService){
this.customerService = customerService;
}
// 保存客户
public String add(){
customerService.save(customer);
return NONE;
}
}
// 第三种方式: Action 由 Spring 框架来创建(推荐)
// 把具体的 Action 类配置到 applicationContext.xml 文件中,注意: struts.xml 需要做修改
// applicationContext.xml
<bean id="customerAction" class="com.itheima.web.action.CustomerAction" scope="prototype">
<property name="customerService" ref="customerService"/>
</bean>
// struts.xml 中的修改,把全路径修改成 ID 值
<action name="customer_*" class="customerAction" method="{1}"/>
// 第三种方式需要注意两个地方
// Spring 框架默认生成 CustomerAction 是单例的, 而 Struts2 框架是多例的,所以需要配置 scope="prototype"
// CustomerService 现在必须自己手动注入
public class CustomerAction extends ActionSupport implements ModelDriven<Customer>{
// 模型驱动,封装请求数据
private Customer customer = new Customer();
public Customer getModel(){
return customer;
}
// 此处为依赖注入
private CustomerService customerService;
public void setCustomerService(CustomerService customerService){
this.customerService = customerService;
}
// 保存客户
public String add(){
customerService.save(customer);
return NONE;
}
}
2. Spring 框架整合 Hibernate 框架
// 最初代码
public class CustomerDaoImpl implements CustomerDao{
public void save(Customer customer){
// 将数据保存到数据库
HibernateTemplate template = new HibernateTemplate();
template.save(customer);
}
}
// 升级版
// 将 template 的创建交给 Spring 框架管理
// applicationContext.xml
<bean id="customerDao" class="com.itheima.dao.CustomerDaoImpl">
<property name="hibernateTemplate" ref="hibernateTemplate"/>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
<!-- hibernateTemplate 底层依赖的是 session, 所以需要传入sessionFactory创建session-->
<property name="sessionFactory"/>
</bean>
public class CustomerDaoImpl implments CustomerDao{
private HibernateTemplate hibernateTemplate;
public void setHibernateTemplate(HibernateTemplate hibernateTemplate){
this.hibernateTemplate = hibernateTemplate;
}
// 保存客户
public void save(Customer customer){
hibernateTemplate.save(customer);
}
}
// 第三次升级
// 直接继承 HibernateDaoSupport
public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao{
// 保存客户
public void save(Customer customer){
this.getHibernateTemplate().save(customer);
}
// 修改客户
public void update(Customer customer){
this.getHibernateTemplate().update(customer);
}
// 删除客户
public void delete(Customer customer){
this.getHibernateTemplate().delete(customer);
}
// 通过主键查询客户
// findById(Class<T> clazz, id)
public void findById(Long cust_id){
this.getHibernateTemplate().get(Customer.class, cust_id);
}
// 查询所有
// find(String queryString, Object...values)
public List<T> findAll(){
this.getHibernateTemplate().find("from Customer");
}
// 分页查询
public PageBean<Customer> findByPage(Integer pageCode, Integer pageSize, DetachedCriteria criteria){
// 创建分页对象
PageBean<T> page = new PageBean<T>();
// 设置属性
page.setPageCode(pageCode);
page.setPageSize(pageSize);
// 设置聚合函数, SQL 已经变成了 select count(*) from
criteria.setProjection(Projections.rowCount());
List<Number> list = (List<Number>)this.getHibernateTemplate().findByCriteria(criteria);
if(list != null && list.size() > 0){
int totalCount = list.get(0).intValue();
page.setTotalCount(totalCount);
}
// 清除SQL, select * from
criteria.setProjection(null);
List<Customer> beanList =
(List<Customer>)this.getHibernateTemplate().findByCriteria(
criteria, (pageCode - 1)*pageSize, pageSize);
page.setBeanList(beanList);
return page;
}
}
// applicationContext.xml
<bean id="customerDao" class="com.itheima.dao.CustomerDaoImpl">
<!-- hibernateDaoSupport 类中会判断,如果 hibernateTemplate 不存在,会创建 -->
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
// 第一种整合方式: 带有 hibernate.cfh.xml 的配置文件
// hibernate.cfg.xml
<!-- 映射配置 -->
<mapping resource="com/itheima/domain/Customer.hbm.xml"/>
// applicationContext.xml
<!-- 编写 bean, 名称都是固定的,加载 hibernate.cfg.xml 的配置文件
并创建 sessionFactory 对象 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml"/>
</bean>
<!-- 配置平台事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<!-- session 可以管理事务, sessionFactory 是生产 session 的地方 -->
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- 开启事务的注解 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- 持久层需要使用 sessionFactory 对象 -->
<bean id="customerDao" class="com.itheima.dao.CustomerDaoImpl">
<!-- hibernateDaoSupport 类中会判断,如果 hibernateTemplate 不存在,会创建 -->
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
// CustomerServiceImpl.java
// 在业务层添加事务的注解
@Transactional
public class CustomerServiceImpl implements CustomerService{
private CustomerDao customerDao;
public void setCustomerDao(CustomerDao customerDao){
this.customerDao = customerDao;
}
// 保存客户
public void save(Customer customer){
customerDao.save(customer);
}
}
// CustomerDaoImpl.java
public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao{
// 保存客户
public void save(Customer customer){
this.getHibernateTemplate().save(customer);
}
}
// 第二种整合方式: 不带有 hibernate.cfg.xml 的配置文件
// 1. hibernate 配置文件中
// * 数据库连接基本参数(四大参数)
// * Hibernate 相关的属性
// * 连接池
// * 映射文件
// 在 applicationContext.xml 中进行配置上述信息
// 先配置连接池相关的信息
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mydb1"/>
<property name="user" value="root"/>
<property name="password" value="root"/>
</bean>
// LocalSessionFactory 加载配置文件
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
// 加载连接池
<property name="dataSource" ref="dataSource"/>
// 加载数据库方言,加载可选项
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
// 引入映射的配置文件
<property name="mappingResources">
<list>
<value>com/itheima/domain/Cusomter.hbm.xml</value>
</list>
</property>
</bean>
参考资料