(二)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;
    }
}
### 关于 MyBatis 的全面学习笔记 #### 一、MyBatis 基础概念 MyBatis 是一款优秀的持久框架,它支持定制化 SQL、存储过程以及高级映射。通过 MyBatis 创建 DAO 接口的实现类对象完成对 SQL 语句的执行[^1]。 #### 、环境搭建与配置 为了使 MyBatis 正常工作,在项目中需引入必要的依赖并配置数据库连接信息。通常这些信息会保存在一个名为 `jdbc.properties` 文件内,如下所示: ```properties jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test jdbc.username=root jdbc.password=root ``` 此部分配置用于指定 JDBC 驱动程序名称、URL 地址及登录凭证等必要参数[^2]。 #### 三、数据操作流程概述 当利用 MyBatis 进行 CRUD 操作时,实际的数据源可以来自多种途径之一——例如从关系型数据库获取记录集作为 Java 对象列表 (`List<T>`) 来处理。对于导出至 Excel 文档的需求,则可通过编写工具方法接收上述提到的对象集合及其他元数据(如表头定义),最终返回文件流供下载使用[^3]。 #### 四、动态 SQL 技术详解 MyBatis 提供了一套强大的动态 SQL 功能,允许开发者依据业务逻辑灵活构建查询条件。这项特性极大地简化了复杂查询场景下的编码难度,并提高了代码可读性和维护效率[^4]。 --- 下面是一些具体的实践建议帮助更好地掌握 MyBatis: - **深入理解 XML 映射文件**: 学习如何声明命名空间(namespace),编写 Select/Insert/Update/Delete 节点及其属性设置; - **探索注解方式开发 Mapper Interface**: 尝试不借助 XML 描述而仅依靠接口上的 @Select/@Insert 等标注来定义 SQL 片段; - **熟悉缓存机制**: 掌握一级缓存(默认开启)级缓存的工作原理及时机控制策略; - **研究插件扩展能力**: 利用拦截器(interceptor)自定义行为增强原有功能模块; - **练习分页查询优化技巧**: 结合具体应用场景评估不同方案性能表现差异; 最后提醒一点,随着版本迭代更新速度加快,官方文档始终是最权威可靠的学习资源,请务必定期查阅最新发布的内容保持知识体系与时俱进。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值