说明:本文仅设置<where> 、<if>、<choose>、<set>。通过查询和更新来演示
==================================================
1.项目结构
2.pom.xml(本来这里添加Junit依赖的,然后不知道为什一下可以一下不行,所以也没有去深究,直接在项目中添加Junit支持,方便测试。。)
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.lin</groupId>
<artifactId>DynamicSQLTest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<!-- Mybatis begin -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.3.1</version>
</dependency>
<!-- MyBatis end -->
<!-- mysql begin -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
<!-- mysql end -->
<!-- 日志文件管理包 -->
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- log end -->
<!-- Junit begin -->
<!-- <dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.4</version>
</dependency> -->
<!-- Junit end -->
</dependencies>
<!-- 添加项目jdk编译插件 -->
<build>
<!-- 设置编译版本为1.8 -->
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<!-- 配置tomcat7的插件,如果使用maven的命令方式运行,则命令为:tomcat7:run ,
而不能是tomcat:run(如果使用该命令,还是会使用maven默认的tomcat来编译运行项目)。
可以直接使用eclipse中的tomcat来运行项目(就是原先没有使用maven时的那样运行项目就可以了,那样的话也不需要配这个插件了)。
-->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
</plugin>
</plugins>
</build>
</project>
3.mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- XML 配置文件包含对 MyBatis 系统的核心设置 -->
<configuration>
<!-- 指定 MyBatis 所用日志的具体实现 -->
<settings>
<setting name="logImpl" value="LOG4J"/>
<!-- 要使延迟加载生效必须配置下面两个属性 -->
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
<environments default="mysql">
<!-- 环境配置,即连接的数据库。 -->
<environment id="mysql">
<!-- 指定事务管理类型,type="JDBC"指直接简单使用了JDBC的提交和回滚设置 -->
<transactionManager type="JDBC"/>
<!-- dataSource指数据源配置,POOLED是JDBC连接对象的数据源连接池的实现。 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/maven"/>
<property name="username" value="root"/>
<property name="password" value="546784"/>
</dataSource>
</environment>
</environments>
<!-- mappers告诉了MyBatis去哪里找持久化类的映射文件 -->
<mappers>
<package name="org.fkit.mapper"/>
</mappers>
</configuration>
3.实体类Employee.java 和SQL脚本语句
/**
*
* SQL脚本:
*
CREATE TABLE tb_employee (
ID INT(11) PRIMARY KEY AUTO_INCREMENT,
loginname VARCHAR(18),
PASSWORD VARCHAR(18),
NAME VARCHAR(18) DEFAULT NULL,
SEX CHAR(2) DEFAULT NULL,
AGE INT(11) DEFAULT NULL,
phone VARCHAR(21),
sal DOUBLE,
state VARCHAR(18)
)
INSERT INTO tb_employee(loginname,PASSWORD,NAME,sex,age,phone,sal,state)
VALUES('jack','123456','杰克','男',26,'13902019999',9800,'ACTIVE');
INSERT INTO tb_employee(loginname,PASSWORD,NAME,sex,age,phone,sal,state)
VALUES('rose','123456','露丝','女',21,'13902018888',6800,'ACTIVE');
* */
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id; // 主键id
private String loginname; // 登录名
private String password; // 密码
private String name; // 真实姓名
private String sex; // 性别
private Integer age; // 年龄
private String phone; // 电话
private Double sal; // 薪水
private String state; // 状态
//省略set和get方法……
public String toString() {
return "Employee [id=" + id + ", loginname=" + loginname
+ ", password=" + password + ", name=" + name + ", sex=" + sex
+ ", age=" + age + ", phone=" + phone + ", sal=" + sal
+ ", state=" + state + "]";
}
}
4.EmployeeMapper.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="org.fkit.mapper.EmployeeMapper">
<select id="selectEmployeeByIdLike" resultType="org.fkit.domain.Employee">
select * from tb_employee
<where>
state = 'ACTIVE'
<!--
如果传入了id,就根据id查询;没有传入id就根据loginname和password查询;否则查询sex等于男的数据。
-->
<choose>
<when test="id!=null and id!=''">
and id = #{id}
</when>
<when test="loginname!=null and loginname!='' and password!=null and password!=''">
and loginname = #{loginname} and password = #{password}
</when>
<otherwise>
and sex = '男'
</otherwise>
</choose>
</where>
<!-- where和if测试的方式一
<where>
<if test="state!=null and state!=''">
state = 'ACTIVE'
</if>
<if test="id!=null and id!=''">
and id = #{id}
</if>
</where>
-->
<!-- where和if测试的方式二
<where>
<if test="state!=null and state!='' and id!=null and id!=''">
and state = 'ACTIVE'and id = #{id}
</if>
</where>
-->
</select>
<!-- 根据id查询Employee信息(因为一般在执行更新操作时会先查出用户信息,此处模拟) -->
<select id="selectEmployeeWithId" parameterType="int" resultType="org.fkit.domain.Employee">
select * from tb_employee
where id = #{id}
</select>
<!-- 动态更新员工信息 -->
<update id="updateEmployeeIfNecessary" parameterType="org.fkit.domain.Employee">
update tb_employee
<set>
<if test="loginname!=null and loginname!=''">
loginname = #{loginname},
</if>
<if test="password!=null and password!=''">
password = #{password},
</if>
<if test="name!=null and name!=''">
name = #{name},
</if>
<if test="sex!=null and sex!=''">
sex = #{sex},
</if>
<if test="age!=null and age!=''">
age = #{age},
</if>
<if test="phone!=null and phone!=''">
phone = #{phone},
</if>
<if test="sal!=null and sal!=''">
sal = #{sal},
</if>
<if test="state!=null and state!=''">
state = #{state},
</if>
</set>
<!-- <where>
<if test="id!=null and id!=''">
id = #{id}
</if>
</where> -->
where
id=#{id}
</update>
</mapper>
5.EmployeeMapper.java
package org.fkit.mapper;
import java.util.HashMap;
import java.util.List;
import org.fkit.domain.Employee;
public interface EmployeeMapper {
public List<Employee> selectEmployeeByIdLike(HashMap<String, Object>params);
public Employee selectEmployeeWithId(int id);
public void updateEmployeeIfNecessary(Employee e);
}
6.测试类DynamicSQLTest.java
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
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.fkit.domain.Employee;
import org.fkit.mapper.EmployeeMapper;
import org.junit.Test;
public class DynamicSQLTest {
//SQL动态查询操作
@Test
public void selectTest() throws Exception{
//读取mybatis-config.xml文件
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
//初始化mybatis,创建SQLSessionFactory类的实例
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//创建SqlSession实例
SqlSession sqlSession = sqlSessionFactory.openSession();
DynamicSQLTest d = new DynamicSQLTest();
d.testSelectEmployeeByIdLike(sqlSession);
//提交事务
sqlSession.commit();
//关闭session
sqlSession.close();
}
public void testSelectEmployeeByIdLike(SqlSession session){
//获得EmployeeMapper接口的代理对象
EmployeeMapper em = session.getMapper(EmployeeMapper.class);
//创建一个HashMap存储参数
HashMap<String,Object> params = new HashMap<String,Object>();
/**以下用于单独测试where标签使用*/
// //设置id属性
// params.put("id", 1);
// //设置state属性
// params.put("state", "ACTIVE");
/**以下用于单独测试choose标签使用*/
params.put("id", 1);
params.put("loginname", "jack");
params.put("password", "123456");
//调用EmployeeMapper接口的selectEmployeeByIdLike方法
List<Employee> list = em.selectEmployeeByIdLike(params);
//查看结果
list.forEach(employee -> System.out.println(employee));
}
//动态SQL更新操作
@Test
public void updateTest() throws Exception{
//读取mybatis-config.xml文件
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
//初始化mybatis,创建SQLSessionFactory类的实例
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//创建SqlSession实例
SqlSession sqlSession = sqlSessionFactory.openSession();
DynamicSQLTest d = new DynamicSQLTest();
d.testUpdateEmployee(sqlSession);
//提交事务
sqlSession.commit();
//关闭session
sqlSession.close();
}
public void testUpdateEmployee(SqlSession sqlSession){
EmployeeMapper em = sqlSession.getMapper(EmployeeMapper.class);
//查询id为4的员工信息
Employee employee = em.selectEmployeeWithId(4);
System.out.println(employee);
//设置需要修改的属性
employee.setLoginname("Mary");
employee.setPassword("123");
employee.setName("玛丽");
//更新员工信息
em.updateEmployeeIfNecessary(employee);
//查询id为4的员工信息
Employee employee2 = em.selectEmployeeWithId(4);
System.out.println(employee2);
}
}
--------------------------------------------------------------
--------------------------------------------------------------
测试运行,以下是动态更新操作