(二)MyBatis学习笔记——实现Dao层的不同方式

一、传统方式实现

先导入MyBatis的jar包。项目依旧使用控制层——>业务层——>持久层的结构,使用MyBatis进行数据库CRUD。整体结构如下:
在这里插入图片描述

1.MyBatis配置文件

MyBatisConfig.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>
    <!--  引入数据库连接的配置文件  -->
    <properties resource="jdbc.properties"/>

    <typeAliases>
        <typeAlias type="com.example.bean.Student" alias="student"/>
        <!-- 给包下所有的类起别名,为文件名 -->
        <package name="com.example.bean"/>
    </typeAliases>
    
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="StudentMapper.xml"/>
    </mappers>
</configuration>

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">
<mapper namespace="StudentMapper">
    <select id="selectAll" resultType="student">
        SELECT * FROM student
    </select>

    <select id="selectById" resultType="student" parameterType="int">
        SELECT * FROM student WHERE sid=#{sid}
    </select>

    <!--  从Student类中获取id name age  -->
    <insert id="insert" parameterType="student">
        INSERT INTO student VALUES(#{sid}, #{name}, #{age}, #{birthday});
    </insert>

    <update id="update" parameterType="student">
        UPDATE student SET name=#{name}, age=#{age}, birthday=#{birthday} WHERE sid=#{sid}
    </update>

    <delete id="delete" parameterType="java.lang.Integer">
        DELETE FROM student WHERE sid=#{sid};
    </delete>
</mapper>

2.持久层(Dao层或Mapper层)

定义接口:

package com.example.mapper;

import com.example.bean.Student;

import java.util.List;

//持久层接口
public interface StudentMapper {
    //查询全部
    public abstract List<Student> selectAll();

    //根据id查询
    public abstract Student selectById(Integer id);

    //新增数据
    public abstract Integer insert(Student student);

    //修改数据
    public abstract Integer update(Student student);

    //根据id删除数据
    public abstract Integer delete(Integer id);
}

接口实现:

public class StudentMapperImpl implements StudentMapper {
    //查询全部
    @Override
    public List<Student> selectAll() {
        InputStream is = null;
        SqlSession sqlSession = null;
        List<Student> list = null;
        try {
            //1.加载核心配置文件
            is = Resources.getResourceAsStream("MybatisConfig.xml");
            //2.获取SqlSession工厂对象
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            //3.通过工厂对象获取SqlSession对象
            sqlSession = sqlSessionFactory.openSession(true);//自动提交事务
            //4.执行映射配置文件中的SQL语句,并接收结果
            list = sqlSession.selectList("StudentMapper.selectAll");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //5.释放资源
            if(sqlSession != null)
                sqlSession.close();
            if(is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return list;
    }
    //根据Id查询
    @Override
    public Student selectById(Integer id) {
        InputStream is = null;
        SqlSession sqlSession = null;
        Student stu = null;
        try {
            //1.加载核心配置文件
            is = Resources.getResourceAsStream("MybatisConfig.xml");
            //2.获取SqlSession工厂对象
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            //3.通过工厂对象获取SqlSession对象
            sqlSession = sqlSessionFactory.openSession(true);//自动提交事务
            //4.执行映射配置文件中的SQL语句,并接收结果
            stu = sqlSession.selectOne("StudentMapper.selectById", id);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //5.释放资源
            if(sqlSession != null)
                sqlSession.close();
            if(is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return stu;
    }

    //插入一条数据
    @Override
    public Integer insert(Student student) {
        InputStream is = null;
        SqlSession sqlSession = null;
        Integer res = 0;
        try {
            //1.加载核心配置文件
            is = Resources.getResourceAsStream("MybatisConfig.xml");
            //2.获取SqlSession工厂对象
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            //3.通过工厂对象获取SqlSession对象
            sqlSession = sqlSessionFactory.openSession(true);//自动提交事务
            //4.执行映射配置文件中的SQL语句,并接收结果
            res = sqlSession.insert("StudentMapper.insert", student);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //5.释放资源
            if(sqlSession != null)
                sqlSession.close();
            if(is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return res;
    }

    //修改一条数据
    @Override
    public Integer update(Student student) {
        InputStream is = null;
        SqlSession sqlSession = null;
        Integer res = 0;
        try {
            //1.加载核心配置文件
            is = Resources.getResourceAsStream("MybatisConfig.xml");
            //2.获取SqlSession工厂对象
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            //3.通过工厂对象获取SqlSession对象
            sqlSession = sqlSessionFactory.openSession(true);//自动提交事务
            //4.执行映射配置文件中的SQL语句,并接收结果
            res = sqlSession.update("StudentMapper.update", student);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //5.释放资源
            if(sqlSession != null)
                sqlSession.close();
            if(is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return res;
    }

    @Override
    public Integer delete(Integer id) {
        InputStream is = null;
        SqlSession sqlSession = null;
        Integer res = 0;
        try {
            //1.加载核心配置文件
            is = Resources.getResourceAsStream("MybatisConfig.xml");
            //2.获取SqlSession工厂对象
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            //3.通过工厂对象获取SqlSession对象
            sqlSession = sqlSessionFactory.openSession(true);//自动提交事务
            //4.执行映射配置文件中的SQL语句,并接收结果
            res = sqlSession.delete("StudentMapper.delete", id);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //5.释放资源
            if(sqlSession != null)
                sqlSession.close();
            if(is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return res;
    }
}

3.业务层(Service层)

定义接口:

package com.example.service;

import com.example.bean.Student;

import java.util.List;
//业务层接口
public interface StudentService {
        //查询全部
        public abstract List<Student> selectAll();

        //根据id查询
        public abstract Student selectById(Integer id);

        //新增数据
        public abstract Integer insert(Student student);

        //修改数据
        public abstract Integer update(Student student);

        //根据id删除数据
        public abstract Integer delete(Integer id);

}

实现接口:

public class StudentServiceImpl implements StudentService {
    private StudentMapper mapper = new StudentMapperImpl();//创建持久层对象

    @Override
    public List<Student> selectAll() {
        return mapper.selectAll();
    }

    @Override
    public Student selectById(Integer id) {
        return mapper.selectById(id);
    }

    @Override
    public Integer insert(Student student) {
        return mapper.insert(student);
    }

    @Override
    public Integer update(Student student) {
        return mapper.update(student);
    }

    @Override
    public Integer delete(Integer id) {
        return mapper.delete(id);
    }
}

4.控制层(controller层)

public class StudentController {
    //创建业务层对象
    private StudentService service = new StudentServiceImpl();
    //日期格式化
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    //查询全部功能测试
    @Test
    public void selectAll(){
        List<Student> students = service.selectAll();
        for (Student stu : students) System.out.println(stu);
    }
    //通过id查询
    @Test
    public void selectById(){
        Student student = service.selectById(3);
        System.out.println(student);
    }

    //新增功能
    @Test
    public void insert() throws ParseException {
        Student student = new Student(5,"小A",35, dateFormat.parse("2010-10-10"));
        Integer res = service.insert(student);
        System.out.println(res);
    }

    //修改功能
    @Test
    public void update() throws ParseException {
        Student student = new Student(5,"大A",33,dateFormat.parse("2000-01-01"));
        Integer res = service.update(student);
        System.out.println(res);
    }

    //删除功能
    @Test
    public void delete(){
        Integer res = service.delete(5);
        System.out.println(res);
    }
}

二、接口代理方式实现

分析:

  • 接口代理方式的好处?
    • 使用上面这种传统的方式实现Dao层,既要写接口,还要写实现类。使用MyBatis可以省略编写Dao层接口的实现类的步骤,有MyBatis根据定义好的接口,创建该接口的动态代理对象。
  • 动态代理对象如何生成?
    • 通过动态代理模式,持久层只需写一个接口,不需要实现类,通过getMapper()方法最终获取到org.apache.ibatis.binding.MapperProxy代理对象,然后执行功能。此代理对象时MyBatis使用JDK的动态代理技术自动生成的代理实现类对象。由此,可以进行数据持久化操作
  • 方法如何执行?
    • 动态代理实现类对象在执行方法时最终调用了mapperMethod.execute()方法,此方法中通过switch语句根据操作类型判断是CRUD中的哪个操作,最终使用了MyBatis最原生的SqlSession方式来执行CRUD。
  • 使用接口代理方式的要求:
    • 映射配置文件中的名称空间须与Dao层接口的详细目录下的类名相同。<mapper namespace="com.example.mapper.StudentMapper">
    • 映射配置文件中的增删改查标签的id属性须和持久层接口的方法名相同。
    • 映射配置文件中的增删改查标签的parameterType属性须与持久层接口方法的参数相同。
    • 映射配置文件中的增删改查标签的resultType属性须与持久层接口方法的返回值相同。

1.新建项目

和传统Dao实现方式基本相同,只需要修改映射配置文件中的名称空间等上面四步即可。现在不再需要StudentMapper的实现类,其方法实现将转移到StudentServiceImpl中进行实现。项目架构如下:
在这里插入图片描述

2.业务层代码编写

StudentServiceImpl.class

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");
            //2.获取到SqlSession工厂对象
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            //3.通过工厂对象获取到SqlSession对象
            sqlSession = sqlSessionFactory.openSession(true);
            //4.获取StudentMapper接口的实现类对象
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);//等同于:StudentMapper studentMapper = new StudentMapperImpl();
            //5.通过实现类对象调用方法,接收结果
            list = studentMapper.selectAll();
        } catch (IOException e) {
            e.printStackTrace();
        }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(Integer id) {
        Student student = 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 studentMapper = sqlSession.getMapper(StudentMapper.class);//等同于:StudentMapper studentMapper = new StudentMapperImpl();
            //5.通过实现类对象调用方法,接收结果
            student = studentMapper.selectById(id);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //6.释放资源
            if(sqlSession != null) {
                sqlSession.close();
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //7.返回结果
        return student;
    }

    @Override
    public Integer insert(Student student) {
        Integer res = 0;
        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 studentMapper = sqlSession.getMapper(StudentMapper.class);//等同于:StudentMapper studentMapper = new StudentMapperImpl();
            //5.通过实现类对象调用方法,接收结果
            res = studentMapper.insert(student);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //6.释放资源
            if(sqlSession != null) {
                sqlSession.close();
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //7.返回结果
        return res;
    }

    @Override
    public Integer update(Student student) {
        Integer res = 0;
        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 studentMapper = sqlSession.getMapper(StudentMapper.class);//等同于:StudentMapper studentMapper = new StudentMapperImpl();
            //5.通过实现类对象调用方法,接收结果
            res = studentMapper.update(student);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //6.释放资源
            if(sqlSession != null) {
                sqlSession.close();
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //7.返回结果
        return res;
    }

    @Override
    public Integer delete(Integer id) {
        Integer res = 0;
        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 studentMapper = sqlSession.getMapper(StudentMapper.class);//等同于:StudentMapper studentMapper = new StudentMapperImpl();
            //5.通过实现类对象调用方法,接收结果
            res = studentMapper.delete(id);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //6.释放资源
            if(sqlSession != null) {
                sqlSession.close();
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //7.返回结果
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值