特殊Sql执行
- 1. 模糊查询
- 2. 批量删除
- 3. 动态设置表名
- 4. 添加功能获取自增的主键
- 5. 整体代码
1. 模糊查询
/**
* 根据用户名进行模糊查询
* @param moHu
* @return
*/
List<User> getUserByLike(@Param("moHu") String moHu);
<!--List<User> getUserByLike(@Param("hoHu") String moHu);-->
<select id="getUserByLike" resultType="User">
<!-- select * from t_user where username like '%${moHu}%'-->
<!-- select * from t_user where username like concat('%',#{moHu},'%')-->
select * from t_user where username like "%"#{moHu}"%"
</select>
注意:‘${name}’ = ‘name’, #{name} = name, 一个加引号,一个不加,要求sql功底一定要好,知道哪些添加引号,哪些不可以添加。
测试方法
@Test
public void testGetUserByLike(){
SqlSession sqlSession = SqlSessionFactoryUtils.getSqlSession();
SqlMapper sqlMapper = sqlSession.getMapper(SqlMapper.class);
List<User> userList = sqlMapper.getUserByLike("sm");
for(User user : userList){
System.out.println(user);
}
sqlSession.close();
}
2. 批量删除
只能使用${},如果使用#{},则解析后的sql语句为delete from t_user where id in ('1,2,3')
,这样是将1,2,3
看做是一个整体,只有id为1,2,3
的数据会被删除。正确的语句应该是delete from t_user where id in (1,2,3)
,或者delete from t_user where id in ('1','2','3')
/**
* 根据id进行批量删除
* @param ids
* @return
*/
int deleteMore(@Param("ids") String ids);
<!--int deleteMore(@Param("ids") String ids);-->
<delete id="deleteMore">
<!-- 连续删除错误写法1:delete from t_user where id in (#{ids}), 原因在于#{ids}解析出来会自动添加引号'ids',导致出错-->
<!-- 连续删除错误写法2:delete from t_user where id in ('${ids}'),不能添加引号,要不然sql语句报错-->
<!-- 存在sql注入,会把数据库中的所有数据删除:delete from t_user where id in (${ids}) or '1' = '1'-->
delete from t_user where id in (${ids})
</delete>
测试方法
@Test
public void testDeleteMore() throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
SqlMapper sqlMapper = sqlSession.getMapper(SqlMapper.class);
int count = sqlMapper.deleteMore("22, 23, 24");
System.out.println("影响行数:" + count);
sqlSession.close();
}
3. 动态设置表名
只能使用${},因为表名不能加单引号
/**
* 查询指定表中的数据
* @param tableName
* @return
*/
List<User> getUserByTable(@Param("tableName") String tableName);
<!--List<User> getUserByTable(@Param("tableName") String tableName);-->
<select id="getUserByTable" resultType="User">
select * from ${tableName}
</select>
测试方法
@Test
public void testGetUserByTable() throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
SqlMapper sqlMapper = sqlSession.getMapper(SqlMapper.class);
// 查询t_user表的数据
List<User> userList = sqlMapper.getUserByTable("t_user");
for(User user : userList){
System.out.println(user);
}
sqlSession.close();
}
4. 添加功能获取自增的主键
功能:获取插入数据自增主键的id,便于后续程序的操作
-
在mapper.xml中设置两个属性
-
useGeneratedKeys:设置使用自增的主键
-
keyProperty:因为增删改有统一的返回值是受影响的行数,因此只能将获取的自增的主键放在传输的参数user对象的某个属性中
/**
* 添加用户信息
* @param user
*/
void insert(User user);
<!--
void insertUser(User user) ;
useGeneratedKeys :设置当前标签中的sql使用了自增的主键
keyProperty:将自增的值主键的赋值给传输到映射文件中参数的某个属性
-->
<insert id="insert" useGeneratedKeys="true" keyProperty="id">
insert into t_user values(null, #{username}, #{password}, #{age}, #{sex}, #{email})
</insert>
测试方法
@Test
public void testInsert(){
SqlSession sqlSession = SqlSessionFactoryUtils.getSqlSession();
SqlMapper mapper = sqlSession.getMapper(SqlMapper.class);
// 可以获取插入数据的id
User user = new User(null, "Tom", "123", 23, "男", "1235@qq.com");
mapper.insert(user);
System.out.println(user);
sqlSession.close();
}
进入数据库中进行查看
5. 整体代码
SqlMapper接口
package com.atguigu.mapper;
import com.atguigu.pojo.User;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* @Author Mr.Lu
* @Date 2022/12/2 15:20
* @ClassName SqlMapper
* @Version 1.0
*/
public interface SqlMapper {
/**
* 根据用户名进行模糊查询
* @param moHu
* @return
*/
List<User> getUserByLike(@Param("moHu") String moHu);
/**
* 根据id进行批量删除
* @param ids
* @return
*/
int deleteMore(@Param("ids") String ids);
/**
* 查询指定表中的数据
* @param tableName
* @return
*/
List<User> getUserByTable(@Param("tableName") String tableName);
/**
* 添加用户信息
* @param user
*/
void insert(User user);
}
SqlMapper接口对应的SqlMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.mapper.SqlMapper">
<!--List<User> getUserByLike(@Param("hoHu") String moHu);-->
<select id="getUserByLike" resultType="User">
select * from t_user where username like '%${moHu}%'
<!-- select * from t_user where username like concat('%',#{moHu},'%')-->
<!-- select * from t_user where username like "%"#{moHu}"%"-->
</select>
<!--int deleteMore(@Param("ids") String ids);
delete from t_user where id in (1, 2, 3): 如果数据表t_user存在主键id = 1或2或3,删除该条数据
-->
<delete id="deleteMore">
<!-- 连续删除错误写法1:delete from t_user where id in (#{ids})-->
<!-- 连续删除错误写法2:delete from t_user where id in ('${ids}')-->
<!-- 存在sql注入,会把数据库中的所有数据删除:delete from t_user where id in (${ids}) or '1' = '1'-->
delete from t_user where id in (${ids})
</delete>
<!--List<User> getUserByTable(@Param("tableName") String tableName);-->
<select id="getUserByTable" resultType="User">
select * from ${tableName}
</select>
<!--
void insertUser(User user) ;
功能:获取新增数据的主键,方便后续程序编写
useGeneratedKeys :设置当前标签中的sql使用了自增的主键
keyProperty:将自增的值主键的赋值给传输到映射文件中参数的某个属性
-->
<insert id="insert" useGeneratedKeys="true" keyProperty="id">
insert into t_user values(null, #{username}, #{password}, #{age}, #{sex}, #{email})
</insert>
</mapper>
MybatisSqlTest测试类
package com.atguigu.test;
import com.atguigu.mapper.SqlMapper;
import com.atguigu.pojo.User;
import com.atguigu.util.SqlSessionFactoryUtils;
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 java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
* @Author Mr.Lu
* @Date 2022/12/2 15:21
* @ClassName MybatisSqlTest
* @Version 1.0
*/
public class MybatisSqlTest {
@Test
public void testGetUserByLike(){
SqlSession sqlSession = SqlSessionFactoryUtils.getSqlSession();
SqlMapper sqlMapper = sqlSession.getMapper(SqlMapper.class);
List<User> userList = sqlMapper.getUserByLike("sm");
for(User user : userList){
System.out.println(user);
}
sqlSession.close();
}
@Test
public void testDeleteMore() throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
SqlMapper sqlMapper = sqlSession.getMapper(SqlMapper.class);
int count = sqlMapper.deleteMore("7,8,9");
System.out.println("影响行数:" + count);
sqlSession.close();
}
@Test
public void testGetUserByTable() throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
SqlMapper sqlMapper = sqlSession.getMapper(SqlMapper.class);
List<User> userList = sqlMapper.getUserByTable("t_user");
for(User user : userList){
System.out.println(user);
}
sqlSession.close();
}
@Test
public void testInsert(){
SqlSession sqlSession = SqlSessionFactoryUtils.getSqlSession();
SqlMapper mapper = sqlSession.getMapper(SqlMapper.class);
// 可以获取插入数据的id
User user = new User(null, "ton", "123", 23, "男", "1235@qq.com");
mapper.insert(user);
System.out.println(user);
sqlSession.close();
}
}