之前我们学习了利用mybatis进行了模糊查询。本节学习使用mybatis进行多条件查询。下面就主要步骤进行一些阐述
1.准备Category.xml
主要查询代码是:
<select id="listCategoryByIdAndName" parameterType="map" resultType="Category">
select * from category_ where id>#{id} and name like concat('%',#{name},'%')
</select>
加上约束后完整的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.how2java.pojo">
<select id="listCategoryByIdAndName" parameterType="map" resultType="Category">
select * from category_ where id>#{id} and name like concat('%',#{name},'%')
</select>
</mapper>
2.书写TestMybatis.java
package com.how2java.pojo;
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;
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 sqlSession=sqlSessionFactory.openSession();
Map<String,Object> params=new HashMap<>();
params.put("id", 3);
params.put("name", "cat");
List<Category> cs=sqlSession.selectList("listCategoryByIdAndName",params);
for(Category c:cs) {
System.out.println(c.getName());
}
/*List<Category> cs = sqlSession.selectList("listCategoryByName","cat");
for (Category c : cs) {
System.out.println(c.getName());
}*/
/*Category c=new Category();
c.setName("新增加的Category");
sqlSession.insert("addCategory",c);
listAll(sqlSession);*/
sqlSession.commit();
sqlSession.close();
}
public static void listAll(SqlSession session) {
List<Category> categories=session.selectList("listCategory");
for (Category c : categories) {
System.out.println(c.getName());
}
}
}
数据库表结构为:
测试结果如下:
新增加的Category