文章目录
一.代理开发方式
采用Mybatis的电路考法方式实现Dao层的开发,这种方式是我们进入企业的主流。
Mapper接口开发方法只需要程序员编写Mapper接口(相当于Dao接口),由Mybatis框架根据接口定义创建接口的动态代理对象,代理对象的方法体同上边Dao接口实现类方法。 Mapper接口开发需要遵循以下规范:
Mapper.xml文件中的namespace与mapper接口的全限定名相同。
Mapper接口方法名和Mapperxml中定义的每个statement的id相同。
Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql的parameterType的类型相同。
Mapper接口方法的输出参数类型和mapper.xml中定义的每个sql的resultType的类型相同。
代码实现如下:
UserDao.java:
public interface UserDao {
public User findById(int id) throws IOException;
}
UserMapper.xml:
<!--根据id进行查询-->
<select id="findById" parameterType="int" resultType="user">
select * from user where id=#{id}
</select>
sqlConfig.xml配置映射文件:
<!--加载映射文件-->
<mappers>
<mapper resource="com/itheima/mapper/UserMapper.xml"></mapper>
</mappers>
测试:
public static void main(String[] args) throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.findById(1);
System.out.println(user);
}
二.mybatis映射文件的深入
动态sql语句
概述:Mybatais的映射文件中,前面我们的SQL都是比较简单的,有时候业务逻辑复杂时,我们的sql时动态变化的,此时在其那面学习的sql就不能满足要求了。
2.1 动态SQL之
我们根据实体类的不同取值,使用不同的 SQL语句来进行查询。比如在id如果不为空时可以根据id查询,如果username 不为空时还要加入用户名作为条件。这种情况在我们的多条件组合查询中经常会碰到。
UserMapper.xml:
<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>
测试类:
@Test
public void test1() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//模拟条件user
User user=new User();
user.setId(1);
user.setUsername("zhangsan");
//user.setPassword("123");
List<User> userList = mapper.findByCondition(user);
System.out.println(userList);
}
当查询条件是id和username,控制台打印的sql语句是 select * from user where id=? and username=?
2.2 动态SQL之
循环执行sql的拼接操作,例如:SELECT * FROM USER WHERE id IN (1,2,5)。
UserMapper.xml:
<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>
测试类:
@Test
public void test2() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//模拟ids的数据
List<Integer> ids=new ArrayList<Integer>();
ids.add(1);
ids.add(2);
List<User> byIds = mapper.findByIds(ids);
System.out.println(byIds);
}
控制台输出的sql语句是select * from user where id in (?,?)
foreach标签的属性含义如下:
标签用于遍历集合,它的属性:
• collection:代表要遍历的集合元素,注意编写时不要写#{}
• open:代表语句的开始部分
• close:代表结束部分
• item:代表遍历集合的每个元素,生成的变量名
• sperator:代表分隔符
2.3 动态SQL之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>
核心配置文件深入
typeHandlers标签
可以重写类型处理器或创建你自己的类型处理器来处理不支持的或非标准的类型。
具体做法为:实现org.apache.ibatis.type.TypeHandler接口,或继承一个很便利的类org.apache.ibatis.type.BaseTypeHandler,然后可以选择性地将它映射到一个JDBC类型。
例如需求:一个Java中的Date数据类型,我想将之存到数据库的时候存成一个1970年至今的毫秒数,取出来时转换成java的Date,即java的Date与数据库的varchar毫秒值之间转换。
开发步骤:
①定义转换类继承类BaseTypeHandler(这个泛型就是要转化的java类型)
②覆盖4个未实现的方法,其中setNonNullParameter为java程序设置数据到数据库的回调方getNullableResul为查询时mysql的字符串类型转换成java的Type类型的方法
③在MyBatis核心配置文件中进行注册
④ 测试转换是否正确
例子:1.定义转换类继承类BaseTypeHandler
2.覆盖4个未实现的方法,其中setNonNullParameter为java程序设置数据到数据库的回调方getNullableResul为查询时mysql的字符串类型转换成java的Type类型的方法
public class DateTypeHandler extends BaseTypeHandler<Date> {
//将java类型 转换成 数据库需要的类型
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;
}
}
3.在MyBatis核心配置文件中进行注册
<!--注册类型处理器-->
<typeHandlers>
<typeHandler handler="com.itheima.handler.DateTypeHandler"></typeHandler>
</typeHandlers>
4.测试转换是否正确
先测试是否将Java中data类型的数据转换到数据库中是Long
@Test
public void test1() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//创建user
User user = new User();
user.setUsername("ceshi");
user.setPassword("abc");
user.setBirthday(new Date());
//执行保存造作
mapper.save(user);
sqlSession.commit();
sqlSession.close();
}
再测试通过id查询Long类型的数据控制台转换输出的是Data类型
@Test
public void test2() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.findById(15);
System.out.println("user中的birthday:"+user.getBirthday());
sqlSession.commit();
sqlSession.close();
}
plugins标签
分页助手PageHelper
MyBatis可以使用第三方的插件来对功能进行扩展,分页助手PageHelper是将分页的复杂操作进行封装,使用简单的方式即可过得分页的相关数据
开发步骤:
①导入通用PageHelper的坐标
②在mybatis核心配置文件中配置PageHelper插件
③测试分页数据获取
1.导入通用PageHelper的坐标,pom.xml
<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>
</dependencies>
2.在mybatis核心配置文件中配置PageHelper插件,sqlMapConfig.xml,
<!--配置分页助手插件-->
<plugins>
<plugin interceptor="com.github.pagehelper.PageHelper">
<property name="dialect" value="mysql"></property>
</plugin>
</plugins>
3.测试分页数据获取
@Test
public void test3() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//设置分页相关参数 当前页+每页显示的条数
PageHelper.startPage(3,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.close();
}
测试结果: