mybatis-动态查询学习笔记

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mybatis-动态查询学习笔记相关的知识,希望对你有一定的参考价值。


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>

以上是关于mybatis-动态查询学习笔记的主要内容,如果未能解决你的问题,请参考以下文章

mybatis-动态查询学习笔记

Mybatis 学习笔记 —— 动态SQL关联查询

MyBatis-05-笔记

Mybatis学习笔记8:动态sql

Java技术篇!硬核!阿里内部消化的Mybatis学习笔记

mybatis学习(39):动态sql片段