1. BaseDao的抽取和通用功能的实现
1.1 BaseDao
public interface BaseDao<T> {
//增
void save(T t);
//删
void delete(T t);
//删
void delete(Serializable id);
//改
void update(T t);
//查 根据id查询
T getById(Serializable id);
//查 符合条件的总记录数
Integer getTotalCount(DetachedCriteria dc);
//查 查询分页列表数据
List<T> getPageList(DetachedCriteria dc, Integer start, Integer pageSize);
}
1.1 BaseDaoImpl
public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T> {
private Class clazz;
public BaseDaoImpl() {
//获得当前类型的带有泛型类型的父类
ParameterizedType ptClass = (ParameterizedType) this.getClass().getGenericSuperclass();
//获得运行期的泛型类型
clazz = (Class) ptClass.getActualTypeArguments()[0];
}
@Override
public void save(T t) {
getHibernateTemplate().save(t);
}
@Override
public void delete(T t) {
getHibernateTemplate().delete(t);
}
@Override
public void delete(Serializable id) {
getHibernateTemplate().delete(getById(id));
}
@Override
public void update(T t) {
getHibernateTemplate().update(t);
}
@Override
public T getById(Serializable id) {
return (T) getHibernateTemplate().get(clazz, id);
}
@Override
public Integer getTotalCount(DetachedCriteria dc) {
//设置查询的聚合函数,总记录数
dc.setProjection(Projections.rowCount());
List<Long> list = (List<Long>) getHibernateTemplate().findByCriteria(dc);
// 清空之前设置的聚合函数
dc.setProjection(null);
if (list != null && list.size() > 0) {
Long count = list.get(0);
return count.intValue();
} else {
return null;
}
}
@Override
public List<T> getPageList(DetachedCriteria dc, Integer start, Integer pageSize) {
List<T> list = (List<T>) getHibernateTemplate().findByCriteria(dc, start, pageSize);
return list;
}
}
2. 封装PageBean
作用:将页面传入的参数进行统一的判断处理,并且将查询到的分页数据list也存储进PageBean的对象中,方便进行重定向或者转发
public class PageBean {
//当前页数
private Integer currentPage;
//总记录数
private Integer totalCount;
//每页显示条数
private Integer pageSize;
//总页数
private Integer totalPage;
//分页列表数据
private List list;
public PageBean(Integer currentPage, Integer totalCount, Integer pageSize) {
this.currentPage = currentPage;
this.totalCount = totalCount;
this.pageSize = pageSize;
//如页面没有指定显示那一页.显示第一页.
if(this.currentPage == null){
this.currentPage = 1;
}
//如果每页显示条数没有指定,默认每页显示3条
if(this.pageSize == null){
this.pageSize = 10;
}
//计算总页数
this.totalPage = (this.totalCount+this.pageSize-1)/this.pageSize;
//判断当前页数是否超出范围
//不能小于1
if(this.currentPage < 1){
this.currentPage = 1;
}
//不能大于总页数
if(this.currentPage > this.totalPage){
this.currentPage = this.totalPage;
}
}
//计算起始索引
public int getStart(){
return (this.currentPage-1)*this.pageSize;
}
public Integer getCurrentPage() {
return currentPage;
}
public void setCurrentPage(Integer currentPage) {
this.currentPage = currentPage;
}
public Integer getTotalCount() {
return totalCount;
}
public void setTotalCount(Integer totalCount) {
this.totalCount = totalCount;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getTotalPage() {
return totalPage;
}
public void setTotalPage(Integer totalPage) {
this.totalPage = totalPage;
}
public List getList() {
return list;
}
public void setList(List list) {
this.list = list;
}
}
3. 通过继承BaseDao和封装的PageBean完成客户列表的分页查询
3.1 CustomerAction处理请求
public class CustomerAction extends ActionSupport implements ModelDriven<Customer>{
private Customer customer = new Customer();
private CustomerService customerService;
private Integer currentPage;
private Integer pageSize;
public String list() throws Exception {
//封装离线查询对象
DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Customer.class);
//判断并封装参数
if (StringUtils.isNotBlank(customer.getCust_name())) {
detachedCriteria.add(Restrictions.like("cust_name", "%"+customer.getCust_name()+"%"));
}
//1. 调用Service查询分页数据(PageBean)
PageBean pageBean = customerService.getPageBean(detachedCriteria, currentPage, pageSize);
//2. 将PageBean放入request域,转发到列表页面显示
ActionContext.getContext().put("pageBean", pageBean);
return "list";
}
public void setCustomerService(CustomerService customerService) {
this.customerService = customerService;
}
public void setCurrentPage(Integer currentPage) {
this.currentPage = currentPage;
}
public Integer getCurrentPage() {
return currentPage;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
@Override
public Customer getModel() {
return customer;
}
}
3.2 CustomerService和CustomerServiceImpl
public interface CustomerService {
// 分页方法
PageBean getPageBean(DetachedCriteria dc, Integer currentPage, Integer pageSize);
}
@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, readOnly = true)
public class CustomerServiceImpl implements CustomerService {
CustomerDao customerDao;
@Override
public PageBean getPageBean(DetachedCriteria dc, Integer currentPage, Integer pageSize) {
//1 调用Dao查询总记录数
Integer totalCount = customerDao.getTotalCount(dc);
//2 创建PageBean对象
PageBean pageBean = new PageBean(currentPage, totalCount, pageSize);
//3 调用Dao查询分页列表数据
List<Customer> list = customerDao.getPageList(dc, pageBean.getStart(), pageBean.getPageSize());
pageBean.setList(list);
return pageBean;
}
public void setCustomerDao(CustomerDao customerDao) {
this.customerDao = customerDao;
}
}
3.3 通过继承BaseDao来实现CustomerDao
public interface CustomerDao extends BaseDao<Customer> {
}
public class CustomerDaoImpl extends BaseDaoImpl<Customer> implements CustomerDao {
}
4. 配置文件最终形态
4.1 struts.xml
<struts>
<!--spring负责装配Action依赖属性,默认struts已经打开了-->
<!--<constant name="struts.objectFactory.spring.autoWire" value="name"></constant>-->
<!--将action的创建交给spring容器-->
<constant name="struts.objectFactory" value="spring"></constant>
<!-- 整合方案1:class属性上仍然配置action的完整类名
struts2仍然创建action,由spring负责组装Action中的依赖属性
-->
<package name="crm" namespace="/" extends="struts-default">
<global-exception-mappings>
<exception-mapping exception="java.lang.RuntimeException" result="error"></exception-mapping>
</global-exception-mappings>
<!--
整合方案2:class属性上填写spring中action对象的BeanName
完全由spring管理action生命周期,包括Action的创建
注意:需要手动组装依赖属性
-->
<action name="UserAction_*" class="userAction" method="{1}" >
<result name="toHome" type="redirect" >/index.htm</result>
<result name="error" >/login.jsp</result>
</action>
<action name="CustomerAction_*" class="customerAction" method="{1}">
<result name="list" type="dispatcher">/jsp/customer/list.jsp</result>
</action>
</package>
</struts>
4.2 applicationContext.xml
<!--==========================================================================================-->
<!--读取db.properties文件-->
<context:property-placeholder location="classpath:db.properties"/>
<!--配置c3p0数据库连接池-->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!--=========================================== struts2配置 ===============================================-->
<!--将sessionFactory配置到spring容器中-->
<!-- 加载配置方案2:在spring配置中放置hibernate配置信息 -->
<bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<!-- 将连接池注入到sessionFactory, hibernate会通过连接池获得连接 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 配置hibernate基本信息 -->
<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>
<!-- 引入orm元数据,指定orm元数据所在的包路径,spring会自动读取包中的所有配置 -->
<property name="mappingDirectoryLocations" value="classpath:domain"></property>
</bean>
<!--==========================================================================================-->
<!--配置核心事务管理器-->
<bean name="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!--配置通知-->
<!--<tx:advice id="txAdvice" transaction-manager="transactionManager">-->
<!--<tx:attributes>-->
<!--<tx:method name="save*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />-->
<!--<tx:method name="persist*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />-->
<!--<tx:method name="update*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />-->
<!--<tx:method name="modify*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />-->
<!--<tx:method name="delete*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />-->
<!--<tx:method name="remove*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />-->
<!--<tx:method name="get*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" />-->
<!--<tx:method name="find*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" />-->
<!--</tx:attributes>-->
<!--</tx:advice>-->
<!--<!–配置将通知织入目标对象–>-->
<!--<aop:config>-->
<!--<aop:pointcut expression="execution(* serviceImpl.*ServiceImpl.*(..))" id="txPc"/>-->
<!--<aop:advisor advice-ref="txAdvice" pointcut-ref="txPc" />-->
<!--</aop:config>-->
<!--开启注解事务-->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!--==========================================================================================-->
<!--==================================== action ===========================================-->
<bean name="userAction" class="web.UserAction" scope="prototype">
<property name="userService" ref="userService"></property>
</bean>
<bean name="customerAction" class="web.CustomerAction" scope="prototype">
<property name="customerService" ref="customerService"></property>
</bean>
<!--==================================== service ===========================================-->
<bean name="userService" class="serviceImpl.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
<bean name="customerService" class="serviceImpl.CustomerServiceImpl">
<property name="customerDao" ref="customerDao"></property>
</bean>
<!--==================================== dao ===========================================-->
<bean name="userDao" class="daoImpl.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean name="customerDao" class="daoImpl.CustomerDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
</beans>
网友评论