动态sql指根据不同的查询条件,生成不同的查询语句
Mapper文件:
<?xml version="1.0" encoding="UTF-8"?>
<mapper namespace="entity.User">
<select id="selectUser" resultType="entity.User">
select * from user where id=#{id}
</select>
<insert id="addUser" parameterType="entity.user" useGeneratedkeys="true">
insert into user(name,pwd) values(#{name},#{pwd})
</insert>
<select id="getUserByCondition" parameterType="" resultType="User">
select * from user
<where>
<if test="name!=null">
name like #{name}
</if>
</where>
</select>
</mapper>
dao访问:
public List<User> getAll(Map<String,Object> map)throws Exception{
SqlSession session=MyBatisUtil.getSession();
List<User> list=session.selectList("UserMapper.selectAll");
session.close();
return list;
}
测试:
package test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import dao.UserDao;
import entity.User;
public class testSelectAll {
public static void main(String[] args) throws Exception {
UserDao userDao = new UserDao();
Map<String, String> map = new HashMap<String, String>();
map.put("name", "zou");
List<User> list = userDao.getAll(null);
for (User u : list) {
System.out.println(u);
}
}
}