码迷,mamicode.com
首页 > 其他好文 > 详细

MyBatis——动态查询(四)

时间:2017-10-06 18:08:33      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:col   source   close   beans   shm   err   oct   cat   apache   

beans包

package cn.alexander.beans;


public class Student {
    private Integer id;
    private String name;
    private Integer age;

    public Student() {
    }

    public Student(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public Student(Integer id, String name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }
    public Student(Integer id) {
        this.id = id;

    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name=‘" + name + ‘\‘‘ +
                ", age=" + age +
                ‘}‘;
    }
}

dao包

package cn.alexander.dao;

import cn.alexander.beans.Student;
import org.apache.ibatis.annotations.Param;
import org.junit.runners.Parameterized;

import java.util.List;
import java.util.Map;

/**
 * .动态查询
 *
 */
public interface IStudentDynamicDao {
    /**
     *01、用户传递一个Student对象  但是我们不知道用户对哪些属性赋值了
     */
    List<Student> selectStudentsByIf(Student student);
    /**
     *  choose标签,当年龄不为空,按照年龄查询,当姓名不为空,按照姓名查询
     *  当都为空是,执行一个标签otherwise
     */
    List<Student> selectStudentByChoose(Student student);
    /**
     * foreach 遍历数组
     */
    List<Student> selectStudentsByForeachArray(int...i);
    /**
     * foreach 遍历集合
     */
    List<Student> selectStudentsByForeachList(List<Integer> nums);
    /**
     * foreach 遍历对象集合
     */
    List<Student> selectStudentsByStudents(List<Student> nums);
    /**
     * foreach 遍历map集合
     */
    List<Student> selectStudentsByForeachMap(@Param("mymap") Map map);

}

util包

package cn.alexander.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * SqlSessionFactory的单例类
 */
public class SessionFactoryUtil {
    // 创建需要单例的对象实例
    private static SqlSessionFactory sessionFactory;

    // 私有化构造
    private SessionFactoryUtil(){}

    // 对外提供访问接口
    public static synchronized SqlSession getSession(){
        try {
            InputStream stream = Resources.getResourceAsStream("mybatis-config.xml");
            // 判断SqlSessionFactory是否为空,如果为空则创建
            if(sessionFactory==null){
                sessionFactory = new SqlSessionFactoryBuilder().build(stream);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sessionFactory.openSession();
    }


}

mapper

<?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">
<!--映射文件的根节点
  namespace
-->
<mapper namespace="cn.alexander.dao.IStudentDynamicDao">
    <!-- 用户传递一个Student对象,但是我们不知道用户对哪些属性赋了值-->
    <select id="selectStudentsByIf" resultType="cn.alexander.beans.Student">
        SELECT id,name,age from student_mybatis
        <where>
            <if test="name!=null and name!=‘‘">
                and name like concat(‘%‘,#{name},‘%‘)
            </if>
            <if test="age&gt;0">
                and age > #{age}
            </if>
        </where>
    </select>
<!-- 类似Java中的switch
      choose标签,当年龄不为空,按照年龄查询,当姓名不为空,按照姓名查询
      当都为空是,执行一个标签otherwise
     -->
    <select id="selectStudentByChoose" resultType="Student">
        SELECT id,name,age from student_mybatis
        <where>
            <choose>
                <when test="name!=null and name!=‘‘">
                    and name like concat(‘%‘,#{name},‘%‘)
                </when>
                <when test="age&gt;0">
                    and age > #{age}
                </when>
                <otherwise>
                    1!=1
                </otherwise>
            </choose>
        </where>
    </select>
    <!-- foreach 遍历数组  -->
    <select id="selectStudentsByForeachArray" resultType="Student">
        SELECT id,name,age from student_mybatis
        <if test="array.length>0">
            <where>
                id in
                <foreach collection="array" item="varId" open="(" separator="," close=")" >
                        #{varId}
                </foreach>
            </where>
        </if>
    </select>
    <!-- foreach 遍历集合  -->
    <select id="selectStudentsByForeachList" resultType="Student">
        SELECT id,name,age from student_mybatis
        <if test="list.size>0">
            <where>
                id in
                <foreach collection="list" item="varId" open="(" separator="," close=")" >
                    #{varId}
                </foreach>
            </where>
        </if>
    </select>

    <!-- foreach 遍历对象集合  -->
    <select id="selectStudentsByStudents" resultType="Student">
        SELECT id,name,age from student_mybatis
        <if test="list.size>0">
            <where>
                id in
                <foreach collection="list" item="stu" open="(" separator="," close=")" >
                    #{stu.id}
                </foreach>
            </where>
        </if>
    </select>
    <!-- foreach 遍历map集合  -->
    <select id="selectStudentsByForeachMap" resultType="Student">
        SELECT id,name,age from student_mybatis
        <if test="mymap.keys.size>0">
            <where>
                id in
                <foreach collection="mymap.keys"  item="mapKey" open="(" separator="," close=")" >
                    #{mapKey}
                </foreach>
            </where>
        </if>
    </select>
</mapper>

测试类

package cn.alexander.test;

import cn.alexander.beans.Student;
import cn.alexander.dao.IStudentDynamicDao;
import cn.alexander.util.SessionFactoryUtil;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Shinelon on 2017/10/6.
 */
public class StudentTest {
    IStudentDynamicDao dao = null;
    SqlSession session = null;
    Logger log = Logger.getLogger(StudentTest.class);

    @Before
    public void before(){
        session = SessionFactoryUtil.getSession();
        dao = session.getMapper(IStudentDynamicDao.class);
    }


    @Test
    public void testIf(){
      Student student = new Student();
      student.setName("小");
      student.setAge(12);
        List<Student> students = dao.selectStudentsByIf(student);
        log.debug(students);
    }
    @Test
    public void testChoose(){
        Student student = new Student();
        student.setName("小");
        List<Student> students = dao.selectStudentByChoose(student);
        log.debug(students);
    }


    @Test
    public void testArrayForeach(){
        int [] nums={2,3,4};
        List<Student> students = dao.selectStudentsByForeachArray(nums);
        log.debug(students);
    }

    @Test
    public void testListForeach(){
        List<Integer> list = new ArrayList<Integer>();
        list.add(2);
        list.add(3);
        list.add(4);
        List<Student> students = dao.selectStudentsByForeachList(list);
        log.debug(students);
    }
    @Test
    public void testObjectListForeach(){
        List<Student> list = new ArrayList<Student>();
        list.add(new Student(2));
        list.add(new Student(3));
        list.add(new Student(4));
        List<Student> students = dao.selectStudentsByStudents(list);
        log.debug(students);
    }
    @Test
    public void selectStudentsByForeachMap(){
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("2","object1");
        map.put("3","object2");
        map.put("4","object3");
        List<Student> students = dao.selectStudentsByForeachMap(map);
        log.debug(students);
    }

    @After
    public void after(){
        if(session!=null){
            session.close();
        }
    }

}

 

MyBatis——动态查询(四)

标签:col   source   close   beans   shm   err   oct   cat   apache   

原文地址:http://www.cnblogs.com/alexanderthegreat/p/7631828.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!