动态sql
mybatis的注解也支持动态sql。mybatis提供了各种注解,如@InsertProvider、@UpdateProvider、@DeleteProvider和@SelectProvider,来帮助构建动态sql语句,然后mybatis可以执行这些sql语句。
以上4个Provider注解都有type属性,该属性指定了一个类。method属性指定该类的方法,其用来提供需要执行的sql语句。使用字符串拼接的方法构建sql语句是非常困难的,并且用以出错。所以mybatis提供了一个sql工具类org.apache.ibatis.jdbc.SQL,该类不使用字符串拼接的方式,并且会以合适的空格前缀和后缀来构造sql语句。
sql类的常用方法如下:
T Select(String columns):开始或追加select 子句,参数通常是一个逗号分割的列表的列。
T From(String table):启动或追加from子句。可以调用超过一次,这些参数通常是一个表名。
T JOIN(String join):向JOIN子句添加一个新的查询条件,该参数通常昌一个表,也可以包括一个标准的连接返回的结果集。
T INNER_JOIN(String join):同JOIN子句,连接方式是内连接(INNER_JOIN)
T LEFT_OUTER_JOIN(String join):同JOIN子句,连接方式是左外连接(LEFT_OUTER_JOIN)
T RIGHT_OUTER_JOIN(String join):同JOIN子句,连接方式是右外连接(RIGHT_OUTER_JOIN)
T WHERE(String conditions):追加一个新的where子句条件,可以多次调用。
T OR():使用OR拆分当前where子句条件,可以不止一次被调用。
T AND():使用AND拆分当前where子句条件,可以不止一次被调用。
T GROUP_BY(String columns):追加一个新的GROUP BY子句元素。
T HAVING(String columns):追加一个新的HAVING子句条件。
T ORDER_BY(String columns):追加一个新的ORDER BY子句元素。
T INSERT_INTO(String tableName):启动INSERT语句插入到指定表,应遵循由一个或多个VALUES()调用。
T VALUES(String columns,String values):追加的INSERT语句,第一个参数是要插入的列,第二个参数是插入的值。
T DELETE_FROM(String table):启动delete语句,并指定表删除。
T UPDATE(string table):启动一个更新(UPDATE)语句,并指定表更新。
T SET(String sets):追加一个更新语句set列表。
下面看看例子:
1.创建表
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');
2.创建model
Employee.java
package org.fkit.domain;
import java.io.Serializable;
public class Employee implements Serializable {
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; // 状态
public Employee() {
super();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLoginname() {
return loginname;
}
public void setLoginname(String loginname) {
this.loginname = loginname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Double getSal() {
return sal;
}
public void setSal(Double sal) {
this.sal = sal;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
@Override
public String toString() {
return "data [id=" + id + ", loginname=" + loginname
+ ", password=" + password + ", name=" + name + ", sex=" + sex
+ ", age=" + age + ", phone=" + phone + ", sal=" + sal
+ ", state=" + state + "]";
}
}
3.mapper
EmployeeMapper.java
package org.fkit.mapper;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.DeleteProvider;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.annotations.UpdateProvider;
import org.fkit.domain.Employee;
public interface EmployeeMapper {
// 动态查询
@SelectProvider(type=EmployeeDynaSqlProvider.class,method="selectWhitParam")
List<Employee> selectWhitParam(Map<String, Object> param);
// 动态插入
@InsertProvider(type=EmployeeDynaSqlProvider.class,method="insertEmployee")
@Options(useGeneratedKeys = true, keyProperty = "id")
int insertEmployee(Employee employee);
// 根据id查询
@SelectProvider(type=EmployeeDynaSqlProvider.class,method="selectWhitParam")
Employee selectEmployeeWithId(Map<String, Object> param);
// 动态更新
@UpdateProvider(type=EmployeeDynaSqlProvider.class,method="updateEmployee")
void updateEmployee(Employee employee);
// 动态删除
@DeleteProvider(type=EmployeeDynaSqlProvider.class,method="deleteEmployee")
void deleteEmployee(Map<String, Object> param);
}
EmployeeDynaSqlProvider.java
package org.fkit.mapper;
import java.util.Map;
import org.apache.ibatis.jdbc.SQL;
import org.fkit.domain.Employee;
public class EmployeeDynaSqlProvider {
public String selectWhitParam(Map<String, Object> param){
return new SQL(){
{
SELECT("*");
FROM("tb_employee");
if(param.get("id") != null){
WHERE(" id = #{id} ");
}
if(param.get("loginname") != null){
WHERE(" loginname = #{loginname} ");
}
if(param.get("password") != null){
WHERE("password = #{password}");
}
if(param.get("name")!= null){
WHERE("name = #{name}");
}
if(param.get("sex")!= null){
WHERE("sex = #{sex}");
}
if(param.get("age")!= null){
WHERE("age = #{age}");
}
if(param.get("phone")!= null){
WHERE("phone = #{phone}");
}
if(param.get("sal")!= null){
WHERE("sal = #{sal}");
}
if(param.get("state")!= null){
WHERE("state = #{state}");
}
}
}.toString();
}
public String insertEmployee(Employee employee){
return new SQL(){
{
INSERT_INTO("tb_employee");
if(employee.getLoginname() != null){
VALUES("loginname", "#{loginname}");
}
if(employee.getPassword() != null){
VALUES("password", "#{password}");
}
if(employee.getName()!= null){
VALUES("name", "#{name}");
}
if(employee.getSex()!= null){
VALUES("sex", "#{sex}");
}
if(employee.getAge()!= null){
VALUES("age", "#{age}");
}
if(employee.getPhone()!= null){
VALUES("phone", "#{phone}");
}
if(employee.getSal()!= null){
VALUES("sal", "#{sal}");
}
if(employee.getState()!= null){
VALUES("state", "#{state}");
}
}
}.toString();
}
public String updateEmployee(Employee employee){
return new SQL(){
{
UPDATE("tb_employee");
if(employee.getLoginname() != null){
SET("loginname = #{loginname}");
}
if(employee.getPassword() != null){
SET("password = #{password}");
}
if(employee.getName()!= null){
SET("name = #{name}");
}
if(employee.getSex()!= null){
SET("sex = #{sex}");
}
if(employee.getAge()!= null){
SET("age = #{age}");
}
if(employee.getPhone()!= null){
SET("phone = #{phone}");
}
if(employee.getSal()!= null){
SET("sal = #{sal}");
}
if(employee.getState()!= null){
SET("state = #{state}");
}
WHERE(" id = #{id} ");
}
}.toString();
}
public String deleteEmployee(Map<String, Object> param){
return new SQL(){
{
DELETE_FROM("tb_employee");
if(param.get("id") != null){
WHERE(" id = #{id} ");
}
if(param.get("loginname") != null){
WHERE(" loginname = #{loginname} ");
}
if(param.get("password") != null){
WHERE("password = #{password}");
}
if(param.get("name")!= null){
WHERE("name = #{name}");
}
if(param.get("sex")!= null){
WHERE("sex = #{sex}");
}
if(param.get("age")!= null){
WHERE("age = #{age}");
}
if(param.get("phone")!= null){
WHERE("phone = #{phone}");
}
if(param.get("sal")!= null){
WHERE("sal = #{sal}");
}
if(param.get("state")!= null){
WHERE("state = #{state}");
}
}
}.toString();
}
}
4.mybatis-config.xml
db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/mybatis
username=root
password=root
log4j.properties
# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.org.fkit.mapper.EmployeeMapper=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
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>
<properties resource="db.properties"/>
<!-- 指定 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="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!-- mappers告诉了MyBatis去哪里找持久化类的映射文件 -->
<mappers>
<mapper class="org.fkit.mapper.EmployeeMapper"/>
</mappers>
</configuration>
5.测试
FKSqlSessionFactory.java
package org.fkit.factory;
import java.io.InputStream;
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 FKSqlSessionFactory {
private static SqlSessionFactory sqlSessionFactory = null;
// 初始化创建SqlSessionFactory对象
static{
try {
// 读取mybatis-config.xml文件
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(inputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
// 获取SqlSession对象的静态方法
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
// 获取SqlSessionFactory的静态方法
public static SqlSessionFactory getSqlSessionFactory() {
return sqlSessionFactory;
}
}
DynamicSQLTest.java
package org.fkit.test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import org.fkit.domain.Employee;
import org.fkit.factory.FKSqlSessionFactory;
import org.fkit.mapper.EmployeeMapper;
public class DynamicSQLTest {
public static void main(String[] args) throws Exception {
// 创建Session实例
SqlSession session = FKSqlSessionFactory.getSqlSession();
DynamicSQLTest t = new DynamicSQLTest();
// 获取EmployeeMapper对象
EmployeeMapper em = session.getMapper(EmployeeMapper.class);
// t.testSelectWhitParam(em);
// t.testInsertEmployee(em);
// t.testUpdateEmployee(em);
t.testDeleteEmployee(em);
// 提交事务
session.commit();
// 关闭Session
session.close();
}
// 根据动态参数查询员工数据
public void testSelectWhitParam(EmployeeMapper em){
// 使用Map装载参数
Map<String, Object> param = new HashMap<String, Object>();
param.put("loginname", "jack");
param.put("password", "123456");
// 调用selectWhitParam方法
List<Employee> list = em.selectWhitParam(param);
// 查看返回结果
System.out.println(list);
}
// 根据设置的属性动态插入数据
public void testInsertEmployee(EmployeeMapper em){
Employee e = new Employee();
e.setLoginname("mary");
e.setPassword("123456");
e.setName("玛丽");
e.setSex("女");
e.setAge(20);
e.setPhone("13902019999");
e.setSal(9800.99);
// 注意:没有设置state属性,则insert语句中不会包含state列
// e.setState("ACTIVE");
em.insertEmployee(e);
System.out.println("插入成功,返回id:" + e.getId());
}
// 根据设置的属性动态更新数据
public void testUpdateEmployee(EmployeeMapper em){
// 使用Map装载参数
Map<String, Object> param = new HashMap<String, Object>();
param.put("id", 5);
// 查询id为1的员工
Employee e = em.selectEmployeeWithId(param);
// 修改员工对象的三个属性
e.setLoginname("update");
e.setPassword("fkjava");
e.setName("测试");
// 动态更新
em.updateEmployee(e);
}
// 根据设置的属性动态删除数据
public void testDeleteEmployee(EmployeeMapper em){
// 使用Map装载参数
Map<String, Object> param = new HashMap<String, Object>();
param.put("loginname", "jack");
param.put("password", "123456");
// 动态删除
em.deleteEmployee(param);
}
}
结果:
DEBUG [main] - ==> Preparing: SELECT * FROM tb_employee WHERE ( loginname = ? AND password = ?)
DEBUG [main] - ==> Parameters: jack(String), 123456(String)
DEBUG [main] - <== Total: 1
[data [id=1, loginname=jack, password=123456, name=杰克, sex=男, age=30, phone=15012345678, sal=5000.0, state=1]]