目录
数据库
product_表
插入数据:
建表sql文:
use mybatistest1;
create table product_(
id int NOT NULL AUTO_INCREMENT,
name varchar(30) DEFAULT NULL,
price float DEFAULT 0,
cid int ,
PRIMARY KEY (id)
)AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
代码
Product.java类
package com.mybatis.pojo;
//系统内由很多产品,但是不一定是全部都关联到需要查找的特定的订单
public class Product {
private int id;
private String name;
private float price;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
@Override
public String toString() {
return "Product [id=" + id + ", name=" + name + ", price=" + price + "]";
}
}
Product.xml
<?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.mybatis.pojo">
<select id="listProduct" resultType="Product"> <!-- 传值Product类型的时候需要定义parameterType="Product"-->
<!-- 如果没有传入参数name就执行直接查询 -->
select p.*
from product_ p
<where>
<choose>
<!-- 如果都不满足when的条件的时候,就执行otherwise标签下的语句 -->
<when test="nameKey!=null">
and name like concat('%',#{nameKey},'%')
</when>
<when test="priceKey!=null and price!=0">
and price>=#{price}
</when>
<otherwise>
and id>1
</otherwise>
</choose>
</where>
</select>
</mapper>
choose标签测试类TestMybatis.java
package com.mybatis;
import java.awt.event.ItemEvent;
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.mybatis.pojo.*;
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); //建立sql会话工厂,将输入流装入
SqlSession session=sqlSessionFactory.openSession(); //开启一个会话
listProduct(session);
session.commit(); //更新到数据库
session.close();
}
private static void listProduct(SqlSession session) {
List<Product> ps=session.selectList("listProduct");
for(Product p:ps) {
System.out.println(p);
}
System.out.println("模糊查询");
//新建一个map集合,其中key为String类型,value可以也为String类型
Map<String ,String> params=new HashMap<>();
params.put("nameKey", null);
params.put("priceKey", "0"); //
List<Product> ps2=session.selectList("listProduct",params);
for(Product p:ps2) {
System.out.println(p);
}
}
}
结果
总结
choose标签下,如果都不符合条件when,就执行otherwise标签下的sql