1.模糊查询
接口:
public interface SelectMapper { List<User> getUserByLike(@Param("mohu") String mohu); }
SQL(错误示范):
SQL(错误示范):
测试:
public void test7(){ SqlSessionUtils sqlSessionUtils = new SqlSessionUtils(); SqlSession sqlSession = sqlSessionUtils.getSqlSession(); SelectMapper mapper = sqlSession.getMapper(SelectMapper.class); List<User> userByLike = mapper.getUserByLike("123"); System.out.println(userByLike); }
运行结果:
SQL: SELECT * FROM t_user WHERE PASSWORD LIKE '%?%'
因为:#{}:相当于参数占位符,且会对自动传入的数据加一个双引号,外面已经有一层引号,所以报错。
SQL(正确示范,以下3种都行):
select * from t_user where password like '%${mohu}%'
select * from t_user where password like concat('%',#{mohu},'%')
select * from t_user where password like "%"#{mohu}"%"
运行结果:
2.批量删除
接口:
/** * * @param ids * @return */ int deleteMoreUser(@Param("ids") String ids);
SQL:
<delete id="deleteMoreUser"> delete from t_user where id in(${ids}) </delete>
表: 运行结果:
3.动态设置表名
当有多张表时,例如 VIP表 和 普通表 ,这时需要动态设置表名。
接口:
List<User> getAllUser(@Param("tableName") String tableName);
SQL:
select * from ${tableName}
注意:不能使用 #{}
select * from #{tableName}
因为#{} 会自动添加单引号,就变成了:
select * from '表名'
4.添加功能获取自增的主键
场景模拟:
t_clazz(clazz_id,clazz_name)
t_student(student_id,student_name,clazz_id)
1 、添加班级信息
2 、获取新添加的班级的 id
3 、为班级分配学生,即将某学的班级 id 修改为新添加的班级的 id
接口:
int insertUser(User user);
SQL:
<insert id="insertUser" useGeneratedKeys="true" keyProperty="id"> insert into t_user values(null,#{username},#{password},#{age},#{sex},#{email}) </insert>
测试:
public void test9(){ SqlSessionUtils sqlSessionUtils = new SqlSessionUtils(); SqlSession sqlSession = sqlSessionUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = new User(null,"小K","183918389",22,"男","13121178@qq.com"); mapper.insertUser(user); System.out.println(user); }
效果: 如果把 useGeneratedKeys keyProperty 删除运行结果: 发现id=null