Mybatis(动态sql)
来源:互联网 发布:linux服务器维护教程 编辑:程序博客网 时间:2024/06/10 15:44
动态sql
mybaits核心对sql语句进行灵活操作,通过表达式进行判断,对sql进行灵活拼接,组装
- 需求:用户信息的综合查询列表和用户信息列表总数这两个Statement的定义使用动态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.name!=null and userCustom.name!= ''"> and user.name = #{userCustom.name} </if> </if> </sql>
引用sql片段
select * from user <!-- where可以自动去掉条件中的第一个and --> <where> <!-- 引用sql片段的id,如果refid指定的id不在本mapper文件中,需要前边加namespace --> <include refid = "query_user_where"></include> <!-- 在这里还要引用其他的sql片段 --> </where>
foreach
向sql传递数组或list,mybaits使用foreach解析
- 需求:在用户查询列表和总数中增加多个id的查询
id=1 OR id=2
- 在输入的参数类型中添加Listids 传入多个id
//传入多个id private List<Integer> ids; public List<Integer> getIds() { return ids; } public void setIds(List<Integer> ids) { this.ids = ids; }
- xml文件
<if test = "ids!=null"> <!-- 使用foreach遍历传入ids collection:指定输入对象中集合属性 item:每个遍历生成对象 open:开始遍历拼接的串 close:结束遍历拼接的串 separator:遍历的两个对象中需要拼接的串 --> <!-- 使用实现下边的sql拼接 AND (id=1 OR id=2 OR id=3) --> <foreach collection = "ids" item = "user_id" open = "AND (" close = ")" separator = "OR"> <!-- 每次遍历需要拼接的串 --> id = #{user_id} </foreach> </if>
- 测试
@Test public void testFindUserList() throws Exception { SqlSession sqlSession = SqlSessionFactory.openSession(); //创建UserMapper对象,mybaits自动生成mapper代理对象 UserMapper userMapper = sqlSession.getMapper(UserMapper.class); //SqlMapConfig加载映射文件 //创建包装对象,设置查询条件 UserQueryVo userQueryVo = new UserQueryVo(); UserCustom userCustom = new UserCustom(); //由于这里使用动态sql,如果不设置某个值,条件不会拼接在sql中 //userCustom.setSex("男"); userCustom.setName("小明"); //传入多个id List<Integer> ids = new ArrayList<Integer>(); ids.add(1); ids.add(2); ids.add(3); //将ids通过userQueryVo传入Statement中 userQueryVo.setIds(ids); userQueryVo.setUserCustom(userCustom); //调用userMapper方法 List<UserCustom> list = userMapper.findUserList(userQueryVo); sqlSession.close(); System.out.println(list); }
阅读全文
0 0
- mybatis动态SQL语句
- MyBatis动态SQL
- MyBatis 动态SQL
- Mybatis 动态SQL
- MyBatis动态SQL
- MyBatis动态SQL完整版
- mybatis动态sql
- mybatis动态SQL语句
- mybatis动态SQL语句
- MyBatis的动态SQL
- MyBatis动态SQL
- MyBatis动态SQL
- MyBatis 动态SQL语句
- MyBatis动态SQL
- Mybatis组建动态SQL
- MyBatis 动态sql
- mybatis 动态SQL语句
- MyBatis动态SQL详解
- 第一天:浪迹天涯网上商城(1.0版本)--项目介绍
- 剖析Disruptor:为什么会这么快?(一)锁的缺点
- 08cms安装出错 MYSQL错误:MySQL服务器正在使用–secure-file-priv选项运行,因此无法执行此语句
- 每次看见逃离,我想说我想逃离二线小城市
- spring拦截器与filter的区别
- Mybatis(动态sql)
- oracle新建用户,授权,建表空间语句
- Eclipse的编码
- Linux常用指令总结
- Qt生成UUID码
- 这道题的错误做法是我原创的,目前还不知道哪错了!!!
- 登录后自动跳转到登录前的页面
- 谷歌AI系统写的机器学习代码,完爆程序员
- 《JavaScript编程精粹》——函数篇