Mybatis映射文件动态SQL语句-01
原创
©著作权归作者所有:来自51CTO博客作者漫话人生的原创作品,请联系作者获取转载授权,否则将追究法律责任
因为在很多业务逻辑复杂的项目中,往往不是简单的sql语句就能查询出来自己想要的数据,所有mybatis引入了动态sql语句,
UserMapper.xml
<?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.hao.mapper.UserMapper">
<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>
</mapper>
Dao层接口
然后测试
@Test
public void test1() throws IOException {
InputStream stream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSession sqlSession = new SqlSessionFactoryBuilder().build(stream).openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
// 模拟条件
User user = new User();
user.setId(1);
user.setUsername("张三");
user.setPassword("123");
List<User> userList = mapper.findByCondition(user);
System.out.println(userList);
}
结果: