1.mybatis模糊查询
根据名字实现模糊查询
SQLmapper 添加函数
List<User> getUserByLike(@Param("username") String username);
SQlmapper对应的xml文件
<select id="getUserByLike" resultType="user">
select * from t_user where username like "%"#{username}"%"
</select>
注意:#{} 是以占位符的形式进行赋值 ,${} 是以字符串的形式进行赋值
这里如果用${} 进行赋值那么得到的sql语句为 ……like %‘name’% 百分号当中的引号显然是不符合 sql语句规范的,需要更改为 like ‘%${username}%’ 或 like concat(‘%’,#{username},‘%’)
test添加测试函数查看效果
@Test
public void testGetUserByLike() throws IOException {
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SQLMapper mapper = sqlSession.getMapper(SQLMapper.class);
List<User> all = mapper.getUserByLike("测");
all.forEach(user -> System.out.println(user));
}
模糊查询成功与预期结果一致
2.mybatis批量删除
根据名字实现模糊查询
SQLmapper 添加函数
void deleteUserByIds(@Param("ids") String ids);
SQlmapper对应的xml文件
<delete id="deleteUserByIds" >
delete from t_user where id in (${ids})
</delete>
同样:#{} 是以占位符的形式进行赋值 ,${} 是以字符串的形式进行赋值
这里如果用#{} 进行赋值
test添加测试函数
@Test
public void testDeleteUserByIds() throws IOException {
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SQLMapper mapper = sqlSession.getMapper(SQLMapper.class);
mapper.deleteUserByIds("5,6,7");
ParameterMapper parameterMapper = sqlSession.getMapper(ParameterMapper.class);
List<User> allUser = parameterMapper.getAllUser();
allUser.forEach(user -> System.out.println(user));
}
3.mybatis动态获取表名
SQLmapper 添加函数
List<User> getAllUser(@Param("tableName") String tableName);
<!
<select id="getAllUser" resultType="User">
select * from ${tableName}
</select>
4.添加功能获取自增的主键
int insertUser(User user);
!
<insert id="insertUser" useGeneratedKeys="true" keyProperty="id">
insert into t_user values(null,
</insert>
|