目录
1.模糊查询
2.批量删除
3.动态设置表名
4.添加功能获取自增的主键
1.模糊查询
List<User> getUserByLike(@Param("username") String username);
<select id="getUserByLike" resultType="com.atguigu.mybatis.pojo.User"><!--select * from t_user where username like '%${username}%';--><!--select * from t_user where username like concat('%',#{username},'%');-->select * from t_user where username like "%"#{username}"%";
</select>
@Test
public void testGetUserByLike() {SqlSession sqlSession = SqlSessionUtils.getSqlSession();SqlMapper mapper = sqlSession.getMapper(SqlMapper.class);List<User> userList = mapper.getUserByLike("an");userList.forEach(System.out::println);
}
2.批量删除
int deleteMore(@Param("ids")String ids);
<!-- 批量删除不能使用#{},因为#{}会自动添加单引号,语法错误,必须使用${}-->
<delete id="deleteMore">deletefrom t_userwhere id in (${ids});
</delete>
@Test
public void testDeleteMore() {SqlSession sqlSession = SqlSessionUtils.getSqlSession();SqlMapper mapper = sqlSession.getMapper(SqlMapper.class);int row = mapper.deleteMore("1,2,8");System.out.println(row);
}
3.动态设置表名
List<User> getUserByTableName(@Param("tableName") String tableName);
<select id="getUserByTableName" resultType="User">select *from ${tableName};
</select>
@Test
public void testGetUserByTableName() {SqlSession sqlSession = SqlSessionUtils.getSqlSession();SqlMapper mapper = sqlSession.getMapper(SqlMapper.class);List<User> tableName = mapper.getUserByTableName("t_user");tableName.forEach(System.out::println);
}
4.添加功能获取自增的主键
/*** 添加用户信息 添加功能获取自增的主键* @param user* @return* useGeneratedKeys:设置使用自增的主键* keyProperty:因为增删改有统一的返回值是受影响的行数,* 因此只能将获取的自增的主键放在传输的参数user对象的某个属性中*/
int insertUser(User user);
<insert id="insertUser" useGeneratedKeys="true" keyProperty="id">insert into t_uservalues (null, #{username}, #{password}, #{age}, #{sex}, #{email});
</insert>
pper>