动态sql-if标签与where标签
(1)if标签
if标签:可以判断传入的参数是否为空,如果不为空则拼接sql
<if test="id!=null and id!=''">
and id = #{id}
</if>
(2)where标签
- where标签可以自动检测拼接条件是否全部不成立,等同于where 1=1 不会造成语法错误
select * from table where //不会出现
where 1=1的用处 主要用来构件动态SQL
String sql = “select a,b from table_a where 1=1 “;
if(!b.equals(””))
sql += “and b=’”+b+"’"; 当用户选择了b ( 假如b值为qwe ) 结果就是:String sql = ''select a,b from table_a where 1=1 and b= ‘qwe’;但是当用户没有选择b 那b就是一个空值
结果就是:String sql =’‘select a,b from table_a where 1=1’’; ,运行也不会出错,相当于没有限制b这个条件。
但是如果没有1=1的条件,则l String sql =’‘select a,b from table_a where’’ ; 这样就会报错。
- 同时还可以自动检测第一个拼接条件前是否有and,有and会自动消掉,不会造成
select * from table where and id=?
(3)foreach标签
foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。
例如:select * from table where id in(1,2,3)
foreach元素的属性主要有 item,index,collection,open,separator,close。
- item表示集合中每一个元素进行迭代时的别名,
- index指 定一个名字,用于表示在迭代过程中,每次迭代到的位置,
- open表示该语句以什么开始,
- separator表示在每次进行迭代之间以什么符号作为分隔 符,
- close表示以什么结束。
在使用foreach的时候最关键的也是最容易出错的就是collection属性
该属性是必须指定的,其中collection的属性值与接口的参数名没有任何关系
如果希望使用别名需要用@param指定
使用示例:
配置文件
<select id="selectMoreInfo" resultType="com.glc.bean.user">
select * from `user`
<where>
<if test="id!=null and id!=''">
and id = #{id}
</if>
<if test="username!=null and username!=''">
and username like #{username}
</if>
<if test="birthday!=null and birthday!=''">
and birthday = #{birthday}
</if>
<if test="sex!=null and sex!=''">
and sex = #{sex}
</if>
<if test="address!=null and address!=''">
and address = #{address}
</if>
</where>
</select>
接口:
public interface UserDao {
public List<user> selectMoreInfo(user user) ;
}
测试类:
@org.junit.Test
public void TestSelectMoreInfo(){
//获得session对象
SqlSession sqlsessio = MySessionUtils.getSession();
UserDao mapper = sqlsessio.getMapper(UserDao.class);
user user = new user();
user.setUsername("%小%");
user.setAddress("广州");
List<user> users = mapper.selectMoreInfo(user);
System.out.println(users);
//调用getMapper
sqlsessio.commit();
sqlsessio.close();
//查询订单
//关闭连接
}