mybatis动态SQL--Trim --Where

Trim是干嘛的?
是在你动态语句拼接的时候处理where 1=1

开始干活,配置mapper映射XML文件,写语句

/Mybatis02/config/mappers/GoodsInfoMapper.xml

<select id="queryByTrim" resultType="com.chen.GoodsInfo">
    select * from goods 
    <trim prefix="where" prefixOverrides="AND|OR">
		    <if test="name !=null">
    			and name like '${name}%'
    		</if>
    		<if test="id !=null">
    	  		and id =${id}
    		</if>
    </trim >
    
    </select>

然后去创建一个与select标签id名一样的接口方法

/Mybatis02/src/com/chen/dao/GoodsDao2.java

//动态SQL。。Trim
public List<GoodsInfo> queryByTrim(GoodsInfo a );

然后主入口类调用

/Mybatis02/src/test/Start2.java

public class Start2 {

	public static void main(String[] args) throws IOException {
		
		String resource = "mybatis-conf.xml";
		InputStream  inputStream = Resources.getResourceAsStream(resource);
		//创建SqlSessionFactory
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		//true表示自动提交。否则需要使用commit方法才会提交。默认是false
		SqlSession session = sqlSessionFactory.openSession();
		
		//拿到接口的代理对象
		GoodsDao2 dao=session.getMapper(GoodsDao2.class);
		//拿到了dao这个对象接下来就可以创建sql语句了;(直接调用接口方法)
		//因为接口方法里需要传入一个对象,所以
		GoodsInfo goods =new GoodsInfo();
		//然后给对象插属性
		goods.setId(10);
		goods.setName("牛");
		
	     List list =dao.queryByTrim(goods);
	     System.out.println(list.size());
		
		
		//如果上面不设置自动提交表单,那么就需要commit方法
		session.commit();
	}

}

点击运行

出现了报错,看了一段时间还找不到什么原因,先放着

先学习和Trim标签比较相似的------Where

/Mybatis02/config/mappers/GoodsInfoMapper.xml

<select id ="queryByWhere" resultType="com.chen.GoodsInfo">
    	select * from goods
    	<where>
    		<if test="name !=null">
    			 name like '${name}%'
    		</if>
    		<if test="id !=null">
    			and  id=${id}
    		</if>
    		
    	</where>
    </select>

/Mybatis02/src/com/chen/dao/GoodsDao2.java

//动态SQ; 。。Where
	public List<GoodsInfo> queryByWhere(GoodsInfo a);

/Mybatis02/src/test/Start2.java


public class Start2 {

	public static void main(String[] args) throws IOException {
		
		String resource = "mybatis-conf.xml";
		InputStream  inputStream = Resources.getResourceAsStream(resource);
		//创建SqlSessionFactory
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		//true表示自动提交。否则需要使用commit方法才会提交。默认是false
		SqlSession session = sqlSessionFactory.openSession();
		
		//拿到接口的代理对象
		GoodsDao2 dao=session.getMapper(GoodsDao2.class);
		//拿到了dao这个对象接下来就可以创建sql语句了;(直接调用接口方法)
		//因为接口方法里需要传入一个对象,所以
		GoodsInfo goods =new GoodsInfo();
		//然后给对象插属性
		goods.setId(10);
		goods.setName("牛");
		
	     List list =dao.queryByWhere(goods);
	     System.out.println(list.size());
		
		//如果上面不设置自动提交表单,那么就需要commit方法
		session.commit();
	}

}

运行结果

它mysql客户端里实质执行是这一条语句

回过头来看看写的这个where标签


即是说,如果我传入的id参数和name参数都不为空,那么它就会自动拼接上去,。(相当于执行 select * from goods where name like '?%' and id=? 这条语句)

小细节

假如我把and 也加上去,它是会自动帮你省略掉的,运行不会出错

原文地址:https://www.cnblogs.com/czy16/p/7629291.html