模糊查找
使用关键字like
List<User> findByName(String username);
<!-- 根据名称模糊查询 -->
<select id="findByName" resultType="com.itheima.domain.User" parameterType="String">
select * from user where username like #{username}
</select>
@Test
public void testFindByName(){
List<User> users = userDao.findByName("%王%");
for(User user : users){
System.out.println(user);
}
}
查询编写的QueryVo对象
该写法是将前面的模糊查询的条件,封装到了QueryVo对象当中
public interface IUserDao {
List<User> findByVo(QueryVo vo);
}
public class QueryVo implements Serializable {
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
- XML文件
parameterType是传输#{ }对象的类型属于那一类 resultType是封装数据的类型
<!-- 根据用户名称模糊查询,参数变成一个 QueryVo 对象了 -->
<select id="findByVo" resultType="com.itheima.domain.User"
parameterType="com.itheima.domain.QueryVo">
select * from user where username like #{user.username};
</select
@Test
public void testFindByQueryVo() {
QueryVo vo = new QueryVo();
User user = new User();
user.setUserName("%王%");
vo.setUser(user);
List<User> users = userDao.findByVo(vo);
for(User u : users) {
System.out.println(u);
}
}
标签使用
多条件查询,与前面的QueryVo有点类似
if标签 查询的条件有可能是用户名,有可能是性别,也有可能是地址
List<User> findByUser(User user);
<select id="findByUser" resultType="user" parameterType="user">
select * from user where 1=1
<if test="username!=null and username != '' ">
and username like #{username}
</if>
<if test="address != null">
and address like #{address}
</if>
</select
@Test
public void testFindByUser() {
User u = new User();
u.setUsername("%王%");
u.setAddress("%顺义%");
List<User> users = userDao.findByUser(u);
for(User user : users) {
System.out.println(user);
}
}
|