mybatis-day02笔记

2023-01-10 15:29:11

1.Mybatis的Dao层实现

1.1 传统开发方式

1.1.1编写UserDao接口
public interface UserDao {
    List<User> findAll() throws IOException;
}
1.1.2.编写UserDaoImpl实现
public class UserDaoImpl implements UserDao {
    public List<User> findAll() throws IOException {
        InputStream resourceAsStream = 
                    Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new 
                    SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        List<User> userList = sqlSession.selectList("userMapper.findAll");
        sqlSession.close();
        return userList;
    }
}
1.1.3 测试传统方式
@Test
public void testTraditionDao() throws IOException {
    UserDao userDao = new UserDaoImpl();
    List<User> all = userDao.findAll();
    System.out.println(all);
}

传统方式的缺点
1) 每调用一次方法都要加载一次配置文件
2) dao 层代码编写复杂,大量冗余代码
针对上述缺陷,mybatis 底层使用动态代理+反射的技术提供了一些额外的功能,能够让我们的Dao 层代码变得更加简单

1.2 代理开发方式

1.2.1 代理开发方式介绍

采用 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的类型相同

补充:

0) 方法名称不能重复(不允许重载)

1) 同一个配置文件不能加载两次

2) 根据类名加载配置

要求 Mapper.java 和 Mapper.xml 名称应该一致,包名应该一致

 <!--加载映射文件-->
<mappers>
    <!--<mapper resource="com/itheima/mapper/UserMapper.xml"></mapper>-->
    <!--<mapper class="com.itheima.dao.UserMapper"/>-->
    <package name="com.itheima.dao"/> 当有多个的时候,可以使用这种方式简化配置
</mappers>

为什么?

1) 如果 namespace与mapper接口的全限定名不同,

或者Mapper接口方法名和Mapper.xml中定义的每个statement的id不同

结果: mybatis 找不到 那条sql 要执行

2) 如果请求参数类型不同,无法封装请求参数

3) 如果 返回参数不同,mybatis 不知道要怎么封装参数

1.2.2 编写UserMapper接口

在这里插入图片描述

1.2.3测试代理方式
@Test
public void testProxyDao() throws IOException {
    InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //获得MyBatis框架生成的UserMapper接口的实现类
  UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    User user = userMapper.findById(1);
    System.out.println(user);
    sqlSession.close();
}

1.3 知识小结

MyBatis的Dao层实现的两种方式:

手动对Dao进行实现:传统开发方式

代理方式对Dao进行实现:

UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

1.4 为什么叫代理模式? 即存在的问题

mybatis底层使用的是代理模式

问题:

虽然我们dao 层代码简单了,但是我们的service 层代码变得复杂了?

后续和spring 整合,时会彻底解决

2.MyBatis映射文件深入

2.1 动态sql语句

2.1.1动态sql语句概述

Mybatis 的映射文件中,前面我们的 SQL 都是比较简单的,有些时候业务逻辑复杂时,我们的 SQL是动态变化的,此时在前面的学习中我们的 SQL 就不能满足要求了。

参考的官方文档,描述如下:

在这里插入图片描述

2.1.2动态 SQL 之<if>

我们根据实体类的不同取值,使用不同的 SQL语句来进行查询。比如在 id如果不为空时可以根据id查询,如果username 不同空时还要加入用户名作为条件。这种情况在我们的多条件组合查询中经常会碰到。

<select id="findByCondition" parameterType="user" resultType="user">
    select * from User
    <where>
        <if test="id!=0">
            and id=#{id}
        </if>
        <if test="username!=null">
            and username=#{username}
        </if>
         <if test="username!=null or  id!=0"  > 多判断条件
               and username=#{username}
         </if>
    </where>
</select>

当查询条件id和username都存在时,控制台打印的sql语句如下:

     … … …
     //获得MyBatis框架生成的UserMapper接口的实现类
  UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    User condition = new User();
    condition.setId(1);
    condition.setUsername("lucy");
    User user = userMapper.findByCondition(condition);
    … … …

在这里插入图片描述

当查询条件只有id存在时,控制台打印的sql语句如下:

 … … …
 //获得MyBatis框架生成的UserMapper接口的实现类
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User condition = new User();
condition.setId(1);
User user = userMapper.findByCondition(condition);
… … …

在这里插入图片描述

  1. where 标签会自动去除第一个and

  2. where 标签不会帮助我们添加and

2.1.3 动态 SQL 之<foreach>

循环执行sql的拼接操作,例如:SELECT * FROM USER WHERE id IN (1,2,5)。

<select id="findByIds" parameterType="list" resultType="user">
   select * from User
   <where>
       <foreach collection="list" open="id in(" close=")" item="id" separator=",">
           #{id}
       </foreach>
   </where>
</select>
open: 开始标签
close: 结束标签
 separator: 分隔符
collection: 被遍历的集合,默认必须是 collection 或者 list 
   	可以使用 "findByIds(@Param("ids") List<Integer> ids);" 自定义名称

测试代码片段如下:

 … … …
 //获得MyBatis框架生成的UserMapper接口的实现类
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
int[] ids = new int[]{2,5};
List<User> userList = userMapper.findByIds(ids);
System.out.println(userList);
… … …

在这里插入图片描述

foreach标签的属性含义如下:

标签用于遍历集合,它的属性:

•collection:代表要遍历的集合元素,注意编写时不要写#{}

•open:代表语句的开始部分

•close:代表结束部分

•item:代表遍历集合的每个元素,生成的变量名(局部变量)

•sperator:代表分隔符

2.2 SQL片段抽取

Sql 中可将重复的 sql 提取出来,使用时用 include 引用即可,最终达到 sql 重用的目的

<!--抽取sql片段简化编写-->
<sql id="selectUser" select * from User</sql>
<select id="findById" parameterType="int" resultType="user">
    <include refid="selectUser"></include> where id=#{id}
</select>
<select id="findByIds" parameterType="list" resultType="user">
    <include refid="selectUser"></include>
    <where>
        <foreach collection="array" open="id in(" close=")" item="id" separator=",">
            #{id}
        </foreach>
    </where>
</select>
补充: 不提倡使用select * 因为后续数据库发生变更 可能会导致字段不一致而有问题

2.3 知识小结

MyBatis映射文件配置:

<select>:查询
<insert>:插入

:

:修改

:删除

:where条件

:if判断

:循环

:sql片段抽取

2.4 补充 @Param

public List<User> findByUserNameAndPassword(@Param("username") String username ,@Param("password")String password);

  <select id="findByUserNameAndPassword" resultType="user">
         select * from user where  password=#{password} and username=#{username}
    </select>

3. MyBatis核心配置文件深入

3.1typeHandlers标签

无论是 MyBatis 在预处理语句(PreparedStatement)中设置一个参数时,还是从结果集中取出一个值时, 都会用类型处理器将获取的值以合适的方式转换成 Java 类型。下表描述了一些默认的类型处理器(截取部分)。

在这里插入图片描述

你可以重写类型处理器或创建你自己的类型处理器来处理不支持的或非标准的类型。具体做法为:实现 org.apache.ibatis.type.TypeHandler 接口, 或继承一个很便利的类 org.apache.ibatis.type.BaseTypeHandler, 然后可以选择性地将它映射到一个JDBC类型。例如需求:一个Java中的Date数据类型,我想将之存到数据库的时候存成一个1970年至今的毫秒数,取出来时转换成java的Date,即java的Date与数据库的varchar毫秒值之间转换。

开发步骤:

①定义转换类继承类BaseTypeHandler

②覆盖4个未实现的方法,其中setNonNullParameter为java程序设置数据到数据库的回调方法,getNullableResult为查询时 mysql的字符串类型转换成 java的Type类型的方法

③在MyBatis核心配置文件中进行注册

测试转换是否正确

// 1)此处的泛型指的是 java 类型
public class DateTypeHandler extends BaseTypeHandler<Date> {
    //将java类型 转换成 数据库需要的类型

    /**
     *
     * @param preparedStatement
     * @param i  ? 索引角标位置
     * @param date
     * @param jdbcType
     * @throws SQLException
     */
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Date date, JdbcType jdbcType) throws SQLException {
        long time = date.getTime();
        preparedStatement.setLong(i,time);
    }

    //将数据库中类型 转换成java类型
    //String参数  要转换的字段名称
    //ResultSet 查询出的结果集
    //
    public Date getNullableResult(ResultSet resultSet, String cloumnNname) throws SQLException {
        //获得结果集中需要的数据(long) 转换成Date类型 返回
        long aLong = resultSet.getLong(cloumnNname);
        Date date = new Date(aLong);
        return date;
    }

    //将数据库中类型 转换成java类型
    public Date getNullableResult(ResultSet resultSet, int index) throws SQLException {
        long aLong = resultSet.getLong(index);
        Date date = new Date(aLong);
        return date;
    }

    //将数据库中类型 转换成java类型
    public Date getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        long aLong = callableStatement.getLong(i);
        Date date = new Date(aLong);
        return date;
    }
    public static void main(String[] args) throws Exception{
        Connection connection = null;
        PreparedStatement preparedStatement = connection.prepareStatement("select id,username,password,birthday from user");
        ResultSet resultSet = preparedStatement.executeQuery();
        
        while (resultSet.next()){
            resultSet.getLong(3);
            resultSet.getLong("birthday");
        }
    }
<!--注册类型自定义转换器-->
<typeHandlers>
    <typeHandler handler="com.itheima.typeHandlers.MyDateTypeHandler"></typeHandler>
</typeHandlers>

测试添加操作:

user.setBirthday(new Date());
userMapper.add2(user);

数据库数据:

在这里插入图片描述

测试查询操作:


在这里插入图片描述

3.2 plugins标签

MyBatis可以使用第三方的插件来对功能进行扩展,分页助手PageHelper是将分页的复杂操作进行封装,使用简单的方式即可获得分页的相关数据

开发步骤:

①导入通用PageHelper的坐标

②在mybatis核心配置文件中配置PageHelper插件

③测试分页数据获取

①导入通用PageHelper坐标
<!-- 分页助手 -->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>3.7.5</version>
</dependency>
<dependency>
    <groupId>com.github.jsqlparser</groupId>
    <artifactId>jsqlparser</artifactId>
    <version>0.9.1</version>
</dependency>

②在mybatis核心配置文件中配置PageHelper插件
<!-- 注意:分页助手的插件  配置在通用馆mapper之前 -->
<plugin interceptor="com.github.pagehelper.PageHelper">
    <!-- 指定方言 -->
    <property name="dialect" value="mysql"/>
</plugin>
③测试分页代码实现
@Test
public void testPageHelper(){
    //设置分页参数
    PageHelper.startPage(1,2);

    List<User> select = userMapper2.select(null);
// Page<User> userList = (Page<User>)mapper.findAll();
    for(User user : select){
        System.out.println(user);
    }
}
---------
 PageHelper.startPage(1,3);  // 当前线程全局变量 ,紧跟着的查询第一次使用后失效

      

获得分页相关的其他参数

//其他分页的数据
PageInfo<User> pageInfo = new PageInfo<User>(select);
System.out.println("总条数:"+pageInfo.getTotal());
System.out.println("总页数:"+pageInfo.getPages());
System.out.println("当前页:"+pageInfo.getPageNum());
System.out.println("每页显示长度:"+pageInfo.getPageSize());
System.out.println("是否第一页:"+pageInfo.isIsFirstPage());
System.out.println("是否最后一页:"+pageInfo.isIsLastPage());

3.3 知识小结

MyBatis核心配置文件常用标签:

1、properties标签:该标签可以加载外部的properties文件

2、typeAliases标签:设置类型别名

3、environments标签:数据源环境配置标签

4、typeHandlers标签:配置自定义类型处理器

5、plugins标签:配置MyBatis的插件

补充ResultMap

  1. 当数据库字段类型和java POJO 类不匹配时
public class User {

    private int id;
    //private String userName;// linux 下区分大小写,windows 环境下不区分大小写
     private String name;
    private String password;
    private Date birthday;
<?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="com.itheima.mapper.UserMapper">

    <!--resultMap 标签用来处理映射字段不一致的问题
       1)id="userMap" 表示 给  <resultMap 标签起一个名字
       2)type="user": 返回类型,
===========================
        <id></id> 用于主键字段
        <result>用于非主键字段
        property="id" 表示java 实体类属性字段
         column="id"  表示 数据库字段
    -->

    <resultMap id="userMap" type="user">
        <id property="id" column="id"></id>
        <result property="name" column="username"></result>
        <result property="birthday" column="birthday"></result>
    </resultMap>


    <select id="findAll" resultMap="userMap" >
        select * from user
    </select>
</mapper>

补充 逆向工程

简介

mybatis 官方提供了一种逆袭自动生成dao 层所需的所有代码的工具,使用该工具我们将会自动生成dao 层所需的所有代码,后续将极大加快我们开发的速度

步骤

  1. 修改 generatorConfig.xml
1)修改数据库连接
2)修改生成文件的包名和路径

2)双击执行 执行脚本 autoscript.bat

注意:
	每次执行时请先删除原来的文件,否则生成的xml 文件会重复
  1. 生成文件说明

  2. 数据库的每个表会生成

UserMapp.java 接口

UserMapp.xml 配置文件

User.java 实体类
UserExample.java 查询工具类
  1. 查询工具类使用方法
//1) 获取接口
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
// 2)通过构造工具类
UserExample util = new UserExample(); 
// selet * from user where 1=1 and  id like and name ='lucy' 
// 3)构造查询条件
   util.createCriteria().andIdEqualTo(1).andUserNameEqualTo("lucy");
// 4) 执行查询
        List<User> list = mapper.selectByExample(util);
  • 作者:自由的信仰
  • 原文链接:https://blog.csdn.net/weixin_45185764/article/details/100935463
    更新时间:2023-01-10 15:29:11