本篇主要记录如何利用mybatis的动态sql来实现灵活的增删改查。
一、提取公共代码
在上一篇代码的基础上,提取出公共代码
package com.mybtisstudy.test;
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 org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.mybatisstudy.pojo.Employee;
public class TestMybatis {
private SqlSessionFactory factory;
/**没有将session也提取到方法内是因为session 是不安全的,所以每次使用都新创建就好了*/
@Before
public void prefix() throws IOException {
InputStream stm = Resources.getResourceAsStream("sqlMapConfig.xml");
factory = new SqlSessionFactoryBuilder().build(stm);
}
}
二、进行测试
@Test
public void selectTest() {
SqlSession session = factory.openSession();
String sqlId = "com.mybatisstudy.pojo.EmployeeMapper.findAll";
List<Employee> emps = session.selectList(sqlId);
for (Employee emp : emps) {
System.out.println(emp);
}
}
输出结果为:
说明我们提取的没有问题
三、占位符
本次的占位符只记录#{} 和 ${},不记录?及其他占位符
3.1首先在mapper文件中使用井号占位符
#占位符只能占位为将会获得准确数据的元素,若不是准确数据的则不能占据,例如数据库的列名这种是不能使用#的
打开EmployeeMapper.xml文件,在sql中插入:
<insert id="insertsharp">
insert into employee(name,job,salary) values(#{name},#{job},#{salary})
</insert>
@Test
public void insertTest() {
SqlSession session = factory.openSession();
String sqlId = "com.mybatisstudy.pojo.EmployeeMapper.insertsharp";
Employee emp01 = new Employee();
emp01.setName("criss");
emp01.setJob("worker");
emp01.setSalary(20);
int updateTestInt = session.update(sqlId,emp01);
session.commit();
System.out.println(updateTestInt);
}
这里的#{name}#{job}#{salary}在我们插入数据的时候(对象.set属性(数据))的时候,进行对应。
以#{name}为例,在提取数据的时候会获取Employee的setName()方法内的数据,首先会将Employee内的所有set方法都小写,然后去掉右侧的()和左侧的set,如果有对应的,则会获取该数据,而如果没有则会不成功执行sql。
运行上方的代码,然后到数据库中查询
数据正确了
3.2使用$占位符
$占位符为在不能使用#占位符时使用,即笼统词,例如数据库列,或者模糊查询时使用
在mapper文件中新建sql
<select id="select02" resultType="com.mybatisstudy.pojo.Employee">
select ${elements} from employee
</select>
在测试类中进行实现
@Test
public void selectDollar() {
SqlSession session = factory.openSession();
String sqlId = "com.mybatisstudy.pojo.EmployeeMapper.select02";
Map map = new HashMap();
map.put("elements","name,job");
List<Object> emps = session.selectList(sqlId,map);
for (Object emp : emps) {
System.out.println(emp);
}
}
结果如下(因为toString方法我们重写为所有数据都要展示,所以sqlary和id都获取了,尽管没有获取到):
四、动态SQL
4.1 if标签
在mapper文件中添加如下
<select id="findAll3" resultType="com.mybatisstudy.pojo.Employee">
select * from employee
where 1=1
<if test="name != null">
and name like '%${name}%'
</if>
</select>
在测试类中添加方法
@Test
public void selectTest03() {
SqlSession session = factory.openSession();
String sqlId = "com.mybatisstudy.pojo.EmployeeMapper.findAll3";
Map map = new HashMap();
map.put("name","张");
List<Employee> emps = session.selectList(sqlId,map);
for (Employee emp : emps) {
System.out.println(emp);
}
}
测试结果为:
if标签的作用是在判断其中的 test为true时执行,否则就不会执行
4.2where标签
在mapper文件中添加如下:
<select id="findAll4" resultType="com.mybatisstudy.pojo.Employee">
select * from employee
<where>
<if test="minSalary != null">
salary > #{minSalary}
</if>
<if test="maxSalary != null">
and salary <![CDATA[<]]> #{maxSalary}
</if>
</where>
</select>
在测试类中添加方法
@Test
public void selectTest04() {
SqlSession session = factory.openSession();
String sqlId = "com.mybatisstudy.pojo.EmployeeMapper.findAll4";
Map map = new HashMap();
map.put("minSalary","200");
map.put("maxSalary","3000");
List<Employee> emps = session.selectList(sqlId,map);
for (Employee emp : emps) {
System.out.println(emp);
}
}
结果:
注:sql中的if标签内部,and 这个词要在句首,而不能在句尾,当mybatis在执行sql的时候,检测到前面条件没有成立,会去掉句首的and关键词,使其能够正常执行
4.3set标签
在mapper文件中插入:
<update id="updateEmpById">
update employee
<set>
<if test="name != null">name=#{name},</if>
<if test="job != null">job=#{job},</if>
<if test="salary != null">salary=#{salary}</if>
</set>
where id=#{id}
</update>
接着在测试类 中添加方法
@Test
public void updateEmpById() {
SqlSession session = factory.openSession();
String sqlId = "com.mybatisstudy.pojo.EmployeeMapper.updateEmpById";
Employee emp01 = new Employee();
emp01.setId(2);
emp01.setJob("farmer");
emp01.setName("小黄");
emp01.setSalary(2);
session.update(sqlId,emp01);
session.commit();
}
执行后,去数据库查询
注:sql中的if标签内部, 逗号要在句尾,而不能在句首,当mybatis在执行sql的时候,检测到后面条件没有成立,会去掉句尾的逗号,使其能够正常执行
4.4foreach标签
foreach标签用于多次的检索或者执行,在mapper中添加如下:
<select id="findByIds"
resultType="com.mybatisstudy.pojo.Employee">
select * from employee where id in
<foreach collection="array" open="(" close=")" item="ids"
separator=",">
#{ids}
</foreach>
</select>
注:foreach标签内的item和下方的占位符内的元素要一致,否则不会正常进行
接着我们要在测试类中添加方法
@Test
public void findByIds() {
SqlSession session = factory.openSession();
String sqlId = "com.mybatisstudy.pojo.EmployeeMapper.findByIds";
Integer[] id = {1,2};
List<Employee> emps = session.selectList(sqlId,id);
for (Employee emp : emps) {
System.out.println(emp);
}
}
将要查询的数组封装到id的里就能正确查询了
五、总结
占位符和动态sql的联合使用会使我们简化代码,并且更清晰明了,成熟使用减少很多不必要的工作。我还是比较喜欢使用动态sql的。。。