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 测试传统方式

public class ServiceDemo {
public static void main(String[] args) throws IOException { //创建dao层对象,手动编写的
UserDao userDao=new UserDaoImpl();
List<User> all=userDao.findAll();
System.out.println(all);
} }

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

1.2.2 编写UserMapper接口

1.2.3测试代理方式

    <!--根据id进行查询-->
<select id="findById" parameterType="int" resultType="user">
select * from user where id=#{id}
</select>
public interface UserMapper {

    public List<User> findAll() throws IOException;

    public User findById(int id);

}
@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);

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>
</where>
</select>
package com.itheima.mapper;

import com.itheima.domain.User;

import java.util.List;

public interface UserMapper {

    public List<User> findByCondition(User user);

    public List<User> findByIds(List<Integer> ids);

}

当查询条件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);
… … …

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="array" open="id in(" close=")" item="id" separator=",">
#{id}
</foreach>
</where>
</select>

测试代码片段如下:

 … … …
//获得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标签的属性含义如下:

<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>

2.3 知识小结

<select>:查询

<insert>:插入

<update>:修改

<delete>:删除

<where>:where条件

<if>:if判断

<foreach>:循环

<sql>:sql片段抽取

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<T>

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

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

4、测试转换是否正确

<?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"> <insert id="save" parameterType="user">
insert into user values(#{id},#{username},#{password},#{birthday})
</insert> <select id="findById" parameterType="int" resultType="user">
select * from user where id=#{id}
</select> <select id="findAll" resultType="user">
select * from user
</select> </mapper>

package com.itheima.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType; import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date; public class DateTypeHandler extends BaseTypeHandler<Date> {
//将java类型 转换成 数据库需要的类型i是参数位置
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 s) throws SQLException {
//获得结果集中需要的数据(long) 转换成Date类型 返回
long aLong = resultSet.getLong(s);
Date date = new Date(aLong);
return date;
} //将数据库中类型 转换成java类型
public Date getNullableResult(ResultSet resultSet, int i) throws SQLException {
long aLong = resultSet.getLong(i);
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 class MyDateTypeHandler extends BaseTypeHandler<Date> {
public void setNonNullParameter(PreparedStatement preparedStatement, int i, Date date, JdbcType type) {
preparedStatement.setString(i,date.getTime()+"");
}
public Date getNullableResult(ResultSet resultSet, String s) throws SQLException {
return new Date(resultSet.getLong(s));
}
public Date getNullableResult(ResultSet resultSet, int i) throws SQLException {
return new Date(resultSet.getLong(i));
}
public Date getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
return callableStatement.getDate(i);
}
}

<!--注册类型自定义转换器-->
<typeHandlers>
<typeHandler handler="com.itheima.typeHandlers.MyDateTypeHandler"></typeHandler>
</typeHandlers>

测试添加操作:

数据库数据:

测试查询操作:

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 = mapper.findAll();
for(User user : userList){
System.out.println(user);
}
}

获得分页相关的其他参数

//其他分页的数据
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的插件

Mybatis的Dao层实现原理的更多相关文章

  1. 基于Mybatis的Dao层的开发

    基于Mybatis的Dao层开发 SqlSessionFactoryBuilder用于创建SqlSessionFacoty,SqlSessionFacoty一旦创建完成就不需要SqlSessionFa ...

  2. MyBatis开发Dao层的两种方式(原始Dao层开发)

    本文将介绍使用框架mybatis开发原始Dao层来对一个对数据库进行增删改查的案例. Mapper动态代理开发Dao层请阅读我的下一篇博客:MyBatis开发Dao层的两种方式(Mapper动态代理方 ...

  3. MyBatis开发Dao层的两种方式(Mapper动态代理方式)

    MyBatis开发原始Dao层请阅读我的上一篇博客:MyBatis开发Dao层的两种方式(原始Dao层开发) 接上一篇博客继续介绍MyBatis开发Dao层的第二种方式:Mapper动态代理方式 Ma ...

  4. 基于Mybatis的Dao层开发

    转自:https://www.cnblogs.com/rodge-run/p/6528398.html 基于Mybatis的Dao层开发 SqlSessionFactoryBuilder用于创建 Sq ...

  5. Mybatis的dao层实现 接口代理方式实现规范+plugins-PageHelper

    Mybatis的dao层实现 接口代理方式实现规范 Mapper接口实现时的相关规范: Mapper接口开发只需要程序员编写Mapper接口而不用具体实现其代码(相当于我们写的Imp实现类) Mapp ...

  6. MyBatis的Dao层注入SqlSession

    有点坑爹,以前没用过Mybatis,最近才用,而且一直用Mybatis推荐的接口映射的方式,但是今天有人告诉我接口方式用得少,大多还是采用从配置文件里面读sql的方式,当然接口也是类似的,都是利用ma ...

  7. IDEA项目搭建四——使用Mybatis实现Dao层

    一.引入mybatis及mysql的jar包 可以从阿里云上面查找版本,db操作放在dao层所以打开该层的pom.xml文件,找到<dependencies>节点增加两个引入 <de ...

  8. (五)mybatis开发dao层

    目录 SqlSession 是线程不安全的 原始 dao 开发方法 Mapper 代理方法 关于代理对象 SqlSession 是线程不安全的 SqlSession 是 线程不安全 的: 对于它,我们 ...

  9. spring boot 集成 mybatis 单元测试Dao层 控制台报错:org.apache.ibatis.binding.BindingException: Invalid bound statement (not found):

    最近帮同学做毕业程序,采用后端spring boot + mybatis + H2,将框架搭好进行各层的单元测试时,在dao层就出现了错,如图 于是在网上找各种资料,有的说是xml文件和接口没有一一对 ...

随机推荐

  1. PBN进场程序保护区图例分析

      疫情仍在持续,除了待家里不给祖国添乱之外,过去没有时间去完成的事情,现在可以静下心来认真面对,充实过好每一天. 今天想跟大家聊一下ICAO 8168第二卷PBN进场程序的图例. 就是下面这张图: ...

  2. DOM的理解

    https://www.cnblogs.com/djtang/p/11538420.html  dom的理解 https://blog.csdn.net/jiuqiyuliang/article/de ...

  3. Reactive Spring实战 -- 理解Reactor的设计与实现

    Reactor是Spring提供的非阻塞式响应式编程框架,实现了Reactive Streams规范. 它提供了可组合的异步序列API,例如Flux(用于[N]个元素)和Mono(用于[0 | 1]个 ...

  4. 用 hexo 快速搭建博客

    如何做到一毛不拔的搭建网站 以下操作全程使用管理员权限,因为我不清楚哪里会出现 permission denied 1.下载 nodejs 对应 windows 用户,下载对应的 ".msi ...

  5. `vi`——终端中的编辑器

    `vi`--终端中的编辑器 目标* `vi` 简介* 打开和新建文件* 三种工作模式* 常用命令* 分屏命令* 常用命令速查图 01. `vi` 简介 1.1 学习 `vi` 的目的 * 在工作中,要 ...

  6. salesforce零基础学习(一百零一)如何了解你的代码得运行上下文

    本篇参考:https://developer.salesforce.com/docs/atlas.en-us.228.0.apexcode.meta/apexcode/apex_enum_System ...

  7. MyBatis(一):JDBC使用存在的问题

    JDBC使用步骤: a:加载 JDBC 驱动程序 b:创建数据库的连接对象Connection c:根据链接获取Statement d:拼接SQL语句及设置参数 e:执行SQL并获取结果集 f:关闭使 ...

  8. 在ASP.NET Core中用HttpClient(二)——发送POST, PUT和DELETE请求

    在上一篇文章中,我们已经学习了如何在ASP.NET Core中使用HttpClient从Web API获取数据.此外,我们还学习了如何使用GetAsync方法和HttpRequestMessage类发 ...

  9. 03-Spring默认标签解析

    默认标签的解析 上一篇分析了整体的 xml 文件解析,形成 BeanDefinition 并注册到 IOC 容器中,但并没有详细的说明具体的解析,这一篇主要说一下 默认标签的解析,下一篇主要说自定义标 ...

  10. get和post的区别主要有以下几方面

    1.url可见性: get,参数url可见: post,url参数不可见 2.数据传输上: get,通过拼接url进行传递参数: post,通过body体传输参数 3.缓存性: get请求是可以缓存的 ...