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','杰克','男',30,'15012345678',5000,'1');
INSERT INTO tb_employee(loginname,PASSWORD,NAME,sex,age,phone,sal,state)
VALUES('rose','123456','露丝','女',28,'135612345678',4000,'1');

 2.创建实体
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.HashMap;
import java.util.List;
import org.fkit.domain.Employee;
public interface EmployeeMapper {
List<Employee> selectEmployeeByIdLike(HashMap<String, Object> params);
List<Employee> selectEmployeeByLoginLike(HashMap<String, Object> params);
List<Employee> selectEmployeeChoose(HashMap<String, Object> params);
List<Employee> findEmployeeLike(HashMap<String, Object> params);
List<Employee> selectEmployeeLike(HashMap<String, Object> params);
Employee selectEmployeeWithId(Integer id);
void updateEmployeeIfNecessary(Employee employee);
List<Employee> selectEmployeeIn(List<Integer> ids);
List<Employee> selectEmployeeLikeName(Employee employee);
}

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">
<!-- namespace指用户自定义的命名空间。 -->
<mapper namespace="org.fkit.mapper.EmployeeMapper"> <select id="selectEmployeeWithId" parameterType="int" resultType="org.fkit.domain.Employee">
SELECT * FROM tb_employee where id = #{id}
</select> <!-- if -->
<select id="selectEmployeeByIdLike"
resultType="org.fkit.domain.Employee">
SELECT * FROM tb_employee WHERE state = '1'
<!-- 可选条件,如果传进来的参数有id属性,则加上id查询条件 -->
<if test="id != null ">
and id = #{id}
</if>
</select> <!-- if -->
<select id="selectEmployeeByLoginLike"
resultType="org.fkit.domain.Employee">
SELECT * FROM tb_employee WHERE state = '1'
<!-- 两个可选条件,例如登录功能的登录名和密码查询 -->
<if test="loginname != null and password != null">
and loginname = #{loginname} and password = #{password}
</if>
</select> <!-- choose(when、otherwise) -->
<select id="selectEmployeeChoose"
parameterType="hashmap"
resultType="org.fkit.domain.Employee">
SELECT * FROM tb_employee WHERE state = '1'
<!-- 如果传入了id,就根据id查询,没有传入id就根据loginname和password查询,否则查询sex等于男的数据 -->
<choose>
<when test="id != null">
and id = #{id}
</when>
<when test="loginname != null and password != null">
and loginname = #{loginname} and password = #{password}
</when>
<otherwise>
and sex = '男'
</otherwise>
</choose>
</select> <select id="findEmployeeLike"
resultType="org.fkit.domain.Employee">
SELECT * FROM tb_employee WHERE
<if test="state != null ">
state = #{state}
</if>
<if test="id != null ">
and id = #{id}
</if>
<if test="loginname != null and password != null">
and loginname = #{loginname} and password = #{password}
</if>
</select> <!-- where -->
<select id="selectEmployeeLike"
resultType="org.fkit.domain.Employee">
SELECT * FROM tb_employee
<where>
<if test="state != null ">
state = #{state}
</if>
<if test="id != null ">
and id = #{id}
</if>
<if test="loginname != null and password != null">
and loginname = #{loginname} and password = #{password}
</if>
</where>
</select> <!-- set -->
<update id="updateEmployeeIfNecessary"
parameterType="org.fkit.domain.Employee">
update tb_employee
<set>
<if test="loginname != null">loginname=#{loginname},</if>
<if test="password != null">password=#{password},</if>
<if test="name != null">name=#{name},</if>
<if test="sex != null">sex=#{sex},</if>
<if test="age != null">age=#{age},</if>
<if test="phone != null">phone=#{phone},</if>
<if test="sal != null">sal=#{sal},</if>
<if test="state != null">state=#{state}</if>
</set>
where id=#{id}
</update> <!-- foreach -->
<select id="selectEmployeeIn" resultType="org.fkit.domain.Employee">
SELECT *
FROM tb_employee
WHERE ID in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select> <!-- bind -->
<select id="selectEmployeeLikeName" resultType="org.fkit.domain.Employee">
<bind name="pattern" value="'%' + _parameter.getName() + '%'" />
SELECT * FROM tb_employee
WHERE loginname LIKE #{pattern}
</select>
</mapper>
知识点描述:
(1).if
if用来判断字段是否有值,值是否为空,或者判断一些值不会让sql语句出错等
<!-- if -->
<select id="selectEmployeeByIdLike"
resultType="org.fkit.domain.Employee">
SELECT * FROM tb_employee WHERE state = '1'
<!-- 可选条件,如果传进来的参数有id属性,则加上id查询条件 -->
<if test="id != null ">
and id = #{id}
</if>
</select> <!-- if -->
<select id="selectEmployeeByLoginLike"
resultType="org.fkit.domain.Employee">
SELECT * FROM tb_employee WHERE state = '1'
<!-- 两个可选条件,例如登录功能的登录名和密码查询 -->
<if test="loginname != null and password != null">
and loginname = #{loginname} and password = #{password}
</if>
</select>

(2).choose(when、otherwise)
有时候,我们不想用所有的条件语句,而只想从中选择其一二,对与这种情况,mybatis提供了chooose元素,它有点像java中的switch。

<!-- choose(when、otherwise) -->
<select id="selectEmployeeChoose"
parameterType="hashmap"
resultType="org.fkit.domain.Employee">
SELECT * FROM tb_employee WHERE state = '1'
<!-- 如果传入了id,就根据id查询,没有传入id就根据loginname和password查询,否则查询sex等于男的数据 -->
<choose>
<when test="id != null">
and id = #{id}
</when>
<when test="loginname != null and password != null">
and loginname = #{loginname} and password = #{password}
</when>
<otherwise>
and sex = '男'
</otherwise>
</choose>
</select>

(3).where

 <!-- where -->
<select id="selectEmployeeLike"
resultType="org.fkit.domain.Employee">
SELECT * FROM tb_employee
<where>
<if test="state != null ">
state = #{state}
</if>
<if test="id != null ">
and id = #{id}
</if>
<if test="loginname != null and password != null">
and loginname = #{loginname} and password = #{password}
</if>
</where>
</select>

(4).set

动态更新语句使用set元素,set元素可以被用于动态包含需要更新字段。
<!-- set -->
<update id="updateEmployeeIfNecessary"
parameterType="org.fkit.domain.Employee">
update tb_employee
<set>
<if test="loginname != null">loginname=#{loginname},</if>
<if test="password != null">password=#{password},</if>
<if test="name != null">name=#{name},</if>
<if test="sex != null">sex=#{sex},</if>
<if test="age != null">age=#{age},</if>
<if test="phone != null">phone=#{phone},</if>
<if test="sal != null">sal=#{sal},</if>
<if test="state != null">state=#{state}</if>
</set>
where id=#{id}
</update>

(5).foreach

对一个集合操作的时间使用,通常发生在构建in条件语句时。

<!-- foreach -->
<select id="selectEmployeeIn" resultType="org.fkit.domain.Employee">
SELECT *
FROM tb_employee
WHERE ID in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select>

(6).bind
bind元素可以从ognl表达式中创建一个变量并将其绑定到上下文中。

 <!-- bind -->
<select id="selectEmployeeLikeName" resultType="org.fkit.domain.Employee">
<bind name="pattern" value="'%' + _parameter.getName() + '%'" />
SELECT * FROM tb_employee
WHERE loginname LIKE #{pattern}
</select>

4.mybatis-config.xml

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>
<!-- 指定 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/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!-- mappers告诉了MyBatis去哪里找持久化类的映射文件 -->
<mappers>
<mapper resource="org/fkit/mapper/EmployeeMapper.xml"/>
</mappers>
</configuration>

5.测试

package org.fkit.test;
import java.io.InputStream;
import java.util.ArrayList;
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; public class DynamicSQLTest {
public static void main(String[] args) throws Exception {
// 读取mybatis-config.xml文件
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
// 初始化mybatis,创建SqlSessionFactory类的实例
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(inputStream);
// 创建Session实例
SqlSession session = sqlSessionFactory.openSession();
DynamicSQLTest t = new DynamicSQLTest();
t.testSelectEmployeeByIdLike(session);
//t.testSelectEmployeeByLoginLike(session);
//t.testSelectEmployeeChoose(session);
//t.testFindEmployeeLike(session);
//t.testSelectEmployeeLike(session);
//t.testUpdateEmployeeIfNecessary(session);
//t.testSelectEmployeeIn(session);
//t.testSelectEmployeeLikeName(session);
// 提交事务
session.commit();
// 关闭Session
session.close();
} // 测试<select id="selectEmployeeByIdLike" ...>
public void testSelectEmployeeByIdLike(SqlSession session){
// 获得EmployeeMapper接口的代理对象
EmployeeMapper em = session.getMapper(EmployeeMapper.class);
// 创建一个HashMap存储参数
HashMap<String, Object> params = new HashMap<String, Object>();
// 设置id属性
//params.put("id", 1);
// 调用EmployeeMapper接口的selectEmployeeByIdLike方法
List<Employee> list = em.selectEmployeeByIdLike(params);
// 查看返回结果
list.forEach(employee -> System.out.println(employee));
} public void testSelectEmployeeByLoginLike(SqlSession session){
EmployeeMapper em = session.getMapper(EmployeeMapper.class);
HashMap<String, Object> params = new HashMap<String, Object>();
// 设置loginname和password属性
params.put("loginname", "jack");
params.put("password", "123456");
List<Employee> list = em.selectEmployeeByLoginLike(params);
list.forEach(employee -> System.out.println(employee));
} public void testSelectEmployeeChoose(SqlSession session){
EmployeeMapper em = session.getMapper(EmployeeMapper.class);
HashMap<String, Object> params = new HashMap<String, Object>();
// 设置id属性
// params.put("id", 1);
// params.put("loginname", "jack");
// params.put("password", "123456");
List<Employee> list = em.selectEmployeeChoose(params);
list.forEach(employee -> System.out.println(employee));
} public void testFindEmployeeLike(SqlSession session){
EmployeeMapper em = session.getMapper(EmployeeMapper.class);
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("id", 1);
List<Employee> list = em.findEmployeeLike(params);
list.forEach(employee -> System.out.println(employee));
} public void testSelectEmployeeLike(SqlSession session){
EmployeeMapper em = session.getMapper(EmployeeMapper.class);
HashMap<String, Object> params = new HashMap<String, Object>();
// 设置state属性和id属性
params.put("id", 1);
params.put("loginname", "jack");
params.put("password", "123456");
List<Employee> list = em.selectEmployeeLike(params);
list.forEach(employee -> System.out.println(employee));
} public void testUpdateEmployeeIfNecessary(SqlSession session){
EmployeeMapper em = session.getMapper(EmployeeMapper.class);
Employee employee = em.selectEmployeeWithId(4);
// 设置需要修改的属性
employee.setLoginname("mary");
employee.setPassword("123");
employee.setName("玛丽");
em.updateEmployeeIfNecessary(employee);
} public void testSelectEmployeeIn(SqlSession session){
EmployeeMapper em = session.getMapper(EmployeeMapper.class);
// 创建List集合
List<Integer> ids = new ArrayList<Integer>();
// 往List集合中添加两个测试数据
ids.add(1);
ids.add(2);
List<Employee> list = em.selectEmployeeIn(ids);
list.forEach(employee -> System.out.println(employee));
} public void testSelectEmployeeLikeName(SqlSession session){
EmployeeMapper em = session.getMapper(EmployeeMapper.class);
Employee employee = new Employee();
// 设置模糊查询的参数
employee.setName("o");
List<Employee> list = em.selectEmployeeLikeName(employee);
list.forEach(result -> System.out.println(result));
}
}

05—动态sql的更多相关文章

  1. [05] 动态SQL

    MyBatis的强大特性之一就是它的动态SQL,它可以根据不同的条件动态地组成SQL语句进行执行.为此,MyBatis提供了一系列强大的表达式,本章将就此进行学习,主要内容直接参考的是官方文档< ...

  2. 游标、动态sql、异常

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAlIAAAFeCAIAAADBl2bCAAAgAElEQVR4nOyddXgU197H12OEELxIkV

  3. mybatis——动态sql

    MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑. MyBatis中用于实现动态SQL的元素主要有: if choose(when,otherwise) ...

  4. IBATIS动态SQL

    转自:http://www.cnblogs.com/phoebus0501/archive/2011/05/16/2048126.html 直接使用JDBC一个非常普遍的问题就是动态SQL.使用参数值 ...

  5. 动态游标(例如表名作为参数)以及动态SQL分析

    表名作为参数的动态游标 DECLARE v_table_name VARCHAR2(30) := 'CUX_MES_WIP_BARCODE_MAP'; --l_rec SYS_REFCURSOR; T ...

  6. db2存储过程动态sql被截断

    编写存储过程,使用动态sql时,调试时发现变量赋值后被截断. 关键代码如下: 实现的效果是先把上下游做对比的sql语句和相关参数存入RKDM_DATA_VOID_RULE, 执行存储过程后把两个sql ...

  7. (2.3)DDL增强功能-流程化控制与动态sql

    1.流程控制 在T-SQL中,与流程控制语句相关的关键字有8个: BEGIN...END BREAK GOTO CONTINUE IF...ELSE WHILE RETURN WAITFOR 其实还可 ...

  8. (转)Oracle中动态SQL详解

    本文转载自:http://www.cnblogs.com/gaolonglong/archive/2011/05/31/2064790.html 1.静态SQLSQL与动态SQL Oracle编译PL ...

  9. 使用Oracle的DBMS_SQL包执行动态SQL语句

    引用自:http://blog.csdn.net/ggjjzhzz/archive/2005/10/17/507880.aspx 在某些场合下,存储过程或触发器里的SQL语句需要动态生成.Oracle ...

随机推荐

  1. 最新 易车java校招面经 (含整理过的面试题大全)

    从6月到10月,经过4个月努力和坚持,自己有幸拿到了网易雷火.京东.去哪儿.易车等10家互联网公司的校招Offer,因为某些自身原因最终选择了易车.6.7月主要是做系统复习.项目复盘.LeetCode ...

  2. Docker pull php:7.1-fpm的php.ini配置修改

    今天,换了 Deepin 操作系统,开发环境是通过 Docker 搭建的,具体结构如下: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES e ...

  3. MapReduce 框架原理

    1. Hadoop 序列化 1.1 自定义Bean对象实现序列化接口 必须实现 Writable 接口: 反序列化时,需要反射调用空参构造函数,所以必须有空参构造: 重写序列化方法: 重写反序列化方法 ...

  4. bootstrap-table删除指定行注意事项

    方法有两种: 1.使用官方文档的数据(反正我试了2个小时都不行,如有大神请指导下):使用events和operate相结合的方式 2.不使用events,在formatter里面定义事件的实现. 上面 ...

  5. tabs 导航 及内容切换

    <!-- 导航头 --> <div class="col-md-6" style="padding: 0px"> <ul id=& ...

  6. .Net Core 3.0原生Json解析器

    微软官方博客中描述了为什么构造了全新的Json解析器而不是继续使用行业准则Json.Net 微软博客地址:https://devblogs.microsoft.com/dotnet/try-the-n ...

  7. 创建安全的 Netty 程序

    1.使用 SSL/TLS 创建安全的 Netty 程序 SSL 和 TLS 是众所周知的标准和分层的协议,它们可以确保数据时私有的 Netty提供了SSLHandler对网络数据进行加密 使用Http ...

  8. shiro小记

    今天主要看了Shiro的认证,授权功能初步了解了一下,其他的功能用的不多,之后再看. 先说一下Shiro的三个核心概念: 1.Subject: 代表当前正在执行操作的用户,但Subject代表的可以是 ...

  9. 剑指offer14:输入一个链表,输出该链表中倒数第k个结点。

    1. 题目描述 输入一个链表,输出该链表中倒数第k个结点. 2. 思路和方法 可以用两个指针,一个指针遍历到第k个结点的时候,第二个指针再走到第一个节点,然后两个指针的距离始终保持k-1.这样,当第一 ...

  10. python如何切割字符串

    python字符串的分割方法如下 str.split():字符串分割函数 通过指定分隔符对字符串进行切片,并返回分割后的字符串列表. 语法: str.split(s, num)[n] 参数说明: s: ...