mybatis的动态sql

一、什么是动态sql
mybatis中 对sql语句进行灵活操作,通过表达式进行判断,对sql进行灵活拼接、组装
如下,对用户信息查询时,对查询条件进行判断,如果输入参数不为空才进行查询条件拼接。
二、定义入参封装类
其中User类,在本分类其他博客有说明,是公共的

  public class UserCustom extends User{
	      private static final long serialVersionUID = 1L;
   }
   public class UserQueryVo {
	private UserCustom userCustom;
	public UserCustom getUserCustom() {
		return userCustom;
	}
	public void setUserCustom(UserCustom userCustom) {
		this.userCustom = userCustom;
	}
}

三、在mapper.xml定义
3.1定义一个sql片段,并通过条件判断进行查询

       <!-- 定义sql片段 -->
  <sql id="query_user_where">
      <if test="userCustom!=null">
		        <if test="userCustom.sex!=null and userCustom.sex !=''">
		           and user.sex=#{userCustom.sex}
		        </if>
		        <if test="userCustom.username!=null and userCustom.username !=''">
		            and user.username like '%${userCustom.username}%'
		        </if>
	 </if>
  </sql>

3.2引用这个动态sql

 <!-- 通过性别和用户名查询 -->
   <select id="findUserBySexName" parameterType="com.dd.mybatis.po.UserQueryVo" resultType="com.dd.mybatis.po.UserCustom">
		select * from user  
		<!-- 动态sql -->
		<where>
		    <include  refid="query_user_where"></include>
		</where>
	</select>

四、在mqpper.java中定义
//通过性别和姓名查询

public List<UserCustom> findUserBySexName(UserQueryVo UserQueryVo) throws Exception;

五、代码测试

   public class UserMapperTest {
	SqlSessionFactory sqlSessionFactory;
	@Before
	public void before() throws Exception {
		// mybatis配置文件
		String resource = "SqlMapConfig.xml";
		// 得到配置文件流
		InputStream inputStream = Resources.getResourceAsStream(resource);
		// 创建会话工厂,出入文件配置流
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
	}
	@Test
	public void findUserBySexName()  {
		SqlSession sqlSession =null;
		try {
			sqlSession=sqlSessionFactory.openSession();
			// 创建UserMapper对象,mybatis自动生成UserMapper代理对象
			UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
			UserCustom userCustom=new UserCustom();
//			如果入参只有性别,用户名为空,将执行下面sql
//			<if test="userCustom.sex!=null and userCustom.sex !=''">
//	           and user.sex=#{userCustom.sex}
//	        </if>
	     	userCustom.setSex("1");  
//			如果入参只有用户名,性别为空,将执行下面sql
			<if test="userCustom.username!=null and userCustom.username !=''">
//            and user.username like '%${userCustom.username}%'
//        </if>
			userCustom.setUsername("张三丰");
			UserQueryVo userQueryVo=new UserQueryVo();
			userQueryVo.setUserCustom(userCustom);
			List<UserCustom> list = userMapper.findUserBySexName(userQueryVo);
			System.out.println(list);
		} catch (Exception e) {
			// TODO: handle exception
		}finally{
			sqlSession.close();
		}
		
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值