MyBatis研习录(11)——MyBatis动态SQL


C语言自学完备手册(33篇)

Android多分辨率适配框架

JavaWeb核心技术系列教程

HTML5前端开发实战系列教程

MySQL数据库实操教程(35篇图文版)

推翻自己和过往——自定义View系列教程(10篇)

走出思维困境,踏上精进之路——Android开发进阶精华录

讲给Android程序员看的前端系列教程(40集免费视频教程+源码)


版权声明

  • 本文原创作者:谷哥的小弟
  • 作者博客地址:http://blog.csdn.net/lfdfhl

概述

动态SQL是MyBatis 的强大特性,利用动态SQL可以极大的优化SQL语句的编写及其处理。

数据准备

CREATE TABLE user(
  id INT PRIMARY KEY auto_increment,
  username VARCHAR(50),
  password VARCHAR(50),
  gender VARCHAR(10)
);

INSERT INTO user(username,password,gender) VALUES("lucy","123456","female");
INSERT INTO user(username,password,gender) VALUES("momo","234567","female");
INSERT INTO user(username,password,gender) VALUES("xixi","345678","female");
INSERT INTO user(username,password,gender) VALUES("pepe","456123","female");

SELECT * FROM user;

搭建开发环境

创建普通的Java工程,结构如下:
在这里插入图片描述

User

package cn.com.pojo;
/**
 * 本文作者:谷哥的小弟 
 * 博客地址:http://blog.csdn.net/lfdfhl
 */
public class User {
	private Integer id;
	private String username;
	private String password;
	private String gender;
	public User() {
		
	}

	public User(Integer id, String username, String password, String gender) {
		super();
		this.id = id;
		this.username = username;
		this.password = password;
		this.gender = gender;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", password=" + password + ", gender=" + gender + "]";
	}
	
}

UserMapper.java

package cn.com.mapper;

import java.util.List;
import org.apache.ibatis.annotations.Param;
import cn.com.pojo.User;
/**
 * 本文作者:谷哥的小弟 
 * 博客地址:http://blog.csdn.net/lfdfhl
 */
public interface UserMapper {
	
	//测试动态SQL语句if
	public List<User> queryUserWithIf(@Param("username")String username,@Param("password")String password);
	
	//测试动态SQL语句where
	public List<User> queryUserWithWhere(@Param("username")String username,@Param("password")String password);
	
	//测试动态SQL语句choose
	public List<User> queryUserWithChoose(@Param("username")String username,@Param("password")String password);
	
	//测试动态SQL语句set
	public int updateUserWithSet(User user);
	
	//测试动态SQL语句trim
	public int updateUserWithTrim(User user);
	
	//测试动态SQL语句bind
	public List<User> queryUserWithBind(@Param("username")String username);
	
	//测试动态SQL语句foreach
	public List<User> queryUserWithForeach(@Param("userIDList")List<Integer> userIDList);
	
	//测试动态SQL语句include
	public List<User> queryUserWithInclude(@Param("username")String username,@Param("password")String password);
	
}

常用动态SQL

if

if用于进行条件判断,其test属性用于指定判断条件。

注意事项:
在test的属性值中不必再使用占位符#{ }

where

where主要用于用于管理where子句,其主要作用如下:

  • 1、如果没有where子句则不生成where关键字
  • 2、如果有where子句则自动添加where关键字
  • 3、如果where子句第一个条件中有and则将其去除

choose

choose常与when、otherwise配合使用用于分支选择,其使用方式和作用非常类似于switch case default语句。

set

set用于维护update语句中的set子句,其主要作用如下:

  • 1、满足条件时, 自动添加set关键字
  • 2、不满足条件时, 不会生成set关键字
  • 3、删除set子句中多余的逗号

trim

trim用于在SQL语句前后添加或删除一些内容,其属性作用如下:

  • 1、prefix:在SQL语句前面添加内容
  • 2、prefixOverrides:从SQL语句前面去除内容
  • 3、suffix:向SQL语句后面添加内容
  • 4、suffixOverrides:从SQL语句后面去除内容

bind

bind用于对数据进行再加工,常用于模糊查询。

foreach

foreach用于在SQL语句中遍历集合参数,常在in查询中使用;,其属性作用如下:

  • 1、collection:设置待遍历集合
  • 2、open:设置开始符号
  • 3、item:迭代变量
  • 4、separator:分隔符
  • 5、close:设置结束符号

include

include常与sql配合使用;其中,sql抽取公用SQL语句include引用该语句。

UserMapper.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="cn.com.mapper.UserMapper">	

  <!-- 测试动态SQL语句if -->
  <select id="queryUserWithIf" resultType="cn.com.pojo.User">
    select * from user where 1=1
    <if test="username !=null and username !=''">
       and username=#{username}
    </if>
    <if test="password !=null and password !=''">
       and password=#{password}
    </if>
  </select>
  
  <!-- 测试动态SQL语句where -->
  <select id="queryUserWithWhere" resultType="cn.com.pojo.User">
    select * from user
    <where>
	    <if test="username !=null and username !=''">
	       and username=#{username}
	    </if>
	    <if test="password !=null and password !=''">
	       and password=#{password}
	    </if>
    </where>
  </select>
  
  <!-- 测试动态SQL语句choose -->
  <select id="queryUserWithChoose" resultType="cn.com.pojo.User">
    select * from user
    <where>
	    <choose>
		    <when test="username !=null and username !=''">
		       and username=#{username}
		    </when>
		    <when test="password !=null and password !=''">
		       and password=#{password}
		    </when>
		    <otherwise>
		       and username like concat('%','lu','%')
		    </otherwise>
	    </choose>
    </where>
  </select>
  
  <!-- 测试动态SQL语句set -->
  <update id="updateUserWithSet" parameterType="cn.com.pojo.User">
    update user 
    <set>
       <if test="username !=null and username !=''">
	       username=#{username},
	   </if>
	   <if test="password !=null and password !=''">
	       password=#{password},
	   </if>
	   <if test="gender !=null and gender !=''">
	       gender=#{gender}
	   </if>
    </set>
    where id=#{id}
  </update>
  
  <!-- 测试动态SQL语句trim -->
  <update id="updateUserWithTrim" parameterType="cn.com.pojo.User">
    update user 
    <trim prefix="set" suffixOverrides=",,,">
      username=#{username},,,
    </trim>
    where id=#{id}
  </update>
  
  <!-- 测试动态SQL语句bind -->
  <select id="queryUserWithBind" resultType="cn.com.pojo.User">
    select * from user
    <where>
	    <if test="username !=null and username !=''">
	       <bind name="username" value="'%'+username+'%'"/>
	       username like #{username}
	    </if>
    </where>
  </select>
  
  <!-- 测试动态SQL语句foreach -->
  <select id="queryUserWithForeach" parameterType="list" resultType="cn.com.pojo.User">
    select * from user where id in
    <foreach collection="userIDList" open="(" separator="," close=")" item="userID">
      #{userID}
    </foreach>
  </select>
  
   <!-- 测试动态SQL语句include -->
  <sql id="columns">id,username,password,gender</sql>
  <select id="queryUserWithInclude" resultType="cn.com.pojo.User">
    select <include refid="columns"/> from user
    <where>
	    <if test="username !=null and username !=''">
	       and username=#{username}
	    </if>
	    <if test="password !=null and password !=''">
	       and password=#{password}
	    </if>
    </where>
  </select>
  
</mapper>

MybatisTest

package cn.com.test;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
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.junit.Test;
import cn.com.mapper.UserMapper;
import cn.com.pojo.User;
/**
 * 本文作者:谷哥的小弟
 * 博客地址:http://blog.csdn.net/lfdfhl
 */
public class MybatisTest {

	static SqlSessionFactory sqlSessionFactory = null;

	public static SqlSessionFactory getSqlSessionFactory() {
		try {
			if (sqlSessionFactory == null) {
				InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
				SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
				sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
			}
			return sqlSessionFactory;
		} catch (Exception e) {
			// TODO: handle exception
		} finally {

		}
		return null;
	}
	
	@Test
	public void testQueryUserWithIf() {
		//获取SqlSession
		SqlSession sqlSession=getSqlSessionFactory().openSession();
		//利用SqlSession得到UserMapper
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		//利用SqlSession执行数据操作
		List<User> userList = userMapper.queryUserWithIf("lucy", "123456");
		//List<User> userList = userMapper.queryUserWithIf("", "");
		//List<User> userList = userMapper.queryUserWithIf("lucy", "");
		//List<User> userList = userMapper.queryUserWithIf("", "123456");
		Iterator<User> iterator = userList.iterator();
		while(iterator.hasNext()) {
			User user = iterator.next();
			System.out.println(user);
		}
		//关闭SqlSession
		sqlSession.close();
	}

	@Test
	public void testQueryUserWithWhere() {
		//获取SqlSession
		SqlSession sqlSession=getSqlSessionFactory().openSession();
		//利用SqlSession得到UserMapper
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		//利用SqlSession执行数据操作
		List<User> userList = userMapper.queryUserWithWhere("lucy", "123456");
		//List<User> userList = userMapper.queryUserWithWhere("", "");
		//List<User> userList = userMapper.queryUserWithWhere("lucy", "");
		//List<User> userList = userMapper.queryUserWithWhere("", "123456");
		Iterator<User> iterator = userList.iterator();
		while(iterator.hasNext()) {
			User user = iterator.next();
			System.out.println(user);
		}
		//关闭SqlSession
		sqlSession.close();
	}
	
	
	@Test
	public void testQueryUserWithChoose() {
		//获取SqlSession
		SqlSession sqlSession=getSqlSessionFactory().openSession();
		//利用SqlSession得到UserMapper
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		//利用SqlSession执行数据操作
		List<User> userList = userMapper.queryUserWithChoose("lucy", "123456");
		//List<User> userList = userMapper.queryUserWithChoose("", "");
		//List<User> userList = userMapper.queryUserWithChoose("lucy", "");
		//List<User> userList = userMapper.queryUserWithChoose("", "123456");
		Iterator<User> iterator = userList.iterator();
		while(iterator.hasNext()) {
			User user = iterator.next();
			System.out.println(user);
		}
		//关闭SqlSession
		sqlSession.close();
	}
	
	@Test
	public void testUpdateUserWithSet() {
		//获取SqlSession
		SqlSession sqlSession=getSqlSessionFactory().openSession();
		//利用SqlSession得到UserMapper
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		//利用SqlSession执行数据操作
		User user=new User(1, "tutu", "666999", "male");
		int result=userMapper.updateUserWithSet(user);
		System.out.println(result);
		//提交
		sqlSession.commit();
		//关闭SqlSession
		sqlSession.close();
	}
	
	@Test
	public void testUpdateUserWithTrim() {
		//获取SqlSession
		SqlSession sqlSession=getSqlSessionFactory().openSession();
		//利用SqlSession得到UserMapper
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		//利用SqlSession执行数据操作
		User user=new User(1, "wawa", "666666", "male");
		int result=userMapper.updateUserWithTrim(user);
		System.out.println(result);
		//提交
		sqlSession.commit();
		//关闭SqlSession
		sqlSession.close();
	}
	
	@Test
	public void testQueryUserWithBind() {
		//获取SqlSession
		SqlSession sqlSession=getSqlSessionFactory().openSession();
		//利用SqlSession得到UserMapper
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		//利用SqlSession执行数据操作
		List<User> userList = userMapper.queryUserWithBind("xi");
		Iterator<User> iterator = userList.iterator();
		while(iterator.hasNext()) {
			User user = iterator.next();
			System.out.println(user);
		}
		//关闭SqlSession
		sqlSession.close();
	}
	
	
	@Test
	public void testQueryUserWithForeach() {
		//获取SqlSession
		SqlSession sqlSession=getSqlSessionFactory().openSession();
		//利用SqlSession得到UserMapper
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		//利用SqlSession执行数据操作
		List<Integer> userIDList=new ArrayList<Integer>();
		userIDList.add(1);
		userIDList.add(2);
		userIDList.add(3);
		List<User> userList = userMapper.queryUserWithForeach(userIDList);
		Iterator<User> iterator = userList.iterator();
		while(iterator.hasNext()) {
			User user = iterator.next();
			System.out.println(user);
		}
		//关闭SqlSession
		sqlSession.close();
	}
	
	@Test
	public void testQueryUserWithInclude() {
		//获取SqlSession
		SqlSession sqlSession=getSqlSessionFactory().openSession();
		//利用SqlSession得到UserMapper
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		//利用SqlSession执行数据操作
		List<User> userList = userMapper.queryUserWithInclude("pepe", "456123");
		Iterator<User> iterator = userList.iterator();
		while(iterator.hasNext()) {
			User user = iterator.next();
			System.out.println(user);
		}
		//关闭SqlSession
		sqlSession.close();
	}
	

}

log4j.properties

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# 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">
<configuration>
  <!-- 配置数据源 -->
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatisDatabase"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
      </dataSource>
    </environment>
  </environments>
  
  <!-- 配置mapper -->
  <mappers>
    <mapper resource="cn/com/pojo/UserMapper.xml"/>
  </mappers>
  
</configuration>
发布了1019 篇原创文章 · 获赞 1913 · 访问量 233万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 精致技术 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览