首发于我的博客 和尚的博客
本文讲解动态的SQL操作,CRUD中,CUD都需要自己手动提交事务,动态的添加语句,批量删除的三种处理方式,提取公共的sql代码,if标签,where标签,trim标签,set标签,choose标签,foreach标签,批量添加
源码获取github
<trim prefix="当发现有内容的时候,你在内容的最前面想加入什么内容"
prefixOverrides="当发现有内容的时候,你在内容的最前面想抹掉什么内容"
suffix="当发现有内容的时候,你在内容的最后面面想加入什么内容"
suffixOverrides="当发现有内容的时候,你在内容的最后面想抹掉什么内容">
trim>
当你发现有内容的时候,在内容的最前面加入 set 当你放下有内容的时候,检查内容的最后面是否有逗号”,” 如果将其抹掉
同前几天笔记
mybatis-config.xml
<configuration>
<properties resource="jdbc.properties"/>
<typeAliases>
<package name="com.hs.model"/>
typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${jdbc.mysql.driver}" />
<property name="url" value="${jdbc.mysql.url}" />
<property name="username" value="${jdbc.mysql.username}" />
<property name="password" value="${jdbc.mysql.password}" />
dataSource>
environment>
environments>
<mappers>
<mapper resource="com/hs/model/UserMapper.xml"/>
mappers>
configuration>
User.java
package com.hs.model;
import java.util.Date;
public class User {
/*本字段名字跟数据库的字段一样*/
private Integer user_id;
private String user_name;
private String sex;
private Double money;
private Date birthday;
public Integer getUser_id() {
return user_id;
}
public void setUser_id(Integer user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User{" +
"user_id=" + user_id +
", user_name='" + user_name + '\'' +
", sex='" + sex + '\'' +
", money=" + money +
", birthday=" + birthday +
'}';
}
}
UserMapper.xml
<mapper namespace="com.hs.dao.UserDao">
<resultMap id="BaseResultMap" type="com.hs.model.User">
<id column="user_id" property="user_id"/>
<result column="user_name" property="user_name"/>
<result column="sex" property="sex"/>
<result column="money" property="money"/>
<result column="birthday" property="birthday"/>
resultMap>
<sql id="oa_user_columns">
user_id,user_name,sex,money,birthday
sql>
<sql id="oa_user_columns_alias">
${alias}.user_id,${alias}.user_name,${alias}.sex,${alias}.money,${alias}.birthday
sql>
<select id="getUserListIf01" parameterType="map" resultMap="BaseResultMap">
select
<include refid="oa_user_columns"/>
from
oa_user
where 1=1
<if test="name != null && name != ''">
and user_name like concat('%',#{name},'%')
if>
<if test="sex != null and sex != ''">
and sex = #{sex}
if>
select>
<select id="getUserListIf02" parameterType="map" resultMap="BaseResultMap">
select
<include refid="oa_user_columns"/>
from
oa_user
<where>
<if test="name != null && name != ''">
and user_name like concat('%',#{name},'%')
if>
<if test="sex != null and sex != ''">
and sex = #{sex}
if>
where>
select>
<select id="getUserListIf03" parameterType="map" resultMap="BaseResultMap">
select
<include refid="oa_user_columns"/>
from
oa_user
<trim prefix="where " prefixOverrides="and || or">
<if test="name != null && name != ''">
and user_name like concat('%',#{name},'%')
if>
<if test="sex != null and sex != ''">
and sex = #{sex}
if>
trim>
select>
<update id="updateUser01ByPk" parameterType="com.hs.model.User">
update oa_user
<set>
<if test="user_name !=null and user_name != ''">
user_name = #{user_name},
if>
<if test="sex !=null and sex != ''">
sex = #{sex},
if>
<if test="money != null">
money = #{money},
if>
set>
where user_id = #{user_id}
update>
<update id="updateUser02ByPk" parameterType="com.hs.model.User">
update oa_user
<trim prefix="set" suffixOverrides=",">
<if test="user_name !=null and user_name != ''">
user_name = #{user_name},
if>
<if test="sex !=null and sex != ''">
sex = #{sex},
if>
<if test="money != null">
money = #{money},
if>
trim>
where user_id = #{user_id}
update>
<select id="getSkillByChoose" parameterType="map" resultMap="BaseResultMap">
select <include refid="oa_user_columns"/>
from oa_user
where
<choose>
<when test='sex!=null and sex=="男"'>
money > 700
when>
<when test='sex!=null and sex="女"'>
when>
<otherwise>
1=1
otherwise>
choose>
select>
<insert id="addSkill01" parameterType="com.hs.model.User" useGeneratedKeys="true" keyProperty="user_id">
insert into oa_user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="user_name !=null and user_name!=''">
user_name,
if>
<if test="sex !=null and sex!=''">
sex,
if>
<if test="money !=null">
money,
if>
<if test="birthday !=null">
birthday,
if>
trim>
<trim prefix="values(" suffix=")" suffixOverrides=",">
<if test="user_name !=null and user_name!=''">
#{user_name},
if>
<if test="sex !=null and sex!=''">
#{sex},
if>
<if test="money !=null">
#{money},
if>
<if test="birthday !=null">
#{birthday},
if>
trim>
insert>
<delete id="deleteSkillByArray" >
delete from oa_user where user_id in
<foreach collection="array" item="id" open="(" close=")" separator=",">
#{id}
foreach>
delete>
<delete id="deleteSkillByList" parameterType="list">
delete from oa_user where user_id in
<foreach collection="list" item="id" open="(" close=")" separator=",">
#{id}
foreach>
delete>
<delete id="deleteSkillByMap" parameterType="map">
delete from oa_user where user_id in
<foreach collection="id_array" item="id" open="(" close=")" separator=",">
#{id}
foreach>
delete>
<insert id="addSkillByAll" parameterType="list">
insert into oa_user(user_name,sex,money)
values
<foreach collection="list" item="user" separator=",">
(#{user.user_name},#{user.sex},#{user.money})
foreach>
insert>
mapper>
同之前的笔记
UserDao.java
package com.hs.dao;
import com.hs.model.User;
import java.util.List;
import java.util.Map;
public interface UserDao {
List getUserListIf01(Map map);
List getUserListIf02(Map map);
List getUserListIf03(Map map);
int updateUser01ByPk(User user);
int updateUser02ByPk(User user);
List getSkillByChoose(Map map);
int addSkill01(User user);
int deleteSkillByArray(int[] array);
int deleteSkillByList(List list);
int deleteSkillByMap(Map map);
int addSkillByAll(List list);
}
log4j.properties.xml
# 日志配置文件Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
# 如果要显示SQL语句,那么这个位置需要配置为命名空间log4j.logger.命名空间
log4j.logger.com.hs.dao.UserDao=TRACE
# 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
MyBatisTest.java
package com.hs.test;
import com.hs.dao.UserDao;
import com.hs.model.User;
import com.hs.util.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 接口代理模式实现操作,在xxDao接口中,定义方法: sql语句返回的结果类型 sql语句的id(要传的值);
* 不用写实现类,直接写测试类,具体实现见测试类
* sql的映射文件的命名空间跟接口的全路径一致
* 可以根据接口的返回类型自动判断使用selectOne还是selectList eg:返回的是一个对象的为one,返回的是list的就是list,如果是List,也是list
*/
public class MyBatisTest {
/**
* if标签,进行两个姓名和性别的条件查询,通过恒等式完成动态SQL语句
*/
@Test
public void getUserListIf01() {
SqlSession sqlSession = null;
try {
sqlSession = MyBatisUtils.getSqlsession();
Map map = new HashMap();
map.put("name", "悟");
map.put("sex", "男");
UserDao userDao = sqlSession.getMapper(UserDao.class);
System.out.println(userDao.getUserListIf01(map));
} finally {
MyBatisUtils.closeSqlSession(sqlSession);
}
}
/**
* if标签,进行两个姓名和性别的条件查询,通过where标签(推荐!!!):
* 如果发现标签內有内容,那么会在内容的最前面加入关键字 where
* 如果有内容,会检查内容的最前面是否含有 AND空格 或者 OR空格 ,自动将其抹
*/
@Test
public void getUserListIf02() {
SqlSession sqlSession = null;
try {
sqlSession = MyBatisUtils.getSqlsession();
Map map = new HashMap();
map.put("name", "悟");
map.put("sex", "男");
UserDao userDao = sqlSession.getMapper(UserDao.class);
System.out.println(userDao.getUserListIf02(map));
} finally {
MyBatisUtils.closeSqlSession(sqlSession);
}
}
/**
* if标签,进行两个姓名和性别的条件查询,通过trim标签:
*
*/
@Test
public void getUserListIf03() {
SqlSession sqlSession = null;
try {
sqlSession = MyBatisUtils.getSqlsession();
Map map = new HashMap();
map.put("name", "悟");
map.put("sex", "男");
UserDao userDao = sqlSession.getMapper(UserDao.class);
System.out.println(userDao.getUserListIf03(map));
} finally {
MyBatisUtils.closeSqlSession(sqlSession);
}
}
/**
* 更新操作—变更数据库
* 利用set标签
* 当你发现有内容的时候,在内容的最前面加入 set
* 当你发现有内容的时候,检查内容的最后面是否有逗号"," 如果有将其抹掉
*/
@Test
public void updateUser01ByPk() throws ParseException {
SqlSession sqlSession = null;
try {
sqlSession = MyBatisUtils.getSqlsession();
//数据
User user = new User();
user.setUser_id(3);
user.setUser_name("天蓬元帅");
//日期的转换
String date = "2018-8-3";
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
user.setBirthday(dateFormat.parse(date));
UserDao userDao = sqlSession.getMapper(UserDao.class);
System.out.println(userDao.updateUser01ByPk(user));
//重点!!!,CRUD中,除了R(查询),不用提交事务,其余全的自己提交事务,传统和接口模式提交事务都是一样的
sqlSession.commit();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
MyBatisUtils.closeSqlSession(sqlSession);
}
}
/**
* 更新操作—变更数据库
* 利用trim标签
*
* @throws ParseException
*/
@Test
public void updateUser02ByPk() throws ParseException {
SqlSession sqlSession = null;
try {
sqlSession = MyBatisUtils.getSqlsession();
//数据
User user = new User();
user.setUser_id(3);
user.setUser_name("天蓬元帅");
user.setMoney(1000.0);
//日期的转换
String date = "2018-8-3";
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
user.setBirthday(dateFormat.parse(date));
UserDao userDao = sqlSession.getMapper(UserDao.class);
System.out.println(userDao.updateUser02ByPk(user));
//重点!!!,CRUD中,除了R(查询),不用提交事务,其余全的自己提交事务,传统和接口模式提交事务都是一样的
sqlSession.commit();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
MyBatisUtils.closeSqlSession(sqlSession);
}
}
/**
* 查询通过choose标签
* 解决小于号的问题
*/
@Test
public void getSkillByChoose() {
SqlSession sqlSession = null;
try {
sqlSession = MyBatisUtils.getSqlsession();
Map map = new HashMap();
map.put("sex", "女");
UserDao userDao = sqlSession.getMapper(UserDao.class);
System.out.println(userDao.getSkillByChoose(map));
} finally {
MyBatisUtils.closeSqlSession(sqlSession);
}
}
/**
* 添加一个数据,然后返回这个数据自增长的主键信息
*/
@Test
public void addSkill01() throws ParseException {
SqlSession sqlSession = null;
try {
sqlSession = MyBatisUtils.getSqlsession();
User user = new User();
user.setUser_name("沙僧");
user.setSex("男");
user.setMoney(455.0);
String date = "2018-8-5";
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
user.setBirthday(dateFormat.parse(date));
UserDao userDao = sqlSession.getMapper(UserDao.class);
System.out.println("影响行数"+userDao.addSkill01(user));
sqlSession.commit();
System.out.println("user_id:"+user.getUser_id());
} finally {
MyBatisUtils.closeSqlSession(sqlSession);
}
}
/**
* 传递传递数组删除规则
*/
@Test
public void deleteSkillByArray(){
SqlSession sqlSession = null;
try {
sqlSession = MyBatisUtils.getSqlsession();
UserDao userDao = sqlSession.getMapper(UserDao.class);
System.out.println(userDao.deleteSkillByArray(new int[]{6,8})); //静态初始化
//事务的手动提交
sqlSession.commit();
} finally {
MyBatisUtils.closeSqlSession(sqlSession);
}
}
/**
* 传递List集合删除规则
*/
@Test
public void deleteSkillByList(){
SqlSession sqlSession = null;
try {
sqlSession = MyBatisUtils.getSqlsession();
List list = new ArrayList();
list.add(9);
list.add(11);
UserDao userDao = sqlSession.getMapper(UserDao.class);
System.out.println(userDao.deleteSkillByList(list));
//事务的手动提交
sqlSession.commit();
} finally {
MyBatisUtils.closeSqlSession(sqlSession);
}
}
/**
* 传递Map里装list删除规则
*/
@Test
public void deleteSkillByMap(){
SqlSession sqlSession = null;
try {
sqlSession = MyBatisUtils.getSqlsession();
List list = new ArrayList();
list.add(8);
list.add(10);
Map map = new HashMap();
map.put("id_array",list);
UserDao userDao = sqlSession.getMapper(UserDao.class);
System.out.println(userDao.deleteSkillByMap(map));
//事务的手动提交
sqlSession.commit();
} finally {
MyBatisUtils.closeSqlSession(sqlSession);
}
}
/**
* 通过list里装User实现批量添加
*/
@Test
public void addSkillByAll(){
SqlSession sqlSession = null;
try {
sqlSession = MyBatisUtils.getSqlsession();
List list = new ArrayList();
User user1 = new User();
user1.setUser_name("嫦娥");
user1.setSex("女");
user1.setMoney(1213.0);
User user2 = new User();
user2.setUser_name("月兔");
user2.setSex("女");
user2.setMoney(2113.0);
list.add(user1);
list.add(user2);
UserDao userDao = sqlSession.getMapper(UserDao.class);
System.out.println(userDao.addSkillByAll(list));
sqlSession.commit();
} finally {
MyBatisUtils.closeSqlSession(sqlSession);
}
}
}