分享知识-快乐自己:Mybatis 基础动态语句
目录:

User:
package mlq.bean; /**
* 用户实体类
*/
public class User { private Integer uId;
private String userName;
private String userPwd;
private String realName; public User(Integer uId, String userName, String userPwd, String realName) {
this.uId = uId;
this.userName = userName;
this.userPwd = userPwd;
this.realName = realName;
} public User(Integer uId) {
this.uId = uId;
} public User() {
} @Override
public String toString() {
return "User{" +
"uId=" + uId +
", userName='" + userName + '\'' +
", userPwd='" + userPwd + '\'' +
", realName='" + realName + '\'' +
'}';
} }
UserMappers:
package mlq.Mapper; import mlq.bean.User;
import org.apache.ibatis.annotations.Param; import java.util.List;
import java.util.Map; /**
* 用户接口
*/
public interface UserMappers { /**
* 查询用户信息
*/
public List<User> userAllList(User user);
public List<User> userAllListTow(User user);
public List<User> userAllListChoose(User user);
/**
* 更新用户信息
*/
public int updUser(User user);
public int updUserTow(User user); /**
* 使用数组入参Foreach遍历
* @param ars
* @return
*/
public List<User> userArrays(int[] ars); /**
* 使用List普通入参Foreach遍历
* @param ars
* @return
*/
public List<User> userListForeach(List<String> ars); /**
* 使用List对象入参Foreach遍历
* @param ars
* @return
*/
public List<User> userListForeachs(List<User> ars); /**
* 使用Map+List集合入参Foreach遍历
* @param ars
* @return
*/
public List<User> userMapForeach(Map<String,Object> ars); /**
* 使用Map入参Foreach遍历
* @param ars
* @return
*/
public List<User> userMap(Map<String,Object> ars);
public List<User> userMapTow(@Param("ars") Map<String,User> ars); /**
* 同时插入多条数据
* @param list
* @return
*/
public int inserUsers(List<User> list);
}
MyBatis.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> <!--引入properties文件-->
<properties resource="DatabaseConfig.properties" /> <!--设置类别名-->
<typeAliases>
<package name ="mlq.bean" />
</typeAliases> <!--设置Mybatis运行环境-->
<environments default="mysql"><!--default找到环境的id,只能用一个-->
<environment id="mysql"><!--可以定义多个环境-->
<transactionManager type="JDBC"/><!--后续事务的管理 统一交给spring容器-->
<dataSource type="POOLED"><!--数据源 Tomcat:JNDI Mybatis:POOLED-->
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments> <mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
</configuration>
MyBatisTool:
package mlq.util; 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 java.io.IOException;
import java.io.Reader; /**
* 获取连接对象工具类
*/
public class MyBatisTool { //建立私有构造
private MyBatisTool(){} //SQLSessionFactory 简单的理解就是创建SQLSession 实例的工厂。
private final static SqlSessionFactory sqlSessionFactory; //静态代码块初始化sqlSessionFactory对象
static
{
//获取Mybatis.xml核心配置文件路径
String path="MyBatis.xml";
Reader reader=null;
try {
//将文件信息读取到内存中
reader = Resources.getResourceAsReader(path);
} catch (IOException e) {
e.printStackTrace();
}
//创建实例
sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
} /**
* 获取工厂函数SQLSessionFactory
* @return
*/
public static SqlSessionFactory getSqlSessionFactory() { return sqlSessionFactory; } /**
* 获取SqlSession连接对象
* @return
*/
public static SqlSession getSqlSession(){return sqlSessionFactory.openSession();} /**
* 关闭连接对象
* @param sqlSession
*/
public static void closeSqlsession(SqlSession sqlSession){
if (sqlSession!=null)
{
sqlSession.close();
}
}
}
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="mlq.Mapper.UserMappers"> <!--使用Where标签实现动态SQL拼接-->
<select id="userAllListTow" parameterType="User" resultType="User">
SELECT * FROM `user` WHERE 1=1
<if test="userName!=null and userName!=''">
AND `userName`=#{userName}
</if>
<if test="userPwd!=null and userPwd!=''">
AND `userPwd`=#{userPwd}
</if>
<if test="uId!=null and uId!=''">
AND `uId`=#{uId}
</if>
</select> <!--使用Where标签实现动态SQL拼接-->
<select id="userAllList" parameterType="User" resultType="User">
SELECT * FROM `user`
<where>
<if test="userName!=null and userName!=''">
AND `userName`=#{userName}
</if>
<if test="userPwd!=null and userPwd!=''">
AND `userPwd`=#{userPwd}
</if>
<if test="uId!=null and uId!=''">
AND `uId`=#{uId}
</if>
</where>
</select> <!--使用SET标签更新数据:说明此番操作有漏洞。逗号位置不明确:建议使用下述方式-->
<update id="updUser" parameterType="User">
UPDATE `user`
<set>
<if test="userName!=null and userName!=''">
`userName`=#{userName},
</if>
<if test="userPwd!=null and userPwd!=''">
`userPwd`=#{userPwd},
</if>
<if test="realName!=null and realName!=''">
`realName`=#{realName},
</if>
</set>
<where>
`uId`=#{uId}
</where>
</update>
<update id="updUserTow" parameterType="User">
UPDATE `user`
<trim prefix="set" suffixOverrides="," suffix="`uId`=#{uId}">
<if test="userName!=null and userName!=''">
`userName`=#{userName},
</if>
<if test="userPwd!=null and userPwd!=''">
`userPwd`=#{userPwd},
</if>
<if test="realName!=null and realName!=''">
`realName`=#{realName},
</if>
</trim>
</update> <!--公用SQL片段-->
<sql id="cols"> SELECT * FROM `user`</sql>
<!--使用choose方式判断:相当于switch结构-->
<select id="userAllListChoose" parameterType="User" resultType="User">
<include refid="cols"/>
<where>
<choose>
<when test="userName!=null and userName!=''">
AND `userName`=#{userName}
</when>
<when test="userPwd!=null and userPwd!=''">
AND `userPwd`=#{userPwd}
</when>
<otherwise>
AND `uId`=#{uId}
</otherwise>
</choose>
</where>
</select> <!--使用数组入参,Foreach遍历-->
<select id="userArrays" resultType="User">
<include refid="cols"/>
<trim prefix="where `uId` in">
<if test="array.length>0">
<foreach item="temp" collection="array" open="(" close=")" separator=",">
#{temp}
</foreach>
</if>
</trim>
</select>
<!--使用List普通入参,Foreach遍历-->
<select id="userListForeach" resultType="User">
<include refid="cols"/>
<trim prefix="where `uId` in">
<if test="list.size>0">
<foreach item="temp" collection="list" open="(" close=")" separator=",">
#{temp}
</foreach>
</if>
</trim>
</select>
<!--使用List对象入参,Foreach遍历-->
<select id="userListForeachs" resultType="User">
<include refid="cols"/>
<trim prefix="where `uId` in">
<if test="list.size>0">
<foreach item="temp" collection="list" open="(" close=")" separator=",">
#{temp.uId}
</foreach>
</if>
</trim>
</select>
<!--使用Map+List集合入参-->
<select id="userMapForeach" resultType="User">
<include refid="cols"/>
<where>
<if test="mapList.size>0">
`uId` in
<foreach collection="mapList" open="(" close=")" item="temp" separator=",">
#{temp}
</foreach>
</if>
</where> </select> <select id="userMap" resultType="User">
<include refid="cols"/>
<where>
`uId` in (#{one})
</where>
</select>
<!--使用注解入参Map-->
<select id="userMapTow" resultType="User">
<include refid="cols"/>
<where>
`uId` in
<if test="ars.keys.size>0">
<foreach collection="ars.keys" open="(" separator="," close=")" item="key" index="ind">
<!--通过键获取value-->
#{ars[${key}].uId}
<!--直接获取key-->
<!--#{key}-->
</foreach>
</if>
</where>
</select> </mapper>
UserText:
package mlq; import mlq.bean.User;
import mlq.Mapper.UserMappers;
import mlq.util.MyBatisTool;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; public class UserText { //连接SQLSession
private SqlSession sqlSession = null;
private UserMappers mapper = null; //测试前置增强
@Before
public void before() {
sqlSession = MyBatisTool.getSqlSession();
mapper = sqlSession.getMapper(UserMappers.class);
} //测试后置增强
@After
public void after() {
sqlSession.commit();
sqlSession.close();
} /**
* 查询用户信息
*/
@Test
public void userAllList() {
User user = new User();
user.setUserName("MLQ");
user.setUId(20180001);
List<User> users = mapper.userAllList(user);
System.out.println(users);
} @Test
public void userAllListTow() {
User user = new User();
user.setUserName("MLQ");
user.setUId(20180001);
List<User> users = mapper.userAllListTow(user);
System.out.println(users);
} @Test
public void userAllListChoose() {
User user = new User();
user.setUserName("FKX");
user.setUId(20180002);
List<User> users = mapper.userAllListChoose(user);
System.out.println(users);
} /**
* 更新用户信息
*/
@Test
public void updUser() {
User user = new User();
user.setRealName("MLQMLQ");
user.setUserPwd("456");
user.setUserName("MLQ");
user.setUId(20180001);
int i = mapper.updUser(user);
System.out.println((i > 0) ? "更新成功" : "更新失败!!!");
} @Test
public void updUserTow() {
User user = new User();
user.setRealName("MLQ");
user.setUserPwd("123");
user.setUserName("MLQ");
user.setUId(20180001);
int i = mapper.updUser(user);
System.out.println((i > 0) ? "更新成功" : "更新失败!!!");
} /**
* 使用数组入参Foreach遍历
*/
@Test
public void arrayList() {
int[] ars = {20180001, 20180002};
List<User> users = mapper.userArrays(ars);
System.err.println(users);
} /**
* 使用List入参Foreach遍历
*/
@Test
public void userListForeach() {
List<String> list = new ArrayList<String>();
list.add("20180001");
list.add("20180002");
List<User> users = mapper.userListForeach(list);
System.out.println(users);
} @Test
public void userListForeachs() {
List<User> list = new ArrayList<User>();
User user = new User();
user.setUId(20180001);
User user1 = new User();
user1.setUId(20180002);
list.add(user);
list.add(user1);
List<User> users = mapper.userListForeachs(list);
System.err.println(users);
} //使用Map集合入参Foreach遍历
@Test
public void userMapForeach() {
Map<String, Object> map = new HashMap<String, Object>();
List<Integer> list = new ArrayList<Integer>();
list.add(20180001);
list.add(20180002);
map.put("one", 20180001);
map.put("mapList", list);
List<User> users = mapper.userMapForeach(map);
System.err.println(users);
} //使用Map集合入参Foreach遍历
@Test
public void userMap() {
Map<String, Object> map = new HashMap<String, Object>();
List<Integer> list = new ArrayList<Integer>();
list.add(20180001);
list.add(20180002);
map.put("one", 20180001);
map.put("mapList", list);
List<User> users = mapper.userMap(map);
System.err.println(users);
} /**
* 入参Map集合使用注解标注信息
*/
@Test
public void userMapTow() {
Map<String, User> map = new HashMap<String, User>();
User user = new User(20180001);
User user1 = new User(20180002);
map.put("20180001", user);
map.put("20180002", user1);
List<User> users = mapper.userMapTow(map);
System.err.println(users);
}
}
分享知识-快乐自己:Mybatis 基础动态语句的更多相关文章
- mybatis xml动态语句写法
mapper.java: /** * @Description: 根据摄像机Id查询出入记录 * @Param: * name 姓名 * monitorId 布控ID * starttime 开始时间 ...
- (转)mybatis:动态SQL
概述:在mybatis中,动态语句是个非常强大和灵活的功能,并且动态语句可以放在sql的任何地方,利用该功能,我们可以写出非常灵活的代码.在mybatis的动态语句中常常可能会用到以下几个运算和逻辑判 ...
- mybatis where in语句中参数过多
ps : mybatis在in中参数过多 出现问题 com.microsoft.sqlserver.jdbc.SQLServerException: 传入的请求具有过多的参数.该服务器支持最多 210 ...
- mybatis基础系列(三)——动态sql
本文是Mybatis基础系列的第三篇文章,点击下面链接可以查看前面的文章: mybatis基础系列(二)--基础语法.别名.输入映射.输出映射 mybatis基础系列(一)--mybatis入门 动态 ...
- MyBatis基础入门《十八》动态SQL(if-where)
MyBatis基础入门<十八>动态SQL(if-where) 描述: 代码是在<MyBatis基础入门<十七>动态SQL>基础上进行改造的,不再贴所有代码,仅贴改动 ...
- myBatis动态语句详解
SQL 映射XML 文件是所有sql语句放置的地方.需要定义一个workspace,一般定义为对应的接口类的路径.写好SQL语句映射文件后,需要在MyBAtis配置文件mappers标签中引用,例如: ...
- MyBatis基础:MyBatis动态SQL(3)
1. 概述 MyBatis中动态SQL包括元素: 元素 作用 备注 if 判断语句 单条件分支判断 choose(when.otherwise) 相当于Java中的case when语句 多条件分支判 ...
- MyBatis基础入门《二十》动态SQL(foreach)
MyBatis基础入门<二十>动态SQL(foreach) 1. 迭代一个集合,通常用于in条件 2. 属性 > item > index > collection : ...
- MyBatis基础入门《十九》动态SQL(set,trim)
MyBatis基础入门<十九>动态SQL(set,trim) 描述: 1. 问题 : 更新用户表数据时,若某个参数为null时,会导致更新错误 2. 分析: 正确结果: 若某个参数为nul ...
随机推荐
- Redis源码阅读-Dict哈希字典
Dict和Java中的HashMap很相似,都是数组开链法解决冲突. 但是Redis为了高性能, 有很多比较微妙的方法,例如 数组的大小总是2的倍数,初始大小是4. rehash并不是一次就执行完,而 ...
- Linux Apache安装加载mod_deflate模块
为了开启apache服务器中的gzip压缩功能,mod_deflate模块是必须安装加载的.现在介绍如何安装.1.进入到mod_deflate.c目录 cd /lamp/httpd-2.2.20/mo ...
- 在Servlet的GenericServlet类中为什么有两个init()方法
想要搞清楚这件事情,必须先了解Servlet容器调用Servlet的过程.调用过程如下 首次访问该Servlet1.调用init(ServletConfig config) 进行初始化,Servlet ...
- httpClient实现
1.实现功能 向关注了微信公众号的微信用户群发消息.(可以是所有的用户,也可以是提供了微信openid的微信用户集合) 2.基本步骤 前提: 已经有认证的公众号或者测试公众账号 发送消息步骤: 发送一 ...
- 快速清除MS SQL SERVER 日志
USE [master] GO ALTER DATABASE yourdatabase SET RECOVERY SIMPLE WITH NO_WAIT GO ALTER DATABASE yourd ...
- mysql海量数据条件删除
1. 问题描述:现在存在两个表,具体表结构及记录数如下所示: mysql> desc user_mapping; +------------+------------------+------+ ...
- 弹窗:popwindow 4部分
弹窗:popwindow 四部分 ①windows.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN ...
- Windows 下Node.js开发环境配置
第一步:安装VirtualBox(以管理员身份安装) 1.安装完成后,打开VirtualBox,点击“新建”按钮,输入信息,“下一步”(名称可任意) 2.设置内存为1024MB,“下一步”—>“ ...
- javascript修改图片链接地址
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head> < ...
- Python高级入门01-property
JAVA中存在对变量 私有化,公开,保护... 私有化时候,需要提供一个公开的get 和 set方法对外公开,让别人进行调用 python中同样存在 私有化变量定义是__是这个双下划线,eg:_ ...