1.动态SQL语句
Mybatis 的映射文件中,我们刚接触的 SQL 都是比较简单的,有些时候业务逻辑复杂时,我们的 SQL是动态变化的,此时在前面的学习中我们的 SQL 就不能满足要求了。
参考的官方文档,描述如下:
①if语句
<!--根据参数值得不同情况进行查询-->
<select id="findById" parameterType="int" resultType="user">
select * from user where id=#{id}
</select>
<select id="findByCondition" parameterType="user" resultType="user">
select * from user
<where>
<if test="id!=0">
id=#{id}
</if>
<if test="username!=null">
and username=#{username}
</if>
<if test="password!=null">
and password=#{password}
</if>
</where>
</select>
在根据参数传入的值进行动态的判断
public class ServiceTest {
public static void main(String[] args) throws IOException {
//动态SQL语句
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
//获得session工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
//获得session会话对象
SqlSession session=sqlSessionFactory.openSession();//可以设置为true,自动提交
//执行操作,参数,namespace+id
UserMapper mapper= session.getMapper(UserMapper.class);
//通过mapper对象调用方法,实现对数据库的操作
//模拟User对象
User user=new User();
//当参数条件只有一个的时候,我们也可以传入User对象
//会通过if语句进行判断,然后查询处相应的结果
// user.setId(1);
// user.setUsername("zhangsan");
user.setPassword("123");
List<User> byCondition = mapper.findByCondition(user);
System.out.println(byCondition);
}
}
②foreach语句
循环执行sql的拼接操作,例如:SELECT * FROM USER WHERE id IN (1,2)。
<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>
public class ServiceTest {
public static void main(String[] args) throws IOException {
//foreach
//模拟Ids的数据
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
//获得session工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
//获得session会话对象
SqlSession session=sqlSessionFactory.openSession();//可以设置为true,自动提交
//执行操作,参数,namespace+id
UserMapper mapper= session.getMapper(UserMapper.class);
//通过mapper对象调用方法,实现对数据库的操作
List<Integer> ids=new ArrayList<>();
ids.add(1);
ids.add(2);
List<User> userlist=mapper.findByIds(ids);
System.out.println(userlist);
}
}
2.SQL语句的抽取
总结: