動態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]]
代碼:點擊下載