MyBatis multi-condition query and MyBatis Condition

Source: Internet
Author: User

MyBatis multi-condition query and MyBatis Condition

I. Multi-condition query using dynamic SQL

A: use if + where to implement multi-condition Query

First, the scenario needs to have a grade and class table. The first requirement is to perform conditional query based on the fuzzy query name and age. The interface layer method

 public  List<student>  getStudentByIf(student stu);

Second, the configuration of the ing File

 

 <select id="getStudentByIf" parameterType="stu" resultType="stu">        select * from student       <where>           <if test="stuAge!=0">           and stuAge>#{stuAge}       </if>             <if test="stuName!=null">                 and stuName LIKE '%' #{stuName} '%'             </if>       </where>    </select>

 

Test

StudentDao dao = MyBatis. getSessionTwo (). getMapper (studentDao. class); student stu = new student (); stu. setStuName ("z"); // stu. setStuAge (19); List <student> list = dao. getStudentByIf (stu); for (student item: list) {System. out. println ("----------" + item. getStuName ());}


Print Effect

---------- Zhangyu
---------- Zy
---------- Zy
---------- Zhang

 

 

B: choose when classification

This method is the same as the choose loop structure in java. To judge multiple situations, you only need to modify the ing file.

Interface Class

Public List <student> getAllStudentByLike (Map <String, Object> userMap); // use map as the parameter

 

Ing File

 <select id="getAllStudentByLike" parameterType="Map" resultType="stu">        select * from student        <where>        <choose>            <when test="stuName!=null">                 stuName like CONCAT('%',#{stuName},'%')            </when>            <when test="stuAge!=0">                 stuAge> #{stuAge}            </when>
<otherwise>
1=1
</otherwise>

</choose> </where> </select>

 

Result

zhangyuzyzyzhang

 

 

C: You can use foreach to complete complex queries in three ways,

First, the input parameter is of the array type.

// Upload a group of xueshengID public List <student> getStudentBystuId_foreach_array (Integer [] ints); ing file configuration <! -- Query student Interger by student id --> <select id = "getStudentBystuId_foreach_array" resultMap = "studentList"> select * from student <if test = "array. length> 0 "> where stuId IN/* input student Id IN array form */<foreach collection =" array "item =" stu "open =" ("separator = ", "close =") ">#{ stu} </foreach> </if> </select>

 

Test class

 

  Integer[] ints = {2,3,4};        List<student> list = dao.getStudentBystuId_foreach_array(ints);        for (student item:list) {            System.out.println(item.getStuName());        }

 

Type 2: Input list set

   public List<student> getStudentBystuId_foreach_list(List<Integer> list);

 

<! -- Follow the student id query method --> <select id = "getStudentBystuId_foreach_list" resultMap = "studentList"> select * from student <if test = "list. size> 0 "> where stuId IN/* sets to input student Id */<foreach collection =" list "item =" stu "open =" ("separator = ", "close =") ">#{ stu} </foreach> </if> </select>

 

Test:

 studentDao dao = MyBatis.getSessionTwo().getMapper(studentDao.class);        Integer ints = 2;        List<Integer> list = new ArrayList<Integer>();        list.add(ints);        List<student> stulist = dao.getStudentBystuId_foreach_list(list);        for (student item:stulist) {            System.out.println(item.getStuName());        }

 

Third: according to the Map set

 public List<student> getStudentBystuId_foreach_map(Map<String, Object> stuMap);

 

<! -- Query student map by student id --> <select id = "getStudentBystuId_foreach_map" resultMap = "studentList"> select * from student where stuId IN/* sets to input student Id */ <foreach collection = "stuId" item = "stu" open = "(" separator = ", "close =") "> <! -- Collection is defined by itself, that is, the key value of map -- >#{ stu} </foreach> </select>

 

  Map<String ,Object> stumap = new HashMap<String, Object>();        List<Integer> listStuId = new ArrayList<Integer>();        listStuId.add(2);        listStuId.add(3);        listStuId.add(4);        stumap.put("stuId",listStuId);         List<student> list = dao.getStudentBystuId_foreach_map(stumap);        for (student item:list             ) {            System.out.println(item.getStuName());        }

 

Run the following command to print the result.

D. One-to-multiple implementation methods

The configuration in resultMapper is different.

Interface Method

 public grade getGradeById(int gradeId);

 

Ing file configuration

<! -- Implement the first-to-many implementation --> <resultMap id = "gradeMapOne" type = "grade"> <id column = "gradeId" property = "gradeId"> </id> <result column = "gradeName" property = "gradeName"> </result> <collection property = "gatStudent" ofType = "stu"> <id column = "stuUd" property = "stuId"> </id> <result column = "stuName" property = "stuName"> </result> <result column = "stuAge" property = "stuAge"> </ result> </collection> </resultMap> <! -- Implement one-to-many second implementation --> <resultMap id = "gradeMap" type = "entity. grade "> <id column =" gradeId "property =" gradeId "> </id> <result column =" gradeName "property =" gradeName "> </result> <collection property = "gatStudent" ofType = "student" select = "getStudentById" column = "gradeId"> </collection> <! -- The value of column is mainly used as the condition for the next query, that is, the condition for querying students --> </resultMap>
    <select id="getGradeById" resultMap="gradeMapOne">        select * from grade,student where grade.gradeId = student.stuGrade and gradeId = #{gradeId}    </select>    <!--ddddddddddddddddddd-->    <select id="getGradeById" resultMap="gradeMap">        select * from grade where gradeId=#{gradeId}    </select>    <select id="getStudentById" resultType="entity.student">        select * from student where stuGrade = #{stuGrade}    </select>

 

 

 

 

  @Test    public void  TestConn(){       gradeDao dao = MyBatis.getSessionTwo().getMapper(gradeDao.class);       grade grade = dao.getGradeById(1);       for (student item:grade.getGatStudent()            ) {           System.out.println(item.getStuName());       }    }

 

Both methods can be implemented to print the results

Solution 1: print the results

==> Preparing: select * from grade, student where grade. gradeId = student. stuGrade and gradeId =? ============= An SQL
==> Parameters: 1 (Integer)
<= Columns: gradeId, gradeName, stuId, stuName, stuAge, stuGrade
<= Row: 1, S1297, 2, zhangyu, 19, 1
<= Row: 1, S1297, 3, zy, 20, 1
<= Row: 1, S1297, 4, zy, 21, 1
<= Total: 3
Zhangyu
Zy
Zy

Process finished with exit code 0

Solution 2: print the results

==> Preparing: select * from grade where gradeId =? =========== The first SQL
==> Parameters: 1 (Integer)
<= Columns: gradeId, gradeName
<= Row: 1, S1297
====> Preparing: select * from student where stuGrade =? ========= Second SQL
====> Parameters: 1 (Long)
<==== Columns: stuId, stuName, stuAge, stuGrade
<= Row: 2, zhangyu, 19, 1
<= Row: 3, zy, 20, 1
<= Row: 4, zy, 21, 1
<=== Total: 3
<= Total: 1
Zhangyu
Zy
Zy

Process finished with exit code 0

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.