Mybatis代理方式的增删改查
标签搜索
侧边栏壁纸
  • 累计撰写 21 篇文章
  • 累计收到 390 条评论

Mybatis代理方式的增删改查

limei
2023-07-23 / 0 评论 / 28 阅读 / 正在检测是否收录...

代理开发方式介绍

采用 Mybatis 的代理开发方式实现 DAO 层的开发,这种方式是我们后面进入企业的主流。

Mapper 接口开发方法只需要程序员编写Mapper 接口(相当于Dao 接口),由Mybatis 框架根据接口定义创建接口的动态代理对象,代理对象的方法体同上边Dao接口实现类方法。

Mapper 接口开发需要遵循以下规范:

1) Mapper.xml文件中的namespace与mapper接口的全限定名相同

2) Mapper接口方法名和Mapper.xml中定义的每个statement的id相同

3) Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql的parameterType的类型相同

4) Mapper接口方法的输出参数类型和mapper.xml中定义的每个sql的resultType的类型相同

增删改查的实现

*** 案例目录结构 ***

该案例和《Mybatis的基本使用》使用的是同一个数据库以及实体类

1.编写StudentController类
2.编写StudentMapper接口
3.编写StudentService接口
4.编写StudentServiceImpl类
5.编写StudentMapper.xml文件

  • 编写StudentController类
  • package com.limei.controller;
    
    
    import com.limei.bean.Student;
    import com.limei.service.StudentService;
    import com.limei.service.impl.StudentServiceImpl;
    import org.junit.Test;
    
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    
    /*
        控制层测试类
     */
    public class StudentController {
        //创建业务层对象
        private StudentService service = new StudentServiceImpl ();
    
        //String类型转换为Date类型
        public Date conversionDate(String s){
            String str =s;
            Date date=null;
            SimpleDateFormat sdf=null;
            try {
                sdf = new SimpleDateFormat ( "yyyy-MM-dd" );
                 date = sdf.parse ( str );
            } catch (ParseException e) {
                e.printStackTrace ();
            }
            return date;
        }
    
        //查询全部功能测试
        @Test
        public void selectAll() {
            List<Student> students = service.selectAll();
            for (Student stu : students) {
                System.out.println(stu);
            }
        }
    
        //根据id查询功能测试
        @Test
        public void selectById() {
            Student stu = service.selectById("10001");
            System.out.println(stu);
        }
    
        //新增功能测试
        @Test
        public void insert() {
            Date date = conversionDate ( "2011-09-01" );
            Student stu = new Student("10010","赵六",date,"上海市");
                Integer result = service.insert(stu);
                System.out.println(result);
        }
    
        //修改功能测试
        @Test
        public void update() {
            Date date = conversionDate ( "2011-09-01" );
            Student stu = new Student("10010","赵五",date,"上海市");
            Integer result = service.update(stu);
            System.out.println(result);
        }
    
        //删除功能测试
        @Test
        public void delete() {
            Integer result = service.delete("10010");
            System.out.println(result);
        }
    
        //    多条件查询
        @Test
        public void selectCondition(){
            Student stu = new Student();
            stu.setId("10002");
            stu.setName("李四");
            List<Student> list = service.selectCondition ( stu );
    
            //6.处理结果
            for (Student student : list) {
                System.out.println(student);
            }
    
        }
    
        //根据多个id查询
        @Test
        public void selectByIds(){
            List<String> ids = new ArrayList<> ();
            ids.add("10001");
            ids.add("10002");
            ids.add("10003");
            List<Student> list = service.selectByIds ( ids );
            for (Student student:list){
                System.out.println (student);
            }
        }
    }
    

  • 编写StudentMapper接口
  • package com.limei.mapper;
    
    import com.limei.bean.Student;
    
    import java.util.List;
    
    public interface StudentMapper {
        //查询全部
        public abstract List<Student> selectAll();
    
        //根据id查询
        public abstract Student selectById(String id);
    
        //新增数据
        public abstract Integer insert(Student stu);
    
        //修改数据
        public abstract Integer update(Student stu);
    
        //删除数据
        public abstract Integer delete(String id);
    
        //多条件查询
        public abstract List<Student> selectCondition(Student stu);
    
        //根据多个id查询
        public abstract List<Student> selectByIds(List<String> ids);
    
    }
    

  • 编写StudentService接口
  • package com.limei.service;
    
    import com.limei.bean.Student;
    
    import java.util.List;
    
    /*
        业务层接口
     */
    public interface StudentService {
        //查询全部
        public abstract List<Student> selectAll();
    
        //根据id查询
        public abstract Student selectById(String id);
    
        //新增数据
        public abstract Integer insert(Student stu);
    
        //修改数据
        public abstract Integer update(Student stu);
    
        //删除数据
        public abstract Integer delete(String id);
    
        //多条件查询
        public abstract List<Student> selectCondition(Student stu);
    
        //根据多个id查询
        public abstract List<Student> selectByIds(List<String> ids);
    }
    

  • 编写StudentServiceImpl类
  • package com.limei.service.impl;
    
    
    import com.limei.bean.Student;
    import com.limei.mapper.StudentMapper;
    import com.limei.service.StudentService;
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.ArrayList;
    import java.util.List;
    /*
        业务层实现类
     */
    public class StudentServiceImpl implements StudentService {
    
        //查询全部
        @Override
        public List<Student> selectAll() {
            List<Student> list = null;
            SqlSession sqlSession = null;
            InputStream is = null;
            try{
                //1.加载核心配置文件
                is = Resources.getResourceAsStream("MyBatisConfig.xml");
                System.out.println (is);
                //2.获取SqlSession工厂对象
                SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
    
                //3.通过工厂对象获取SqlSession对象
                sqlSession = sqlSessionFactory.openSession(true);
    
                //4.获取StudentMapper接口的实现类对象
                StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); // StudentMapper mapper = new StudentMapperImpl();
    
                //5.通过实现类对象调用方法,接收结果
                list = mapper.selectAll();
    
            } catch (Exception e) {
    
            } finally {
                //6.释放资源
                if(sqlSession != null) {
                    sqlSession.close();
                }
                if(is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
    
            //7.返回结果
            return list;
        }
    
        @Override
        public Student selectById(String id) {
            Student stu = null;
            SqlSession sqlSession = null;
            InputStream is = null;
            try{
                //1.加载核心配置文件
                is = Resources.getResourceAsStream("MyBatisConfig.xml");
    
                //2.获取SqlSession工厂对象
                SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
    
                //3.通过工厂对象获取SqlSession对象
                sqlSession = sqlSessionFactory.openSession(true);
    
                //4.获取StudentMapper接口的实现类对象
                StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); // StudentMapper mapper = new StudentMapperImpl();
    
                //5.通过实现类对象调用方法,接收结果
                stu = mapper.selectById(id);
    
            } catch (Exception e) {
    
            } finally {
                //6.释放资源
                if(sqlSession != null) {
                    sqlSession.close();
                }
                if(is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
    
            //7.返回结果
            return stu;
        }
    
        @Override
        public Integer insert(Student stu) {
            Integer result = null;
            SqlSession sqlSession = null;
            InputStream is = null;
            try{
                //1.加载核心配置文件
                is = Resources.getResourceAsStream("MyBatisConfig.xml");
    
                //2.获取SqlSession工厂对象
                SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
    
                //3.通过工厂对象获取SqlSession对象
                sqlSession = sqlSessionFactory.openSession(true);
    
                //4.获取StudentMapper接口的实现类对象
                StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); // StudentMapper mapper = new StudentMapperImpl();
    
                //5.通过实现类对象调用方法,接收结果
                result = mapper.insert(stu);
    
            } catch (Exception e) {
    
            } finally {
                //6.释放资源
                if(sqlSession != null) {
                    sqlSession.close();
                }
                if(is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
    
            //7.返回结果
            return result;
        }
    
        @Override
        public Integer update(Student stu) {
            Integer result = null;
            SqlSession sqlSession = null;
            InputStream is = null;
            try{
                //1.加载核心配置文件
                is = Resources.getResourceAsStream("MyBatisConfig.xml");
    
                //2.获取SqlSession工厂对象
                SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
    
                //3.通过工厂对象获取SqlSession对象
                sqlSession = sqlSessionFactory.openSession(true);
    
                //4.获取StudentMapper接口的实现类对象
                StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); // StudentMapper mapper = new StudentMapperImpl();
    
                //5.通过实现类对象调用方法,接收结果
                result = mapper.update(stu);
    
            } catch (Exception e) {
    
            } finally {
                //6.释放资源
                if(sqlSession != null) {
                    sqlSession.close();
                }
                if(is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
    
            //7.返回结果
            return result;
        }
    
        @Override
        public Integer delete(String id) {
            Integer result = null;
            SqlSession sqlSession = null;
            InputStream is = null;
            try{
                //1.加载核心配置文件
                is = Resources.getResourceAsStream("MyBatisConfig.xml");
    
                //2.获取SqlSession工厂对象
                SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
    
                //3.通过工厂对象获取SqlSession对象
                sqlSession = sqlSessionFactory.openSession(true);
    
                //4.获取StudentMapper接口的实现类对象
                StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); // StudentMapper mapper = new StudentMapperImpl();
    
                //5.通过实现类对象调用方法,接收结果
                result = mapper.delete(id);
    
            } catch (Exception e) {
    
            } finally {
                //6.释放资源
                if(sqlSession != null) {
                    sqlSession.close();
                }
                if(is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
    
            //7.返回结果
            return result;
        }
    
        //多条件查询
        @Override
        public List<Student> selectCondition(Student stu) {
    
            List<Student> list=null;
            SqlSession sqlSession = null;
            InputStream is = null;
            try{
                //1.加载核心配置文件
                is = Resources.getResourceAsStream("MyBatisConfig.xml");
    
                //2.获取SqlSession工厂对象
                SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
    
                //3.通过工厂对象获取SqlSession对象
                sqlSession = sqlSessionFactory.openSession(true);
    
                //4.获取StudentMapper接口的实现类对象
                StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); // StudentMapper mapper = new StudentMapperImpl();
    
                //5.通过实现类对象调用方法,接收结果
                list = mapper.selectCondition ( stu );
    
            } catch (Exception e) {
    
            } finally {
                //6.释放资源
                if(sqlSession != null) {
                    sqlSession.close();
                }
                if(is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
    
            //7.返回结果
            return list;
        }
    
    
        //根据多个id查询
        @Override
        public List<Student> selectByIds(List<String> ids) {
            List<Student> list = null;
            SqlSession sqlSession = null;
            InputStream is = null;
            try{
                //1.加载核心配置文件
                is = Resources.getResourceAsStream("MyBatisConfig.xml");
    
                //2.获取SqlSession工厂对象
                SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
    
                //3.通过工厂对象获取SqlSession对象
                sqlSession = sqlSessionFactory.openSession(true);
    
                //4.获取StudentMapper接口的实现类对象
                StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); // StudentMapper mapper = new StudentMapperImpl();
    
                //5.通过实现类对象调用方法,接收结果
                list = mapper.selectByIds ( ids );
    
            } catch (Exception e) {
    
            } finally {
                //6.释放资源
                if(sqlSession != null) {
                    sqlSession.close();
                }
                if(is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
    
            //7.返回结果
            return list;
        }
    
    
    
    
    }
    

  • 编写StudentMapper.xml文件
  • <?xml version="1.0" encoding="UTF-8" ?>
    <!--MyBatis的DTD约束-->
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <!--
        mapper:核心根标签
        namespace属性:名称空间
    -->
    <mapper namespace="com.limei.mapper.StudentMapper">
        <!--
            select:查询功能的标签
            id属性:唯一标识
            resultType属性:指定结果映射对象类型
            parameterType属性:指定参数映射对象类型
        -->
        <select id="selectAll" resultType="student">
            SELECT * FROM student
        </select>
    
        <select id="selectById" resultType="student" parameterType="String">
            SELECT * FROM student WHERE id = #{id}
        </select>
    
        <insert id="insert" parameterType="student">
            INSERT INTO student VALUES (#{id},#{name},#{birthday},#{address})
        </insert>
    
        <update id="update" parameterType="student">
            UPDATE student SET name = #{name},birthday = #{birthday},address=#{address} WHERE id = #{id}
        </update>
    
        <delete id="delete" parameterType="String">
            DELETE FROM student WHERE id = #{id}
        </delete>
    
        <!--
            <where>:条件标签。如果有动态条件,则使用该标签代替 where 关键字。
            <if>:条件判断标签。
                <if test=“条件判断”>
                查询条件拼接
            </if>
        -->
    
        <select id="selectCondition" resultType="student" parameterType="student">
            SELECT * FROM student
            <where>
                <if test="id != null">
                    id = #{id}
                </if>
                <if test="name != null">
                    AND name = #{name}
                </if>
    
            </where>
        </select>
    
        <!--
               属性
                    collection:参数容器类型, (list-集合, array-数组)。
                    open:开始的 SQL 语句。
                    close:结束的 SQL 语句。
                    item:参数变量名。
                    separator:分隔符。
           -->
        <select id="selectByIds" resultType="student" parameterType="list">
            SELECT * FROM student
            <where>
                <foreach collection="list" open="id IN (" close=")" item="id" separator=",">
                    #{id}
                </foreach>
            </where>
        </select>
    
    
    </mapper>

  • 总结
  • 此目录缺失的文件去Mybatis的基本使用中去寻找

    接口代理方式可以让我们只编写接口即可,而实现类对象由 MyBatis 生成。

    实现规则 :

    1. 映射配置文件中的名称空间必须和 Dao 层接口的全类名相同。
    2. 映射配置文件中的增删改查标签的 id 属性必须和 Dao 层接口的方法名相同。
    3. 映射配置文件中的增删改查标签的 parameterType 属性必须和 Dao 层接口方法的参数相同。
    4. 映射配置文件中的增删改查标签的 resultType 属性必须和 Dao 层接口方法的返回值相同。 
    5. 获取动态代理对象 SqlSession 功能类中的 getMapper() 方法。
    0

    评论 (0)

    取消