美文网首页
Mybatis框架demo--实现学生信息的增删改查

Mybatis框架demo--实现学生信息的增删改查

作者: GeekMasker | 来源:发表于2017-12-14 20:36 被阅读0次

一、简述

 MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis,实质上Mybatis对ibatis进行一些改进。 现在托管到gitHub上,下载:https://github.com/mybatis/mybatis-3/releases
MyBatis是一个优秀的持久层框架,它对jdbc的操作数据库的过程进行封装,使开发者只需要关注 SQL 本身,而不需要花费精力去处理例如注册驱动、创建connection、创建statement、手动设置参数、结果集检索等jdbc繁杂的过程代码。
 这个demo是针对mybatis学习而进行的简单的crud操作,并通过jsonp跨域将查询封装的数据发送至前台。关于mybatis这个框架的原理我就不再赘述了,上实例!

二、运行环境

2.1 软件环境

Eclipse + Tomcat7 + Mysql

2.2 软件架构

servlet+ mybatis框架 + html + bootstrap框架 + ajax + jsonp

2.3 数据库表结构

CREATE TABLE `stu` (
  `sno` varchar(10) NOT NULL,
  `sname` varchar(20) NOT NULL,
  `sage` int(10) DEFAULT NULL,
  `ssex` varchar(5) DEFAULT NULL,
  PRIMARY KEY (`sno`),
  UNIQUE KEY `sno` (`sno`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

2.4 主要jar包

三、例子结构

3.1 web项目结构

3.2 前台项目结构

四、主要实现代码

4.1 mybatis.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>

    <!-- 配置通用mapper -->
    <!-- <plugins></plugins> -->

    <!-- 给路径取别名,放在environments前面 -->
    <!-- <typeAliases>
        <typeAlias type="dao.StudentDao" alias="stu" />
    </typeAliases> -->

    <environments default="development">
        <environment id="development">
            <!-- 事务管理 -->
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="username" value="root" />
                <property name="url" value="jdbc:mysql://localhost:3306/student" />
                <property name="password" value="123" />
                <property name="driver" value="com.mysql.jdbc.Driver" />
            </dataSource>
        </environment>

    </environments>
    <!-- 配置 映射文件 -->
    <mappers>
        <mapper resource="entity/StudentMapper.xml" />
    </mappers>
</configuration>

4.2 StudentMapper.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">
<!-- namespace命名空间,作用就是对sql进行分类管理
    注意:使用mapper代理方法开发时,namespace需要特殊设置
 -->
<mapper namespace="dao.StudentDao">
    
    <!-- 查询所有学生信息 -->
    <resultMap type="entity.Student" id="stuMap">
        <id column="sno" javaType="String" property="sno"></id>     
        <result column="sname" javaType="String" property="sname"/>
        <result column="ssex" javaType="String" property="ssex"/>
        <result column="sage" javaType="int" property="sage"/>
    </resultMap>
    
    <select id="findAllStudent" resultMap="stuMap">
        select * from stu
    </select>
    
    <!-- 实现分页查询学生信息 -->
    <select id="findPageStudent" parameterType="map" resultType="entity.Student">
        SELECT * FROM stu LIMIT #{startSize},#{pageSize}
    </select>
    
    <!-- 实现学生信息的添加操作 -->
    <insert id="doInsert" parameterType="entity.Student">
        INSERT INTO stu
        <include refid="columns_mysql"></include>
        VALUES
        <include refid="values_columns"></include>
    </insert>
    
    <!-- 添加的sql片段开始 -->
    <sql id = "columns_mysql">
        <trim prefix="(" suffix=")" suffixOverrides="," >
            <if test="sno!=null">
                sno,
            </if>
            <if test="sname!=null">
                sname,
            </if>
            <if test="sage!=null">
                sage,
            </if>
            <if test="ssex!=null">
                ssex,
            </if>
        </trim>
    </sql>
    
    <sql id="values_columns">
        <trim prefix="(" suffix=")" suffixOverrides="," >
            <if test="sno!=null">
                #{sno},
            </if>
            <if test="sname!=null">
                #{sname},
            </if>
            <if test="sage!=null">
                #{sage},
            </if>
            <if test="ssex!=null">
                #{ssex},
            </if>
        </trim>
    </sql>
    <!-- 添加的sql片段结束 -->
    
    <!-- 实现学生信息的更新操作 -->
    <update id="doUpdateStudent" parameterType="entity.Student">
        update stu 
            set sname = #{sname},
            ssex = #{ssex},
            sage = #{sage}
        where sno = #{sno}
    </update>
    
    <!-- 根据学生id进行删除操作 -->
    <delete id="doDeleteBySno" parameterType="String">
        delete from stu where sno = #{sno}
    </delete>
    
    <!-- 查询学生表总人数 -->
    <select id="findCount" resultType="int">
        select count(*) from stu
    </select>
</mapper>

4.3 Mapper实现类StudentDaoImpl.java

public class StudentDaoImpl implements StudentDao {
    
    private SqlSession sqlSession;

    public List<Student> findAllStudent() {
        sqlSession = SqlSessionUtil.getSession();
        List<Student> list = sqlSession.selectList("findAllStudent");
        sqlSession.commit();
        sqlSession.close();
        
        return list;
    }

    public List<Student> findPageStudent(Integer startSize, Integer pageSize) {
        sqlSession = SqlSessionUtil.getSession();
        Map<String, Integer> map = new HashMap<String, Integer>();
        map.put("startSize", startSize);
        map.put("pageSize", pageSize);
        List<Student> list = sqlSession.selectList("findPageStudent",map);
        sqlSession.commit();
        sqlSession.close();
        return list;
    }

    public int doInsert(Student stu) {
        sqlSession = SqlSessionUtil.getSession();
        Integer result = sqlSession.insert("doInsert",stu);
        sqlSession.commit();
        sqlSession.close();
        
        return result;
    }

    public int doDeleteBySno(String sno) {
        sqlSession = SqlSessionUtil.getSession();
        Integer result = sqlSession.delete("doDeleteBySno",sno);
        sqlSession.commit();
        sqlSession.close();
        
        return result;
    }

    @Override
    public int doUpdateStudent(Student stu) {
        sqlSession = SqlSessionUtil.getSession();
        Integer result = sqlSession.update("doUpdateStudent",stu);
        sqlSession.commit();
        sqlSession.close();
        
        return result;
    }

    public int findCount() {
        sqlSession = SqlSessionUtil.getSession();
        Integer result = sqlSession.selectOne("findCount");
        sqlSession.commit();
        sqlSession.close();
        
        return result;
    }

}

4.4 StudentServiceImpl.java

private StudentDao stuDao = new StudentDaoImpl();
    
    public List<Student> findAllStudent() {
        return stuDao.findAllStudent();
    }

    public PageBean<Student> findPageStudent(Integer currentPage,
            Integer pageSize) {
        Integer count = stuDao.findCount();
        
        Integer allPages = count/pageSize == 0 ? count/pageSize 
                : count/pageSize + 1;
        
        if(currentPage > allPages){
            currentPage = allPages;
        }
        if(currentPage < 1){
            currentPage = 1;
        }
        PageBean<Student> pb = new PageBean<Student>();
        Integer startSize = (currentPage-1)*pageSize;
        List<Student> list = stuDao.findPageStudent(startSize, pageSize);
        
        pb.setAllPages(allPages);
        pb.setCount(count);
        pb.setCurrentPage(currentPage);
        pb.setCurrentCount(pageSize);
        pb.setList(list);
        
        return pb;
    }

    public int doInsert(Student stu) {
        return stuDao.doInsert(stu);
    }

    public int doDeleteBySno(String sno) {
        return stuDao.doDeleteBySno(sno);
    }

    public int doUpdateStudent(Student stu) {
        return stuDao.doUpdateStudent(stu);
    }

4.5 servlet主要操作的方法

4.5.1 分页查询方法

private void sendPageData(HttpServletRequest request,
            HttpServletResponse response) throws IOException{
        int pageSize = 5;
        int currentPage = 1;
        String currPage = request.getParameter("currentPage");
        if(currPage!=null){
            currentPage = Integer.parseInt(currPage);
        }
        
        PageBean<Student> pb = stuService.findPageStudent(currentPage, pageSize);
    
        JSONObject json = JSONObject.fromObject(pb);

        PrintWriter writer = response.getWriter();

        String callback = request.getParameter("callback");

        String result = callback + "(" + json.toString() + ")";
        
        writer.write(result);
    }

4.5.2 数据更新操作

private void doUpdate(HttpServletRequest request,
            HttpServletResponse response) throws IOException{
        String sno = request.getParameter("sno");
        String sname = request.getParameter("sname");
        String ssex = request.getParameter("ssex");
        Integer sage = null;
        if(request.getParameter("sage")!=null){
            sage = Integer.parseInt(request.getParameter("sage"));
        }
        
        System.out.println("姓名:"+sname+"\t性别:"+ssex+"\t学号:"+sno+"\t年纪:"+sage);
        Student stu = new Student();
        stu.setSno(sno);
        stu.setSname(sname);
        stu.setSsex(ssex);
        stu.setSage(sage);
        JSONObject json = new JSONObject();
        
        if(stuService.doUpdateStudent(stu)==1){
            json.put("msg", "修改成功");
        }else{
            json.put("msg", "修改失败");
        }
        
        PrintWriter writer = response.getWriter();

        String callback = request.getParameter("callback");

        String result = callback + "(" + json.toString() + ")";
        
        writer.write(result);
    }

4.5.3 通过学号删除学生操作

private void doDeleteBySno(HttpServletRequest request,
            HttpServletResponse response) throws IOException{
        
        String sno = request.getParameter("sno");
        JSONObject json = new JSONObject();
        if(stuService.doDeleteBySno(sno)==1){
            json.put("msg", "删除成功");
        }else{
            json.put("msg", "删除失败");
        }
        
        PrintWriter writer = response.getWriter();

        String callback = request.getParameter("callback");

        String result = callback + "(" + json.toString() + ")";
        
        writer.write(result);
    }

五、总结

  对于mybatis框架的使用,主要还是在映射文件的配置,将数据库内所查出的数据与实体类的映射,从而实现数据的持久化操作。
  MyBatis是一个优秀的持久层框架,它对jdbc的操作数据库的过程进行封装,使开发者只需要关注 SQL 本身,而不需要花费精力去处理例如注册驱动、创建connection、创建statement、手动设置参数、结果集检索等jdbc繁杂的过程代码。


对于前台页面,我会在下一篇文章中写出,如上面观点你们有所异议,欢迎大家给我指出。

相关文章

网友评论

      本文标题:Mybatis框架demo--实现学生信息的增删改查

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