- import java.util.LinkedHashMap;
- import java.util.List;
- import java.util.Map;
- import org.apache.ibatis.session.SqlSession;
- import cn.itcast.javaee.mybatis.util.MybatisUtil;
- /**
- * 持久层
- * @author AdminTC
- */
- public class StudentDao {
- /**
- * 有条件的查询所有学生
- */
- public List<Student> findAll(Integer id,String name,Double sal) throws Exception{
- SqlSession sqlSession = null;
- try{
- sqlSession = MybatisUtil.getSqlSession();
- Map<String,Object> map = new LinkedHashMap<String,Object>();
- map.put("pid",id);
- map.put("pname",name);
- map.put("psal",sal);
- return sqlSession.selectList("studentNamespace.findAll",map);
- }catch(Exception e){
- e.printStackTrace();
- throw e;
- }finally{
- MybatisUtil.closeSqlSession();
- }
- }
- public static void main(String[] args) throws Exception{
- StudentDao dao = new StudentDao();
- List<Student> studentList = dao.findAll(5,"哈哈",7000D);
- for(Student s : studentList){
- System.out.println(s.getId()+":"+s.getName()+":"+s.getSal());
- }
- }
- }
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <mapper namespace="studentNamespace">
- <resultMap type="cn.itcast.javaee.mybatis.app11.Student" id="studentMap">
- <id property="id" column="students_id"/>
- <result property="name" column="students_name"/>
- <result property="sal" column="students_sal"/>
- </resultMap>
- <select id="findAll" parameterType="map" resultMap="studentMap">
- select * from students
- <where>
- <if test="pid!=null">
- and students_id = #{pid}
- </if>
- <if test="pname!=null">
- and students_name = #{pname}
- </if>
- <if test="psal!=null">
- and students_sal = #{psal}
- </if>
- </where>
- </select>
- </mapper>
来源: http://www.bubuko.com/infodetail-2573774.html