- if else
Mybatis里面没有else标签,但是可以使用when otherwise标签来达到这样的效果。
起作用是: 提供了任何条件,就进行条件查询,否则就使用id>1这个条件。<select id="listProduct" resultType="Product"> SELECT * FROM product_ <where> <choose> <when test="name != null"> and name like concat('%',#{name},'%') </when> <when test="price !=null and price != 0"> and price > #{price} </when> <otherwise> and id >1 </otherwise> </choose> </where> </select>
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.how2java.pojo"> <select id="listProduct" resultType="Product"> SELECT * FROM product_ <where> <choose> <when test="name != null"> and name like concat('%',#{name},'%') </when> <when test="price !=null and price != 0"> and price > #{price} </when> <otherwise> and id >1 </otherwise> </choose> </where> </select> </mapper>
package com.how2java; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import com.how2java.pojo.Product; public class TestMybatis { public static void main(String[] args) throws IOException { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session = sqlSessionFactory.openSession(); Map<String,Object> params = new HashMap<>(); // params.put("name","a"); // params.put("price","10"); List<Product> ps = session.selectList("listProduct",params); for (Product p : ps) { System.out.println(p); } session.commit(); session.close(); } private static void listAll(SqlSession session) { } }
Mybatis动态SQL-choose when otherwise标签
最新推荐文章于 2023-05-04 13:35:04 发布