Spring+Struts2+MyBatis+分页(mybatis无代理)增删改查

Posted CHIL

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring+Struts2+MyBatis+分页(mybatis无代理)增删改查相关的知识,希望对你有一定的参考价值。

1、创建如下项目结构

2、在src下的com.entity包下创建Dept.java

package com.entity;
/**
 * 部门表
 * @author CHIL
 *
 */
public class Dept {
    private Integer deptno; //部门编号
    private String dname; //部门名称
    private String loc; //位置
   

    public Dept() {
    }

    public Dept(Integer deptno, String dname, String loc) {
        this.deptno = deptno;
        this.dname = dname;
        this.loc = loc;
    }

    public Integer getDeptno() {
        return deptno;
    }

    public void setDeptno(Integer deptno) {
        this.deptno = deptno;
    }

    public String getDname() {
        return dname;
    }

    public void setDname(String dname) {
        this.dname = dname;
    }

    public String getLoc() {
        return loc;
    }

    public void setLoc(String loc) {
        this.loc = loc;
    }
    
}

Dept.java
Dept.java

 

3、在src下的com.page包下创建Page.java

package com.page;
/**
 * 
 * @author CHIL
 *
 */
public class Page {
    private Integer pageno;  
    private Integer pagesize;
    private Integer totalcount;
    private Integer totalpage;
    private Integer startrow;
    private Integer endrow;
    
    
    public Page() {
    }
    public Page(Integer pageno, Integer pagesize, Integer totalcount) {
        this.pageno = pageno;
        this.pagesize = pagesize;
        this.startrow=pageno*pagesize;
        this.endrow=(pageno-1)*pagesize;
        this.totalcount = totalcount;
        this.setTotalpage(totalcount);
    }
    public Integer getPageno() {
        return pageno;
    }
    public void setPageno(Integer pageno) {
        this.pageno = pageno;
    }
    public Integer getPagesize() {
        return pagesize;
    }
    public void setPagesize(Integer pagesize) {
        this.pagesize = pagesize;
    }
    public Integer getTotalcount() {
        return totalcount;
    }
    public void setTotalcount(Integer totalcount) {
        this.totalcount = totalcount;
    }
    public Integer getTotalpage() {
        return totalpage;
    }
    /**
     * 总条数
     * @param totalcount
     */
    public void setTotalpage(Integer totalcount) {
        this.totalpage = totalcount%pagesize==0? totalcount/pagesize:totalcount/pagesize+1;
    }
    public Integer getStartrow() {
        return startrow;
    }
    public void setStartrow(Integer startrow) {
        this.startrow = startrow;
    }
    public Integer getEndrow() {
        return endrow;
    }
    public void setEndrow(Integer endrow) {
        this.endrow = endrow;
    }
    

}

Page.java
Page.java

 

4、在src下的com.mapper包下创建DeptMapper.java

package com.mapper;

import java.util.List;

import com.entity.Dept;
import com.page.Page;

/**
 * 数据访问层接口
 * @author CHIL
 *
 */
public interface DeptMapper {

    //查询所有
    public List<Dept> findAll();
    //分页查询
    public List<Dept> findPage(Page page);
    //查询总记录数
    public Integer findCount();
    //根据id查询
    public Dept findById(int id);
    //保存对象
    public int saveDept(Dept dept);
    //修改对象
    public int updateDept(Dept dept);
    //根据id删除
    public int deleteById(int id);
}

DeptMapper.java
DeptMapper.java

 

5、在src下的com.mapper包下创建DeptMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.mapper.DeptMapper">
<!-- 查询所有 -->
  <select id="findAll" resultType="dept">
    select * from dept
  </select>
  <!-- 分页查询 -->
  <select id="findPage" resultType="dept" parameterType="page">
  <![CDATA[
     select * from
     (
       select rownum r,deptno,dname,loc from dept
       where rownum<=#{startrow}
       )d 
      where d.r> #{endrow}
  ]]>
  </select>
  <!-- 查询总记录数 -->
  <select id="findCount" resultType="Integer">
    select count(*) from dept
  </select>
  <!-- 根据id查询 -->
  <select id="findById" parameterType="int" resultType="dept">
    select * from dept where deptno=#{deptno}
  </select>
  <!-- 保存对象 -->
  <insert id="saveDept" parameterType="dept">
     insert into dept values(#{deptno},#{dname},#{loc})
  </insert>
  <!-- 修改对象 -->
  <update id="updateDept" parameterType="dept">
     update dept set dname=#{dname},loc=#{loc} where deptno=#{deptno}
  </update>
  <!-- 根据id删除 -->
  <delete id="deleteById" parameterType="int">
     delete from dept where deptno=#{deptno}
  </delete>
  
</mapper>

DeptMapper.xml
DeptMapper.xml

 

6、在src下创建mybatis-config.xml主配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd" >
<configuration>
<!-- 别名映射 -->
  <typeAliases>
    <typeAlias type="com.entity.Dept" alias="dept"/>
    <typeAlias type="com.page.Page" alias="page"/>
  </typeAliases>
  <!-- 注册xml文件 -->
  <mappers>
    <mapper resource="com/mapper/DeptMapper.xml"/>
  </mappers>
</configuration>

mybatis-config.xml
mybatis-config.xml

 

7、在src下创建log4j.properties日志属性文件

log4j.rootLogger=DEBUG, Console  
  
#Console  
log4j.appender.Console=org.apache.log4j.ConsoleAppender  
log4j.appender.Console.layout=org.apache.log4j.PatternLayout  
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n  
  
log4j.logger.java.sql.ResultSet=INFO  
log4j.logger.org.apache=INFO  
log4j.logger.java.sql.Connection=DEBUG  
log4j.logger.java.sql.Statement=DEBUG  
log4j.logger.java.sql.PreparedStatement=DEBUG   

log4j.properties
log4.properties

 

8、在src下的com.mapper.impl包下创建DeptMapperImpl.java

package com.mapper.impl;

import java.util.List;

import org.mybatis.spring.SqlSessionTemplate;

import com.entity.Dept;
import com.mapper.DeptMapper;
import com.page.Page;
/**
 * 数据访问层接口的实现类
 * @author CHIL
 *
 */
public class DeptMapperImpl implements DeptMapper {
    //注入seqsession对象
    private SqlSessionTemplate sqlSessionTemplate;
    
    //必须存在getter和setter否则xml文件不能注入,会报没有session
    public SqlSessionTemplate getSqlSessionTemplate() {
        return sqlSessionTemplate;
    }

    public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
        this.sqlSessionTemplate = sqlSessionTemplate;
    }
    /**
     * 1.根据id删除 
     */
    public int deleteById(int id) {
        int num=sqlSessionTemplate.delete("com.mapper.DeptMapper.deleteById", id);
        if(num>0){
            System.out.println("删除成功");
        }else{
            System.out.println("删除失败");
        }
        return num;
    }

    /**
     * 2.添加部门信息
     */
    public int saveDept(Dept dept) {
        int num=sqlSessionTemplate.insert("com.mapper.DeptMapper.saveDept", dept);
        if(num>0){
            System.out.println("添加成功");
        }else{
            System.out.println("添加失败");
        }
        return num;
    }
    /**
     * 3.修改
     */
    public int updateDept(Dept dept) {
        int num=sqlSessionTemplate.update("com.mapper.DeptMapper.updateDept", dept);
        if(num>0){
            System.out.println("修改成功");
        }else{
            System.out.println("修改失败");
        }
        return num;
    }
    
    /**
     * 4.查询所有
     */
    public List<Dept> findAll() {
        List<Dept> list=sqlSessionTemplate.selectList("com.mapper.DeptMapper.findAll");
        if(list!=null){
            System.out.println("查到所有");
        }else{
            System.out.println("没有查到所有");
        }
        return list;
    }
    /**
     * 5.根据id没有查到
     */
    public Dept findById(int id) {
        Dept dept=sqlSessionTemplate.selectOne("com.mapper.DeptMapper.findById",id);
        if(dept!=null){
            System.out.println("根据id查到");
        }else{
            System.out.println("根据id没有查到");
        }
        return dept;
    }
   /**
    * 分页查询
    */
    public List<Dept> findPage(Page page) {
        List<Dept> list=sqlSessionTemplate.selectList("com.mapper.DeptMapper.findPage",page);
        if(list!=null){
            System.out.println("分页查到了");
        }else{
            System.out.println("分页没有查到");
        }
        return list;
    }
   /**
    * 查询总记录数
    */
    public Integer findCount() {
        Integer totalCount=sqlSessionTemplate.selectOne("com.mapper.DeptMapper.findCount");
        return totalCount;
    }
    

    

}

DeptMapperImpl.java
DeptMapperImpl.java

 

9、在src下的com.service包下创建DeptService.java

package com.service;

import java.util.List;

import com.entity.Dept;
import com.page.Page;
/**
 * 业务逻辑层接口
 * @author CHIL
 *
 */
public interface DeptService {
    //查询所有
    public List<Dept> findAll();
    //分页查询
    public List<Dept> findPage(Page page);
    //查询总记录数
    public Integer findCount();
    //根据id查询
    public Dept findById(int id);
    //保存对象
    public int saveDept(Dept dept);
    //修改对象
    public int updateDept(Dept dept);
    //根据id删除
    public int deleteById(int id);

}

DeptService.java
DeptService.java

 

10、在src下的com.service.impl包下创建DeptServiceImpl.java

package com.service;

import java.util.List;

import com.entity.Dept;
import com.page.Page;
/**
 * 业务逻辑层接口
 * @author CHIL
 *
 */
public interface DeptService {
    //查询所有
    public List<Dept> findAll();
    //分页查询
    public List<Dept> findPage(Page page);
    //查询总记录数
    public Integer findCount();
    //根据id查询
    public Dept findById(int id);
    //保存对象
    public int saveDept(Dept dept);
    //修改对象
    public int updateDept(Dept dept);
    //根据id删除
    public int deleteById(int id);

}

DeptService.java
DeptSerivceImpl.java

 

11、在src下的com.action包下创建DeptAction.java

package com.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.entity.Dept;
import com.opensymphony.xwork2.ActionSupport;
import com.page.Page;
import com.service.DeptService;
/**
 * 
 * @author CHIL
 *
 */
public class DeptAction extends ActionSupport {
    
     //注入业务逻辑层对象
     private DeptService service;
     
     //struts标签中动态代理赋值对象
     private Dept dept;
     
     //分页对象
     private Page page;
     
     /**
      * 1.查询所有
      * @return
      */
     public String findAll(){
         List<Dept> list=service.findAll();
         if(list!=null){
             HttpServletRequest request=ServletActionContext.getRequest();
             request.setAttribute("list", list);
             return SUCCESS;
         }else{
             return ERROR;
         }
         
     }
     
     /**
      * 1.分页查询所有
      * @return
      */
     public String findPage(){
         //当前页
         Integer pageNo=1;
         if(page!=null){
             System.out.println("page不为空");
             pageNo=page.getPageno();
         }else{
             System.out.println("page为空");
         }
         //页面大小
         Integer pageSize=3;
         //查询总条数
         Integer totalCount= service.findCount();
         page=new Page(pageNo, pageSize, totalCount);
         List<Dept> list=service.findPage(page);
         if(list!=null){
             HttpServletRequest request=ServletActionContext.getRequest();
             request.setAttribute("list", list);
             request.setAttribute("page", page);
             return SUCCESS;
         }else{
             return ERROR;
         }
         
     }
     /**
      * 根据id查询
      * @return
      */
     public String findById(){
         if(dept!=null){
             Dept dt=service.findById(dept.getDeptno());
             if(dt!=null){
                 HttpServletRequest request=ServletActionContext.getRequest();
                 request.setAttribute("dt", dt);
                 return SUCCESS;
             }
         }
            return ERROR;
        
     }
     /**
      * 添加
      * @return
      */
     public String save(){
         if(dept!=null){
             int num=service.saveDept(dept);
             if(num>0){
                 return SUCCESS;
             }else{
                 return ERROR;
             }
         }
         return ERROR;
     }
     /**
      * 修改
      * @return
      */
     public String update(){
         if(dept!=null){
             int num=service.updateDept(dept);
             if(num>0){
                 return SUCCESS;
             }else{
                 return ERROR;
             }
         }
         return ERROR;
         
     }
     /**
      * 删除
      * @return
      */
     public String delete(){
         if(dept!=null){
             int num=service.deleteById(dept.getDeptno());
             if(num>0){
                 return SUCCESS;
             }else{
                 return ERROR;
             }
         }
         return ERROR;
     }
    

    public DeptService getService() {
        return service;
    }

    public void setService(DeptService service) {
        this.service = service;
    }

    public Dept getDept() {
        return dept;
    }

    public void setDept(Dept dept) {
        this.dept = dept;
    }

    public Page getPage() {
        return page;
    }

    public void setPage(Page page) {
        this.page = page;
    }
     
    
}

DeptAction.java
DeptAction.java

 

12、在src下创建Spring的配置文件applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:tx="http://www.springframework.org/schema/tx" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans.xsd ">
 <!-- 1.数据源配置 -->
 <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
   <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
   <property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl"/>
   <property name="username" value="scott"/>
   <property name="password" value="tiger"/>
 </bean>
 
 <!-- 2.配置事务 -->
 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <!--  事务中注入数据源-->
    <property name="dataSource" ref="dataSource"/>
 </bean>
 
 <!-- 3.配置SqlSessionFactory -->
 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <!-- 注入数据源 -->
    <property name="dataSource" ref="dataSource"/>
    <!-- 注入mybaits主配置文件 -->
    <property name="configLocation">
      <value>classpath:mybatis-config.xml</value>
    </property>
 </bean>
 
 <!-- 4.获取SqlSessionTemplate -->
 <

以上是关于Spring+Struts2+MyBatis+分页(mybatis无代理)增删改查的主要内容,如果未能解决你的问题,请参考以下文章

Struts2 + Spring + Hibernate 分页

Struts2如何实现Struts2与Spring的整合 外加 MyBatis 框架

ssm(struts2+spring+mybatis)整合

Struts2+Spring+Mybatis+Junit 测试

struts2+spring+mybatis框架整合详细介绍

转 :手动配置三大框架整合:Spring+Struts2+mybatis