1.模糊查询
①在SQLMapper接口里写上方法
/**
* 根据用户名,模糊查询
*/
List getUserByLike(@Param("username") String username);
②在SQLMapper.xml配置类里
用的最多
select * from t_user where username like "%"#{username}"%"
替换
select * from t_user where username like '%${username}%'
select * from t_user where username like concat('%',#{username},'%')
③测试
@Test
public void t1() {
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SQLMapper mapper = sqlSession.getMapper(SQLMapper.class);
List listUser = mapper.getUserByLike("t");
for (User u : listUser) {
System.out.println(u);
}
}
2.批量删除
只能使用${}
#和$两者含义不同
#会把传入的数据都当成一个字符串来处理,会在传入的数据上面加一个双引号来处理。
而$则是把传入的数据直接显示在sql语句中,不会添加双引号。
①在SQLMapper接口里
/**
* 根据多个id,批量删除
*/
int deleteUserByIds(@Param("ids") String ids);
②在SQLMapper.xml配置
delete from t_user where id in (${ids})
③测试
@Test
public void t1() {
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SQLMapper mapper = sqlSession.getMapper(SQLMapper.class);
int i = mapper.deleteUserByIds("1,45,3");
System.out.println(i);
}
3.动态设置表名
只能使用${tableName} 表名没有单引号
①在SQLMapper接口中
/**
* 查询指定表名的数据
*/
List getUserByTableName(@Param("tableName") String tableName);
②在SQLMapper.xml中
③测试
@Test
public void t1() {
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SQLMapper mapper = sqlSession.getMapper(SQLMapper.class);
List t_user = mapper.getUserByTableName("t_user");
for (User user : t_user) {
System.out.println(user);
}
}
4.添加功能获取自增的主键
①SQLMapper接口中
/**
* 添加用户信息
*/
int addUser(User user);
②在SQLMapper.xml中。[1]. useGeneratedKeys:使用递增主键,KeyProperty:将自增主键的值赋值给传输到映射文件User参数的某个属性
insert into t_user values(null,#{username},#{password},#{email})
③测试
@Test
public void t1() {
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SQLMapper mapper = sqlSession.getMapper(SQLMapper.class);
User user = new User(null, "wang", "zgiu", "lei");
int i = mapper.addUser(user);
// 此时user的id有值了,把自动递增的id,存放到传过来的User对象中
System.out.println(user.getId());
}