文章目录
一、MyBatis的Dao层实现
1.1 传统开发方式
1)编写 UserDao接口
public interface UserMapper {
public List<User> findAll() throws IOException;
}
2)编写 UserDaolmpl实现
public class UserMapperImpl implements UserMapper {
public List<User> findAll() throws IOException {
InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = build.openSession();
List<User> userList = sqlSession.selectList("userMapper.findAll");
return userList;
}
}
3)测试传统方式
public class ServiceDemo {
public static void main(String[] args) throws IOException {
//创建 dao 层对象
UserMapper userMapper = new UserMapperImpl();
List<User> userList = userMapper.findAll();
System.out.println(userList);
}
}
1.2 代理开发方式
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接口
UserMapper.java
public interface UserMapper {
public List<User> findAll();
public User findById(int id);
}
UserMapper.xml
<mapper namespace="com.itheima.dao.UserMapper">
<!--查询操作-->
<select id="findAll" resultType="user">
select *from user
</select>
<mapper>
3)测试代理方式
Test1
public class ServiceDemo {
public static void main(String[] args) throws IOException {
InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory build = builder.build(inputStream);
SqlSession sqlSession = build.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.findAll();
System.out.println(userList);
}
}
Test2
public class ServiceDemo {
public static void main(String[] args) throws IOException {
InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory build = builder.build(inputStream);
SqlSession sqlSession = build.openSession();
//查询全部
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.findAll();
//通过id查询
User user = mapper.findById(1);
//打印输出结果
System.out.println(userList);
System.out.println(user);
}
}
1.3 知识小结
MyBatis的Dao层实现的两种方式:
- 手动对Dao进行实现:传统开发方式。
- 代理方式对Dao进行实现。
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
二、MyBatis映射文件的深入理解
2.1 动态sql语句
1. 动态sql语句概述
Mybatis的映射文件中,前面我们的SQL都是比较简单的,有些时候业务逻辑复杂时,我们的SQL是动态变化的,此时在前面的学习中我们的SQL就不能满足要求了参考的官方文档,描述如下:
MapperTest
public class MapperTest {
@Test
public void test1() throws IOException {
InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory build = builder.build(inputStream);
SqlSession sqlSession = build.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//模拟条件User
User condition = new User();
condition.setId(1);
condition.setUsername("zhangsan");
condition.setPassword("123");
List<User> userList = mapper.findByCondition(condition);
System.out.println(userList);
}
}
UserMapper.xml
<mapper namespace="com.itheima.mapper.UserMapper">
<select id="findByCondition" parameterType="user" resultType="user">
select *from user where id = #{id} and username = #{username} and password = #{password}
</select>
</mapper>
上面是测试的sql语句,这里就有一个问题了,如果我不知道传入的参数是否有password或者其他属性会咋样呢?也就是参数不确定。下面做个测试:
//condition.setPassword("123");
测试结果
因为我们没有设置password这个参数,根据sql语句,password = null,所以查不到与之匹配的记录,所以结果也就是空,那么如何解决呢?那就是在sql语句中使用`了
2.(重点)动态SQL之<if>
我们根据实体类的不同取值,使用不同的SQL语句来进行查询。比如在id如果不为空时可以根据id查询,如果username不同空时还要加入用户名作为条件。这种情况在我们的多条件组合查询中经常会碰到。
使用<if>进行判断
Test1不给password
<select id="findByCondition" parameterType="user" resultType="user">
select *from user where 1 = 1
<if test="id != 0">
and id = #{id}
</if>
<if test="username != null">
and username = #{username}
</if>
<if test="password != null">
and password = #{password}
</if>
</select>
当查询条件id和 username都存在时,控制台打印的sq语句如下
上面的sql语句还可以改写成这样(效果是一样的):
<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="password != null">
and password = #{password}
</if>
</where>
</select>
Test2只给id值
condition.setId(1);
//condition.setUsername("zhangsan");
//condition.setPassword("123");
当查询条件只有id存在时,控制台打印的sql语句如下
Test3不给所有属性值
//condition.setId(1);
//condition.setUsername("zhangsan");
//condition.setPassword("123");
通过测试发现
mybatis
会动态的帮我们拼接where
,如果if
条件成立了会自动带上where
3.动态SQL之<foreach>
foreach标签的属性含义如下
<foreach>
标签用于遍历集合,它的属性
- collection:代表要遍历的集合元素,注意编写时不要写#{}
- open:代表语句的开始部分close:代表结束部分
- item:代表遍历集合的每个元素,生成的变量名
- sperator:代表分隔符
UserMapper.xml
<mapper namespace="com.itheima.mapper.UserMapper">
<select id="findByIds" parameterType="list" resultType="user">
select *from user
<where>
<foreach collection="list" open="id in (" close=")" separator="," item="id">
#{id}
</foreach>
</where>
</select>
</mapper>
Test1
@Test
public void test2() throws IOException {
InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory build = builder.build(inputStream);
SqlSession sqlSession = build.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//模拟条件User
User condition = new User();
condition.setId(1);
//condition.setUsername("zhangsan");
//condition.setPassword("123");
List<Integer> ids = new ArrayList<Integer>();
ids.add(1);
ids.add(2);
List<User> userList = mapper.findByIds(ids);
System.out.println(userList);
}
测试结果
2.2 SQL之片段抽取
sql中可将重复的sql提取出来,使用时用
include
引用即可,最终达到sql重用
的目的。
sqlMapper.xml
<mapper namespace="com.itheima.mapper.UserMapper">
<!--sql语句抽取-->
<sql id="selectUser">select * from user</sql>
<select id="findByCondition" parameterType="user" resultType="user">
<include refid="selectUser"></include>
<where>
<if test="id != 0">
and id = #{id}
</if>
<if test="username != null">
and username = #{username}
</if>
<if test="password != null">
and password = #{password}
</if>
</where>
</select>
<select id="findByIds" parameterType="list" resultType="user">
<include refid="selectUser"></include>
<where>
<foreach collection="list" open="id in (" close=")" separator="," item="id">
#{id}
</foreach>
</where>
</select>
</mapper>
2.3 知识小结
MyBatis映射文件配置:
<select>
:查询
<insert>
:插入
<update>
:修改
<delete>
:删除
<where>
:where条件
<if>
:判断
<foreach>
:循环
<sql>
:sql片段抽取
三、MyBatis核心配置文件深入
3.1 typeHandlers标签
无论是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为查询时,mysq的字符串类型转换成java的Type类型的方法
③在 MyBatist核心配置文件中进行注册
④测试转换是否正确
User
public class User {
private int id;
private String username;
private String password;
private Date birthday;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
UserMapper.java
public void save(User user);
UserMapper.xml
<mapper namespace="com.itheima.mapper.UserMapper">
<insert id="save" parameterType="user">
insert into user values(#{id}, #{username}, #{password}, #{birthday})
</insert>
</mapper>
Test1
@Test
public void test1() throws IOException {
//模板代码
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory build = builder.build(resourceAsStream);
SqlSession sqlSession = build.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//模拟user
User user = new User();
user.setUsername("ceshi");
user.setUsername("321");
user.setBirthday(new Date());
//执行sql
mapper.save(user);
//手动提交事务
sqlSession.commit();
//关闭源
sqlSession.close();
}
因为我们插入进去的数据是
Date
类型,与数据库中的类型不符合,所以报错。mybatis
没法帮我们转换的,就需要我们自己手动去自定义转换器了。我们按照前面给出的步骤来玩一下!
1)定义转换类继承类BaseTypeHandler<T>
2)覆盖4个未实现的方法,其中setNonNullParameter为java程序设置数据到数据库的回调方法, getNullableResult为查询时,mysq的字符串类型转换成java的Type类型的方法
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类型 转换成数据库需要的类型
public void setNonNullParameter(PreparedStatement preparedStatement, int i, Date date, JdbcType jdbcType) throws SQLException {
//i 就是当前参数的位置
long time = date.getTime();
preparedStatement.setLong(i, time);
}
/*
* 将数据库中的类型 转换成Java类型
* String参数 要转换的字段名称
* ResultSet 查询出的结果集
* */
public Date getNullableResult(ResultSet resultSet, String s) throws SQLException {
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;
}
public Date getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
long aLong = callableStatement.getLong(i);
Date date = new Date(aLong);
return date;
}
}
踩坑点:导包千万别导错了!巨坑!
3)在 MyBatist核心配置文件中进行注册
<!--注册类处理器-->
<typeHandlers>
<typeHandler handler="com.itheima.handler.DateTypeHandler"></typeHandler>
</typeHandlers>
4)测试转换是否正确
测试查询
我自己测试,使用birthday始终是null,无语了,找不出来问题,先放一放。
3.2 plugins标签
MyBatist可以使用第三方的插件来对功能进行扩展,分页助手 PageHelper是将分页的复杂操作进行封装,使用简单的方式即可获得分页的相关数据开发步骤
①导入通用PageHelper
的坐标
②在mybatis核心配置文件中配置PageHelper
插件
③测试分页数据获取
pom.xml
1)导入通用 Pagehelperl的坐标
<!--分页助手-->
<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>
2)在mybatis核心配置文件中配置 PageHelper插件
<!--配置分页助手插件-->
<plugins>
<plugin interceptor="com.github.pagehelper.PageHelper">
<property name="dialect" value="mysql"/>
</plugin>
</plugins>
3)测试分页数据获取
Test3
@Test
public void test3() throws IOException {
//模板代码
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory build = builder.build(resourceAsStream);
SqlSession sqlSession = build.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//设置分页相关参数 当前页+每页显示条数
PageHelper.startPage(2,3);
List<User> userList = mapper.findAll();
for (User user : userList) {
System.out.println(user);
}
sqlSession.commit();
//关闭源
sqlSession.close();
}
PageHelper.startPage(1,10);
@Test
public void test4() throws IOException {
//模板代码
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory build = builder.build(resourceAsStream);
SqlSession sqlSession = build.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//设置分页相关参数 当前页+每页显示条数
PageHelper.startPage(2, 3);
List<User> userList = mapper.findAll();
for (User user : userList) {
System.out.println(user);
}
//获得与分页相关的参数
PageInfo<User> pageInfo = new PageInfo<User>(userList);
System.out.println("当前页:" + pageInfo.getPageNum());
System.out.println("每页显示条数:" + pageInfo.getPageSize());
System.out.println("总条数 " + pageInfo.getTotal());
System.out.println("总页数: " + pageInfo.getPages());
System.out.println("上一页: " + pageInfo.getPrePage());
System.out.println("下一页: " + pageInfo.getNextPage());
System.out.println("是否是第一个: " + pageInfo.isIsFirstPage());
System.out.println("是否是最后一个: " + pageInfo.isIsLastPage());
sqlSession.commit();
//关闭源
sqlSession.close();
}
PageHelper.startPage(4, 3);
3.3 知识小结
MyBatis核心配置文件常用标签
- properties标签:该标签可以加载外部的
properties
文件- typeAliases标签:设置类型别名
- environments标签:数据源环境配置标签
- typeHandlers标签:配置自定义类型处理器
- plugins标签:配置MyBatis的插件