1.1模糊查询
尝试:
//模糊查询用户
List<User> getUserByLike(@Param("mohu") String mohu);
<select id="getUserByLike" resultType="user">
select * from user where username like '%#{mohu}%'
</select>
@Test
public void testGetUserByLike(){
List<User> users = mapper.getUserByLike("q");
users.forEach(System.out::println);
}
结果:
Could not set parameters for mapping: ParameterMapping{property='mohu', mode=IN, javaType=class java.lang.Object, jdbcType=null, numericScale=null, resultMapId='null', jdbcTypeName='null', expression='null'}.
解决:
法1:看到上方报错结果没有单引号,所以采用$模式
select * from user where username like '%${mohu}%'
法2:concat是MySQL自己的语句,未来可移植性差
select * from user where username like concat ('%',#{mohu},'%')
法3:自己拼接(更常用)
select * from user where username like "%"#{mohu}"%"
1.2批量删除
尝试:
/**
* 批量删除
* @param ids
*/
void delectMoreUser(@Param("ids") String ids);
<delete id="delectMoreUser">
delete from user where id in(#{ids})
</delete>
@Test
public void testDelectMoreUser(){
mapper.delectMoreUser("7,8");
}
结果:
解决:(使用$)
delete from user where id in(${ids})
1.3动态设置表名
(1)写死动态表名进行测试
/**
* 动态设置表名,查询表信息
* @param tableName
* @return
*/
List<User> getUserList(@Param("tableName") String tableName);
<select id="getUserList" resultType="user">
select * from #{tableName}
</select>
@Test
public void testGetUserList(){
List<User> users = mapper.getUserList("user");
users.forEach(System.out::println);
}
结果:
解决:
select * from ${tableName}
(2)改造成实现动态的写法
List<Object> getList(@Param("tableName") String tableName);
<select id="getList" resultType="object">
select * from ${tableName}
</select>
@Test
public void testGetList(){
List<Object> objects = mapper.getList("user");
objects.forEach(System.out::println);
}
结果:只显示了第一列id的内容
解决如下:
List<Map<String,Object>> getList(@Param("tableName") String tableName);
@Test
public void testGetList(){
List<Map<String,Object>> users = mapper.getList("user");
users.forEach(System.out::println);
}
1.4添加功能获取自增的主键
useGeneratedKeys:表示当前添加功能实用自增的主键
keyProperty:将添加的数据的自增主键作为试题类类型的属性赋值
/**
* 添加用户信息并获取自增的主键
* @param user
*/
void insertUser(User user);
<!--
useGeneratedKeys:表示当前添加功能实用自增的主键
keyProperty:将添加的数据的自增主键作为试题类类型的属性赋值
-->
<insert id="insertUser" useGeneratedKeys="true" keyProperty="id">
insert into user values(null,#{username},#{password},#{age},#{sex},#{email})
</insert>
public void testInsertUser(){
User user = new User(null,"kk","1248",46,"男","78@qq.com");
mapper.insertUser(user);
//插入完成后需要知道id值
System.out.println(user);
}
最终数据添加成功