05—动态sql
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>
<!-- 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 -->
<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的更多相关文章
- [05] 动态SQL
MyBatis的强大特性之一就是它的动态SQL,它可以根据不同的条件动态地组成SQL语句进行执行.为此,MyBatis提供了一系列强大的表达式,本章将就此进行学习,主要内容直接参考的是官方文档< ...
- 游标、动态sql、异常
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAlIAAAFeCAIAAADBl2bCAAAgAElEQVR4nOyddXgU197H12OEELxIkV
- mybatis——动态sql
MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑. MyBatis中用于实现动态SQL的元素主要有: if choose(when,otherwise) ...
- IBATIS动态SQL
转自:http://www.cnblogs.com/phoebus0501/archive/2011/05/16/2048126.html 直接使用JDBC一个非常普遍的问题就是动态SQL.使用参数值 ...
- 动态游标(例如表名作为参数)以及动态SQL分析
表名作为参数的动态游标 DECLARE v_table_name VARCHAR2(30) := 'CUX_MES_WIP_BARCODE_MAP'; --l_rec SYS_REFCURSOR; T ...
- db2存储过程动态sql被截断
编写存储过程,使用动态sql时,调试时发现变量赋值后被截断. 关键代码如下: 实现的效果是先把上下游做对比的sql语句和相关参数存入RKDM_DATA_VOID_RULE, 执行存储过程后把两个sql ...
- (2.3)DDL增强功能-流程化控制与动态sql
1.流程控制 在T-SQL中,与流程控制语句相关的关键字有8个: BEGIN...END BREAK GOTO CONTINUE IF...ELSE WHILE RETURN WAITFOR 其实还可 ...
- (转)Oracle中动态SQL详解
本文转载自:http://www.cnblogs.com/gaolonglong/archive/2011/05/31/2064790.html 1.静态SQLSQL与动态SQL Oracle编译PL ...
- 使用Oracle的DBMS_SQL包执行动态SQL语句
引用自:http://blog.csdn.net/ggjjzhzz/archive/2005/10/17/507880.aspx 在某些场合下,存储过程或触发器里的SQL语句需要动态生成.Oracle ...
随机推荐
- 【计算机】DMA原理2
DMA (直接存储器访问) DMA(Direct Memory Access,直接内存存取) 是所有现代电脑的重要特色,它允许不同速度的硬件装置来沟通,而不需要依赖于 CPU 的大量中断负载.否则,C ...
- spring效验
相关依赖 如果开发普通 Java 程序的的话,你需要可能需要像下面这样依赖: <dependency> <groupId>org.hibernate.validator< ...
- python 创建目录文件夹
主要涉及到三个函数 1.os.path.exists(path) 判断一个目录是否存在 2.os.makedirs(path) 多层创建目录 3.os.mkdir(path) 创建目录 DEMO 直接 ...
- [CF306C]White, Black and White Again_排列组合
White, Black and White Again 题目链接:https://www.luogu.org/problem/CF306C 数据范围:略. 题解: 记得不要看错题,容易看成来回交替下 ...
- [转载]ASP.NET Core文件上传与下载(多种上传方式)
ASP.NET Core文件上传与下载(多种上传方式) 前言 前段时间项目上线,实在太忙,最近终于开始可以研究研究ASP.NET Core了. 打算写个系列,但是还没想好目录,今天先来一篇,后面在 ...
- Hadoop和Spark的Shuffer过程对比解析
Hadoop Shuffer Hadoop 的shuffer主要分为两个阶段:Map.Reduce. Map-Shuffer: 这个阶段发生在map阶段之后,数据写入内存之前,在数据写入内存的过程就已 ...
- 使用 Mybatis-plus 进行 crud 操作
1 Mybatis-Plus简介 1.1 什么是Mybatis-Plus MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化 ...
- Codeforces Round #590 (Div. 3) Editorial
Codeforces Round #590 (Div. 3) Editorial 题目链接 官方题解 不要因为走得太远,就忘记为什么出发! Problem A 题目大意:商店有n件商品,每件商品有不同 ...
- matplotlib 画图中的basemap安装问题
在我用matplotlib画图是会用到,basemap这个库,但是直接安装却会出现问题: 使用这条安装命令就能够安装功能了: conda install -c conda-forge basemap= ...
- linux下nginx搭建
1.准备 1-1.安装 make,zlib,gcc-c++,openssl yum -y install make zlib zlib-devel gcc-c++ libtool openssl o ...