The framework document mybatis in XxxxMaper.xml

We know that in mybatis framework, config.xml will be linked to many of the XxxxMapper xml file, and these files correspond to one interface to observe these xml files
This file is from the following example:
<?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="com.briup.mappers.StudentMapper"> 
 
The first is how to execute sql statement
<insert id="insertStudent" parameterType="Student"> 
            INSERT INTO STUDENTS(STUD_ID,NAME,EMAIL,PHONE) VALUES(#{studId},#{name},#{email},#{phone}) 
</insert> 

 

ID attribute insertStudent, com.briup.mappers.StudentMapper.insertStudent can name space in the current xml file uniquely identifies the sql statement. parameterType attribute is a fully qualified class name or a type alias alias.
This can be called the following sql statement:
  int count =  sqlSession.insert("com.briup.mappers.StudentMapper.insertStudent", student); 
sqlSession.insert () method returns the number of rows affected after an INSERT statement.
Or use mapping interface Mapper to call:
        public interface Student Mapper{ 
                int insertStudent(Student student); 
        } 
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); 
        int count = mapper.insertStudent(student);         
 
INSERT a, (auto-generated primary key)
In the INSERT statement, the value may be automatically generated in the primary key column STUD_ID.
KeyProperty properties make use useGeneratedKeys and database generation auto_increment column values ​​and the resulting value is set into one of the input object attributes, as follows:
    <insert id="insertStudent2" parameterType="Student" useGeneratedKeys="true" keyProperty="studId"> 
            INSERT INTO STUDENTS(NAME, EMAIL, PHONE) VALUES(#{name},#{email},#{phone}) 
    </insert> 
Here STUD_ID database column values will be generated automatically (e.g., MySQL ), and the resulting value is provided to the student object properties studId
Note :
        Some databases, such as the oracle , does not support AUTO_INCREMENT column, but may be used oracle sequence to generate the primary key value.
        For example: Use my_seq sequence to generate the primary key value SUTD_ID. Using the primary key to generate the following code:
        drop sequence my_seq;
        create sequence my_seq; 
    <insert id="insertStudent" parameterType="Student"> 
        <selectKey keyProperty="studId" resultType="int" order="BEFORE"> 
        SELECT my_seq.nextval FROM DUAL 
        </selectKey> 
        INSERT INTO STUDENTS(STUD_ID,NAME,EMAIL, PHONE) 
        VALUES(#{studId},#{name},#{email},#{phone}) 
    </insert> 
As used herein, the <selectKey> tag to obtain the primary key, and the stored values ​​to the attribute studId Student object. Properties order = "before" indicates, MyBatis will get the next value of the sequence as the primary key value, and the value of the property before the studId execute an INSERT statement.
 
update and delete
    <update id="updateStudent" parameterType="Student"> 
            UPDATE STUDENTS SET NAME=#{name}, EMAIL=#{email}, PHONE=#{phone} 
            WHERE STUD_ID=#{studId} 
    </update> 
    <delete id="deleteStudent" parameterType="int"> 
           DELETE FROM STUDENTS WHERE STUD_ID=#{id} 
    </delete> 
Note: insert updata delete labels are not resultType this property, but can not say that use of the three SQL statements corresponding method there is no return value, we can add a parameter of type int for the three methods in the interface, return is a value of type int, this value indicates the number of rows in SQL statements executed after impact.
 
SELECT query
        MyBatis real power lies in the mapping SELECT query results to various types of java. Speaking of inquiries, without mentioning the mapping result sets, there is a one-to-many mapping, mapping many to many.
        A simple select query the configuration, as follows:
    < SELECT ID = "findStudentById" the parameterType = "int"   
    the resultType = "Student" >  
        the SELECT STUD_ID, NAME, for EMAIL, PHONE   
            the FROM STUDENTS 
             <-! Where the value of # {}, if the transmission type is encapsulated in myBatis , such as int, Integer, this value of {#} parameter is done, not named -> 
             <! - If the type parameter is passed pojo different matter -> 
        the wHERE STUD_ID = # {studId } 
    </ SELECT >
 Write like this there is a problem, if there is no type in the Student STUD_ID properties and values ​​corresponding to check out, we can give the name of the column from the individual, if they encapsulate other said it resultMap
SELECT STUD_ID AS STUDID, NAME, EMAIL, PHONE  FROM STUDENTS  WHERE STUD_ID=#{studId} 
 
MyBatis execution returns multiple results SELECT statement to query
As follows:
    <select id="findAllStudents" resultType="Student"> 
        SELECT STUD_ID AS studId, NAME,EMAIL, PHONE  
        FROM STUDENTS 
    </select>
Note: Here, although the return value is written Student but still the result set of data is a List <Student> set type, the queried MyBatis will result set, packaged as an article Student object, then all the objects stored Student the collection is returned
 
Note that, in addition to List collection type, you can also use other types of collections, such as Set, Map and so on.
       
   MyBatis set according to the type, appropriate to achieve collection, as follows:
 
        For List, Collection, Iterable type,
            MyBatis will return java.util.ArrayList 
            If a plurality of data query, resultType specified package type, then the method can directly return value declared as a list a set of reception
        
  For type Map
            MyBatis will return java.util.HashMap 
            Note here that returns a key-value pair or multiple key-value pairs

 

            --- a key to check out the piece of data: the column names do K, the value of doing V, if detected multiple properties, it is stored in a number of KV on the map
            The return value is declared as the received set HashMap
            
            A plurality of key-value pairs --- a plurality of data query: use List <HashMap <K, V >> storage, a data corresponding to a HashMap
            The return value declared as List <HashMap <K, V >> set receiving
        
        For Set type,
            MyBatis will return java.util.HashSet 
 
        For type SortedSet
            MyBatis will return java.util.TreeSet ->
 
Result set mapping resultMap
        resultMap is used to map the results of a SELECT statement to the attribute set java object.
        
        In the mapping file, you can define the result set mapping resultMap, and then reference this resultMap in some SELECT statements.
     
        MyBatis result set mapping resultMap very powerful, it can be used to specify a sql query result set, it will be processed and packaged into how an object, you can also use it to complete the mapping of complex queries such as SELECT one to one, one to many relationship statements.
 
        resultMap tag attributes:
        id attribute values ​​are unique within the current name space.
        Value of the type attribute is the fully qualified name of the specified type or encapsulated into an alias. The properties and methods to return the same value
 
< The resultMap ID = "StudentResult" type = "com.briup.pojo.Student" >  
     <-! <Id> tag and sub <result> tag the same functionality, but <id> is the primary key for the mapping table. -> 
        < ID Property = "studId" column = "stud_id"  />  
          <-! <Result> tag is used to a sub resultset columns are mapped to a property of the object. -> 
          < Result Property = "name" column = "name"  />  
          < Result Property = "In Email" column = "In Email"  />  
          <  
</resultMap>
Note 1, the <select> tag, using resultMap attribute, not resultType properties.
        When <select> tag arranged resutlMap properties, MyBatis based on the object attribute names and column names resutlMap tag defined in [] corresponding relationship between the attribute value is automatically filled object.
        
 Note 2, and both resultType resultMap can only use one, not both.
        resultType attribute refers to the result set what type of automatic packaging. This time default table column names and class names consistent properties.
        resultMap attribute refers to the result set to encapsulate the data in the correspondence relationship [] <resultMap> tag defined.
 
    
Concluded that implementation under the sql statement again
 
1. string, call mapping files in SQL statements
        String is:
        id namespace mapping files + sql statement
        
        E.g:
            SqlSession sqlSession = MyBatisSqlSessionFactory.openSession(); 
            try{ 
                Student student = sqlSession.selectOne("com.briup.mappers.StudentMapper.findStudentById", 1); 
                System.out.println(student);
            } 
            finally { 
                sqlSession.close(); 
            } 

In this way prone to error because of the need to write your own string, we need to check the mapping file namespace, and sql statement defines the parameters and return values ​​of requirements to ensure that the input parameter types and return type of the result is valid. ->

2.MyBatis Mapper can also mapping interface through the use of call mapping file sql.
        The fully qualified name and namespace mapping interface of sql mapping file to be consistent.
        <mapper namespace="com.briup.mappers.StudentMapper"> 
        
        The method of mapping file name sql sql statement id value and mapping interface to be consistent.
        Method of parameter type and attribute mapping interface parameterType sql statement corresponding configuration consistent.
        Method returnType sql statement mapping interface properties and the corresponding configuration type of the return value consistent.
         <select id="findStudentById" parameterType="int" resultType="Student"> 
 
        For example: mapping interface StudentMapper.java
        package com.briup.mappers; 
        public interface StudentMapper{ 
            Student findStudentById(Integer id); 
        } 
 
        By mapping interface, call mapping files in SQL statements.
        code show as below:
        SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();  
        try { 
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class); 

 

            Student stu = studentMapper.findStudentById(1); 
        } 
        finally { 
            sqlSession.close(); 
        }  
    

Guess you like

Origin www.cnblogs.com/Magic-Li/p/11754605.html