分享知识-快乐自己: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 ...
随机推荐
- c语言中external,static关键字用法
static用法: 在C中,static主要定义全局静态变量.定义局部静态变量.定义静态函数. 1.定义全局静态变量:在全局变量前面加上关键字static,该全局变量变成了全局静态变量.全局静态变量有 ...
- 把flask部署到服务器
1.新建一个wsgi.py文件 # -*- coding:utf-8 -*- import sys from os.path import abspath from os.path import di ...
- PHP Memcached 面试题
这里收集了经常被问到的关于memcached的问题 * memcached是怎么工作的? * memcached最大的优势是什么? * memcached和MySQL的query cache相比,有什 ...
- 8168开发之---1g内存换成512M的内存映射配置
最近在帮新来同事调式内存分配,起初是将config.bld 中的内存在标配的基础上减少sr1,和tiler 将dsp从9m增加到16m,然后编译通过, 可是在加载的时候卡住了,init.sh 过,lo ...
- iOS 启动页放大淡出效果
//屏幕宽度#define kWIDTH [UIScreen mainScreen].bounds.size.width//屏幕高度 #define kHEIGHT [UIScreen mainScr ...
- C语言基础知识【C语言教程】
2017年7月7日23:15:51外边下雨,突然想学习c语言,所以刷一遍基础. 笔记:C 语言教程1.C 语言是一种通用的.面向过程式的计算机程序设计语言.1972 年,为了移植与开发 UNIX 操作 ...
- 关于使用Tomcat服务器出现413错误的解决办法(Request Entity Too Large)
解决的办法: 修改tomcat的配置文件C:/MinyooCMS/tomcat/conf/server.xml(或者安装在D盘文件路径是D: /MinyooCMS/tomcat/conf/server ...
- VS2010 fatal error LNK1123: 转换到 COFF 期间失败: 文件无效或损坏
VS2010在经历一些更新后,建立Win32 Console Project时会出“error LNK1123” 错误,解决方案为将 项目|项目属性|配置属性|清单工具|输入和输出|嵌入清单 “是”改 ...
- IIS架构介绍
IIS7及以上版本提供的请求-处理架构包括以下内容: Windows Process Activation Service(WAS)可以让站点支持更多协议,不仅仅是HTTP和HTTPS 可以通过增加或 ...
- iOS 推送跳转到相关页面
哈哈哈 我又来窃取别人的劳动成果了 写的很好呦 http://www.jianshu.com/p/c0eb32443915