只需要编写Mapper 接口,Mybatis 框架根据接口定义创建接口的动态代理对象
Mapper 接口开发需要遵循以下规范:
Mapper.xml文件中的namespace与mapper接口的全限定名相同
在Mapper.xml文件中可以使用:<where>
、<if>
、<foreach>
等标签
例子一:
<select id="findUserByCondition" resultType="user" parameterType="user">
select * from user
<where>
<if test="id!=0">
and id = #{id}
</if>
<if test="username!=null">
and username = #{username}
</if>
</where>
</select>
@Test
//MyBatis动态sql
public void test6() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
//测试数据
User condition = new User();
condition.setUsername("lisi");
//获得MyBatis框架生成的UserMapper接口的实现类
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User userByCondition = userMapper.findUserByCondition(condition );
System.out.println(userByCondition);
sqlSession.close();
}
例子二:
<select id="findUserByIds" resultType="user" parameterType="list">
select * from user
<where>
<foreach collection="list" item="id" open="id in (" close=")" separator=",">
#{id}
</foreach>
</where>
</select>
@Test
//MyBatis动态sql
public void test7() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
//测试数据
List arrayList = new ArrayList();
arrayList.add(1);
arrayList.add(2);
//获得MyBatis框架生成的UserMapper接口的实现类
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = userMapper.findUserByIds(arrayList);
System.out.println(userList);
sqlSession.close();
}
foreach标签的属性:
<!--将重复的sql提取出来-->
<sql id="selectAll">select * from user</sql>
<select id="findUserByIds" resultType="user" parameterType="list">
<!--用include引用-->
<include refid="selectAll"></include>
<where>
<foreach collection="list" item="id" open="id in (" close=")" separator=",">
#{id}
</foreach>
</where>
</select>
重写类型处理器或创建你自己的类型处理器来处理不支持的或非标准的类型
开发步骤:
定义转换类继承类(指定泛型)
在MyBatis核心配置文件中进行注册
MyBatis可以使用第三方的插件来对功能进行扩展,比如:分页助手PageHelper
开发步骤:
导入通用PageHelper的坐标
在mybatis核心配置文件中配置PageHelper插件