Mybatis框架入门学习笔记(二)
一、Mybatis的Dao层实现
(一)传统开发方式
1、编写UserDao接口
public interface UserDao {
List<User> findAll() throws IOException;
}
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;
}
}
3、测试传统方式
@Test
public void testTraditionDao() throws IOException {
UserDao userDao = new UserDaoImpl();
List<User> all = userDao.findAll();
System.out.println(all);
}
(二)代理开发方式
1、代理开发方式介绍
采用 Mybatis 的代理开发方式实现 DAO 层的开发,这种方式是我们后面进入企业的主流。
Mapper 接口开发方法 只需要程序员编写Mapper 接口(相当于Dao 接口),由Mybatis 框架根据接口定义 创建接口的 动态代理对象,代理对象的方法体 同上边Dao接口实现类方法。
Mapper 接口开发需要遵循以下规范:
-
Mapper.xml文件中的namespace与mapper接口的全限定名相同
-
Mapper接口方法名和Mapper.xml中定义的每个statement的id相同
-
Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql的parameterType的类型相同
-
Mapper接口方法的输出参数类型和mapper.xml中定义的每个sql的resultType的类型相同
这张图就是上面四种规范的解释

2、编写UserMapper接口

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();
}
(三)知识小结
MyBatis的Dao层实现的两种方式:
手动对Dao进行实现:传统开发方式
代理方式对Dao进行实现:
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
二、MyBatis映射文件深入
(一)动态sql语句概述
Mybatis 的映射文件中,前面我们的 SQL 都是比较简单的,有些时候业务逻辑复杂时,我们的 SQL是动态变化的,此时在前面的学习中我们的 SQL 就不能满足要求了。
(二)动态 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>
(1)当查询条件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);
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-g35Frrxw-1617609163051)(img\图片3.png)]](/https://i-blog.csdnimg.cn/blog_migrate/a114151a9d3dfd4a67edc174e74e83f8.png)
(2)当查询条件只有id存在时,控制台打印的sql语句如下:
//获得MyBatis框架生成的UserMapper接口的实现类
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User condition = new User();
condition.setId(1);
User user = userMapper.findByCondition(condition);
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZrNSp0aY-1617609163055)(img\图片4.png)]](/https://i-blog.csdnimg.cn/blog_migrate/eee4dbda98406981182047fcf470893f.png)
(四) 动态 SQL 之< foreach>
foreach标签的属性含义如下:< foreach >标签用于遍历集合,它的属性
•collection:代表要遍历的集合元素,注意编写时不要写#{}
•open:代表语句的开始部分
•close:代表结束部分
•item:代表遍历集合的每个元素,生成的变量名
•sperator:代表分隔符
举个栗子
循环执行sql的拼接操作,例如:SELECT * FROM USER WHERE id IN (1,2,5)。
<select id="findByIds" parameterType="array" 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);

(五)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>
(六)小结
MyBatis映射文件配置:
< select>:查询
< insert>:插入
< update>:修改
< delete>:删除
< where>:where条件
< if>:if判断
< foreach>:循环
< sql>:sql片段抽取
三、MyBatis核心配置文件深入
(一)typeHandlers标签
由于 Java类型和sql类型会存在不同,比如string和varchar,所以需要实现两者的转化。
因此 无论是 MyBatis 在预处理语句(PreparedStatement)中设置一个参数时,还是从结果集中取出一个值时, 都会用 类型处理器 将获取的值 以合适的方式 转换成 Java 类型。
下表描述了一些默认的类型处理器(截取部分)
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-VGKNvAFa-1617609163060)(img\图片6.png)]](/https://i-blog.csdnimg.cn/blog_migrate/4e2299ce0617a75cb164d31f926bf11d.png)
你可以 重写类型处理器(覆盖掉) 或 创建你自己的类型处理器(自定义) 来处理不支持的 或 非标准的类型。
具体做法为:
实现 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类型的方法


或者
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);
}
}
③在MyBatis核心配置文件中进行注册
<!--注册类型自定义转换器-->
<typeHandlers>
<typeHandler handler="com.itheima.typeHandlers.MyDateTypeHandler"></typeHandler>
</typeHandlers>
测试转换是否正确
测试添加操作:
user.setBirthday(new Date());
userMapper.add2(user);
数据库数据:
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0xtm9Jds-1617609163062)(img\图片7.png)]](/https://i-blog.csdnimg.cn/blog_migrate/43163c7b0e5dabf4ae5fe833ab9d241f.png)
测试查询操作:
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-E74gvQSI-1617609163063)(img\图片8.png)]](/https://i-blog.csdnimg.cn/blog_migrate/2d3ae9d85235e0496bf78060a70f2d83.png)
(二)plugins标签(插件标签)
MyBatis可以使用第三方的插件来对功能进行扩展,分页助手PageHelper 是将分页的复杂操作进行封装,使用简单的方式 即可获得分页的相关数据
开发步骤:
①导入通用PageHelper的坐标(在pom.xml里面)
要导其他插件就要集成其他插件的坐标,导完坐标就有相应的API和jar包
<!-- 分页助手 -->
<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插件
mybatis核心配置文件就是告诉mybatis我们要使用什么——就是把PageHelper插件和mybatis进行一个关联
所以说,pom.xml是整个项目的坐标导入(放各种依赖)
mybatis核心配置文件是告诉mybatis什么东西和自己关联
<!-- 注意:分页助手的插件 配置在通用馆mapper之前 -->
<plugin interceptor="com.github.pagehelper.PageHelper">
<!-- 指定方言 -->
<property name="dialect" value="mysql"/>
</plugin>
③测试分页代码实现
@Test
public void testPageHelper(){
//设置分页参数
PageHelper.startPage(1,2); //当前页+每页显示的条数
//这里的显示结果是:数据库里被排在第一页里的两条信息
PageHelper.startPage(2,2); //当前页+每页显示的条数
//这里的显示结果是:数据库里被排在第二页里的两条信息
List<User> select = userMapper2.select(null);
for(User user : select){
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());
(三)小结
MyBatis核心配置文件常用标签:
1、properties标签:该标签可以加载外部的properties文件(就是那个jdbc文件导入)
2、typeAliases标签:设置类型别名
3、environments标签:数据源环境配置标签
4、typeHandlers标签:配置自定义类型处理器
5、plugins标签:配置MyBatis的插件
本文详细介绍了MyBatis的Dao层实现,包括传统开发方式和代理开发方式,并通过实例展示了如何实现。接着深入探讨了MyBatis映射文件中的动态SQL,如<if>和<foreach>标签的用法,以及SQL片段抽取。此外,还讲解了MyBatis核心配置文件中的typeHandlers和plugins标签,包括自定义类型处理器和使用PageHelper插件进行分页操作。
&spm=1001.2101.3001.5002&articleId=115443484&d=1&t=3&u=1f16d790279c449c8b93186f9c631a02)
8720

被折叠的 条评论
为什么被折叠?



