(二)MyBatis 实现CRUD(增删改查,有条件分页,和无条件分页)

基于上一篇博文的基础上我们来实现MyBatis的增删改查,以及分页功能。
先看
1.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名字可以随便写,但是一般都写成实体类的名字-->

<mapper namespace="com.flyz.app01.Student">
    <!-- resultMap标签:映射实体与表
         type属性:表示实体全路径名
         id属性:为实体与表的映射取一个任意的唯一的名字
    -->
    <resultMap type="student" id="studentMap">
        <!-- id标签:映射主键属性
             result标签:映射非主键属性
             property属性:实体的属性名
             column属性:表的字段名
        -->
        <id property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="sal" column="sal"/>
    </resultMap>


    <!--<select id="findById" parameterType="int" resultType="student">-->
         <!--select * from students where id = #{id}-->
   <!--</select>-->
    <!--
            insert标签:要书写insert这么一个sql语句
            id属性:为insert这么一个sql语句取一个任意唯一的名字
            parameterType:要执行的dao中的方法的参数,如果是类的话,必须使用全路径类
        -->


    <!--没有参数的add方法-->
    <insert id="add1">
        insert into students(id,name,sal) values(5,'哈哈',7000)
    </insert>


    <!--带一个Student为参数的方法-->
    <insert id="add2" parameterType="student">
        insert into students(id,name,sal) values(#{id},#{name},#{sal}) <!-- #{属性名} 这种方式引用从参数中传过来的student的参数中的值-->
    </insert>


    <!-- 根据ID查询学生
         如果参数不是一个实体的话,只是一个普通变量,例如:int,double,String
         这里的#{中间的变量名可以随便写},不过提倡就用方法的形参
     -->
    <select id="findById" parameterType="int" resultType="student">
        select id,name,sal from students where id = #{id}<!-- #{属性名} 这种方式引用从参数中传过来的student的参数中的值-->
    </select>



    <!-- 查询所有学生
         理论上resultType要写List<Student>
         但这里只需书写List中的类型即可,即只需书写Student的全路径名
    -->
    <select id="findAll" resultType="student">
        select id,name,sal from students
    </select>



    <!-- 更新学生 -->
    <update id="update" parameterType="student">
        update students set name=#{name},sal=#{sal} where id=#{id}<!-- #{属性名} 这种方式引用从参数中传过来的student的参数中的值-->
    </update>



    <!-- 删除学生 -->
    <delete id="delete" parameterType="student">
        delete from students where id = #{id}<!-- #{属性名} 这种方式引用从参数中传过来的student的参数中的值-->
    </delete>


    <!--
    <insert id="delete" parameterType="cn.itcast.javaee.mybatis.app09.Student">
        delete from students where id = #{id}
    </insert>
    -->


    <!--
        注意:这个insert/update/delete标签只是一个模板,在做操作时,其实是以SQL语句为核心的
             即在做增/删/时,insert/update/delete标签可通用,
             但做查询时只能用select标签
             我们提倡什么操作就用什么标签
    -->

    <select id="findAllWithFy" parameterType="map" resultMap="studentMap">
        select id,name,sal
        from students
        limit #{pstart},#{psize}
    </select>


    <select id="findAllByNameWithFy" parameterType="map" resultMap="studentMap">
        select id,name,sal
        from students
        where name like #{pname}
        limit #{pstart},#{psize}
    </select>

</mapper>

2.StudentDao.java:

package com.flyz.app01;

import com.flyz.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class StudentDao {
    /**
     * 增加学生
     */
    public void add1() throws Exception{
        SqlSession sqlSession = null;
        try{
            sqlSession = MybatisUtil.getSqlSession();
            //事务开始(默认)
            //读取StudentMapper.xml映射文件中的SQL语句
            int i = sqlSession.insert("com.flyz.app01.Student.add1");//命名空间+对应的sql的id
            System.out.println("本次操作影响了"+i+"行");
            //事务提交
            sqlSession.commit();
        }catch(Exception e){
            e.printStackTrace();
            //事务回滚
            sqlSession.rollback();
            throw e;
        }finally{
            MybatisUtil.closeSqlSession();
        }
    }
    /**
     * 增加学生
     */
    public void add2(Student student) throws Exception{
        SqlSession sqlSession = null;
        try{
            sqlSession = MybatisUtil.getSqlSession();
            //事务开始(默认)
            //读取StudentMapper.xml映射文件中的SQL语句
            sqlSession.insert(Student.class.getName()+".add2",student);
            //事务提交
            sqlSession.commit();
        }catch(Exception e){
            e.printStackTrace();
            //事务回滚
            sqlSession.rollback();
            throw e;
        }finally{
            MybatisUtil.closeSqlSession();
        }
    }

    /**
     * 根据ID查询学生
     */
    public Student findById(int id) throws Exception{
        SqlSession sqlSession = null;
        try{
            sqlSession = MybatisUtil.getSqlSession();
            Student student = sqlSession.selectOne(Student.class.getName()+".findById",id);
            sqlSession.commit();
            return student;
        }catch(Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            throw e;
        }finally{
            MybatisUtil.closeSqlSession();
        }
    }
    /**
     * 查询所有学生
     */
    public List<Student> findAll() throws Exception{
        SqlSession sqlSession = null;
        try{
            sqlSession = MybatisUtil.getSqlSession();
            return sqlSession.selectList(Student.class.getName()+".findAll");
        }catch(Exception e){
            e.printStackTrace();
            throw e;
        }finally{
            MybatisUtil.closeSqlSession();
        }
    }
    /**
     * 更新学生
     */
    public void update(Student student) throws Exception{
        SqlSession sqlSession = null;
        try{
            sqlSession = MybatisUtil.getSqlSession();
            sqlSession.update(Student.class.getName()+".update",student);
            sqlSession.commit();
        }catch(Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            throw e;
        }finally{
            MybatisUtil.closeSqlSession();
        }
    }
    /**
     * 删除学生
     */
    public void delete(Student student) throws Exception{
        SqlSession sqlSession = null;
        try{
            sqlSession = MybatisUtil.getSqlSession();
            sqlSession.delete(Student.class.getName()+".delete",student);
            sqlSession.commit();
        }catch(Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            throw e;
        }finally{
            MybatisUtil.closeSqlSession();
        }
    }




    /**
     * 无条件分页
     * @param start 表示在mysql中从第几条记录的索引号开始显示,索引从0开始
     * @param size 表示在mysql中最多显示几条记录
     */
    public List<Student> findAllWithFy(int start,int size) throws Exception{
        SqlSession sqlSession = null;
        try{
            sqlSession = MybatisUtil.getSqlSession();

            Map<String,Object> map = new LinkedHashMap<String,Object>();
            map.put("pstart",start);
            map.put("psize",size);
            return sqlSession.selectList(Student.class.getName()+".findAllWithFy",map);
        }catch(Exception e){
            e.printStackTrace();
            throw e;
        }finally{
            MybatisUtil.closeSqlSession();
        }
    }
    /**
     * 有条件分页
     */
    public List<Student> findAllByNameWithFy(String name,int start,int size) throws Exception {
        SqlSession sqlSession = null;
        try {
            sqlSession = MybatisUtil.getSqlSession();
            Map<String, Object> map = new LinkedHashMap<String, Object>();
            map.put("pname", "%" + name + "%");
            map.put("pstart", start);
            map.put("psize", size);
            return sqlSession.selectList(Student.class.getName() + ".findAllByNameWithFy", map);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            MybatisUtil.closeSqlSession();
        }
    }
}

MybatisUtil.java

package com.flyz.util;

import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * 工具类
 * @author AdminTC
 */
public class MybatisUtil {
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
    private static SqlSessionFactory sqlSessionFactory;
    /**
     * 加载位于src/mybatis.xml配置文件
     */
    static{
        try {
            Reader reader = Resources.getResourceAsReader("mybatis.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    /**
     * 禁止外界通过new方法创建
     */
    private MybatisUtil(){}
    /**
     * 获取SqlSession
     */
    public static SqlSession getSqlSession(){
        //从当前线程中获取SqlSession对象
        SqlSession sqlSession = threadLocal.get();
        //如果SqlSession对象为空
        if(sqlSession == null){
            //在SqlSessionFactory非空的情况下,获取SqlSession对象
            sqlSession = sqlSessionFactory.openSession();
            //将SqlSession对象与当前线程绑定在一起
            threadLocal.set(sqlSession);
        }
        //返回SqlSession对象
        return sqlSession;
    }
    /**
     * 关闭SqlSession与当前线程分开
     */
    public static void closeSqlSession(){
        //从当前线程中获取SqlSession对象
        SqlSession sqlSession = threadLocal.get();
        //如果SqlSession对象非空
        if(sqlSession != null){
            //关闭SqlSession对象
            sqlSession.close();
            //分开当前线程与SqlSession对象的关系,目的是让GC尽早回收
            threadLocal.remove();
        }
    }

}




以上就是关于这CRUD的配置,基于上一篇博文的基础就可以实现正删改查了。需要说的是,这两个文件的内容是相互配合的。

3.下面以update方法来说明一下:

a) StudentDao.java文件中


09.jpg

a) StudentMapping.xml文件中


10.jpg

4.在分页查询中的参数需要注意了:如果传的不是student类型,而且是多个参数的话,参数类型就应该写map 以分页条件查询为例:


11.jpg
11.png

ok以上就是普通方式的CURD查询

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. 简介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的...
    笨鸟慢飞阅读 5,862评论 0 4
  • 一. Java基础部分.................................................
    wy_sure阅读 3,877评论 0 11
  • JAVA面试题 1、作用域public,private,protected,以及不写时的区别答:区别如下:作用域 ...
    JA尐白阅读 1,195评论 1 0
  • 文/恰恰天蓝 1 如果一个人生病了,与这个人生活的相关的日常都会被打乱,重排。 儿子发烧,高烧不退,咳嗽,整个人乏...
    恰恰天蓝阅读 600评论 1 2
  • 花艳 国画作品参加全国省市美展多次获奖;并被博物馆、美术馆等单位及个人收藏; 作品被收录多部大型专业书刊;电视台...
    卉泽軒工作室阅读 3,054评论 0 0