MyBatis mapping file configuration in detail

Common additions and changes to delete search

<?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.chy.mapper.StudentMapper">
    <insert id="insertStudent" parameterType="com.chy.pojo.Student">
        INSERT INTO student_tb(id,name,age,score)VALUES (#{id},#{name},#{age},#{score})
    </insert>

    <update id="updateStudent" parameterType="com.chy.pojo.Student">
        UPDATE student_tb SET name=#{name},age=#{age},score=#{score} WHERE id=#{id}
    </update>

    <delete id="deleteStudent" parameterType="Integer">
        DELETE FROM student_tb WHERE id=#{id}
    </delete>

    <select id="queryById" parameterType="Integer" resultType="com.chy.pojo.Student">
        SELECT * FROM student_tb WHERE id=#{id}
    </select>
</mapper>

<mapper> common mapping of namespace file is located in the  package and name of the mapping file name  . For example in the map file com.chy.mapper packet StudentMapper.xml => com.chy.mapper.StudentMapper

parameterType specify the data type of the parameter passed, resultType specify the query results are mapped to what type of data.

 

 

Student student = sqlSession.selectOne("com.chy.mapper.StudentMapper.queryById", 1);

Referenced by the namespace and the corresponding element ID , type of parameters passed parameterType. ResultType return data type specified.

 In fact, if you can uniquely identify the element to be referenced by the id, it can be omitted namespace, write-only id. 

 

 

 


 

 

 

Fuzzy query

Precise query: must be identical, such as WHERE name = 'chy', name field must be chy only match, not what chy1.

Fuzzy queries: long can comprise, for example WHERE name LIKE '% chy%', as long as the name field can contain chy, can match chy, 1chy1 ......

 

 

<select id="queryByName" parameterType="String" resultType="Student">
        SELECT * FROM student_tb WHERE name LIKE '%${value}%'
</select>

% Is a wildcard, representing the other characters.

$ # {} {} In addition to the functions, there ligation string.

 

 

{} $ Using insecure connection string, sql injection can not be prevented, for safety, as far as possible in the concat sql () function to connect string:

<select id="queryByName" parameterType="String" resultType="String">
        SELECT name FROM student_tb WHERE name LIKE concat('%',#{value},'%')
</select>

The string sql concat () function can be connected to a plurality of strings, to be connected to the incoming order.

Note that using a # {}

 

 

It contains the parameters passed to concat('%',#{value},'%') '%${value}%'
Beginning with the incoming parameters concat('%',#{value}) '%${value}'
At the end of the argument passed concat(#{value},'%') '${value}%'

 

 

 


  

 

If the incoming data is a simple type, such as numeric, String, # {}, {} $ can easily write a variable name, the name known sense to refer, generally written in # {} class field name pojo, $ { } often write value.

If the incoming object pojo class # {}, $ {name} field can only write pojo class.

 

 


 

 

 

pojo base class member variable, the basic data type mapping file, to make use of the type of packaging.

For example int => Integer, long => Long.

 

 

for example:

Absent of a classmate in the results table, the table of financial expenditure has not filled out this month,

If you use the sql 0 means, others thought it was a test of 0, this month expenditure is 0.

Fields did not use the null value representation. Others see a null, you know that this guy did not score, absent, this month's expenditure has not filled in.

 

 

Can be converted to numeric type of packaging, such as int type 0 can be converted to an Integer of 0;

However, many types of packaging than the base value of a numeric type: null, this value is not found in the basic value corresponding type.

 

 

private int score; we did not give this field assignment, jvm to the initial value is 0, 0 is inserted into the database.

private Integer score; we did not give this field assignment, jvm to the initial value of the wrapper class is null, inserted into the database is null. If the value is 0, assign to it wants score = 0, 0 is inserted so that the database.

Package Type more comprehensive than some basic types, the basic type can represent it also said it can not represent the basic types can also be expressed.

Pojo member variable classes, data type mapping file to make use of the package type.

 

 

 


 

 

 

 <Mapper> child element common

  • <select>、<insert>、<update>、<delete>
  • sql fragment <sql> is used to define a reusable
  • <resultMap>

 

 

<Select>, <insert>, <update>, <delete> have properties

  • userCache secondary cache control the opening, closing, Boolean value
  • After flushCache call sql statement, the local cache and secondary cache queries need to clear before, Boolean value
  • timeout Set timeout in seconds by default, the timeout will throw an exception
  • statementType jdbc use of which is provided mybatis statement to work, optional values: STATEMENT, PREPARED (default value), CALLABLE, respectively corresponding to the jdbc Statement, PreparedStatement, CallableStatement

 

 

<Select> element unique attributes

  • resultType query results are mapped to that type of data
  • resultMap reference <resultMap>
  • fetchSize get the total number of records

 

 


 

 

<ResultMap> Usage

<ResultMap> custom mapping rules for the query result set.

<resultMap id="" type="">
        <constructor>
            <idArg />
            <arg />
        </constructor>

        <id />
        <result />

        <association property="" />
        <discriminator javaType="">
            <case value="" />
        </discriminator>
</resultMap>

type specifies the result set is mapped to which data type.

<Constructor> for: pojo class provides parameterized constructor, but does not appear to provide no-argument constructor, using <constructor> with reference to the parameter passing constructor, <idArg> biographees key, <arg> Normal pass column.

<Id>, <result> for: pojo class only provides no argument constructor, assignment for the two elements (in essence calling setter methods) to members of the class of the instance variables pojo, <id> primary key transmission, <result> pass the normal field.

<Association> is used to specify one association, <discriminator> is used to specify many association.

 

 

Examples of Use

    <resultMap id="resultMap" type="com.chy.pojo.Student">
        <id property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="age" column="score"/>
        <result property="score" column="score"/>
    </resultMap>

    <select id="queryById" parameterType="Integer" resultMap="resultMap">
        SELECT * FROM student_tb WHERE id=#{id}
    </select>

property designated member variables pojo class, column designated fields in the table. Results automatically sets the specified field of the record is performed, the members assigned to instance variables pojo class.

The default property, column is the same, if the member variable name pojo class field names in the table is not the same, we need to configure their own <resultMap>.

In use resultMap <select> by reference id <resultMap>.

 

 

 


 

 

 

Primary key record insertion and self-energizing

Provided (1) designed to increment primary key tables, no value is set when a record of the primary key, the database will automatically set the value of id. After inserting the primary key field record automatically provided pojo instance of the class corresponding to the value:

<insert id="insertStudent" parameterType="com.chy.pojo.Student" keyProperty="id" useGeneratedKeys="true">
        INSERT INTO student_tb(name,age,score)VALUES (#{name},#{age},#{score})
</insert>

 the keyProperty, inserted, updated return value is assigned to the class designated field pojo operation, if you want to assign a plurality of fields, separated by commas.

useGeneratedKeys, the jdbc getGeneratedKeys to call () Gets the value of a database to the primary key field generated by the self-energizing.

 

Student student = new Student();
student.setName("chy");
sqlSession.insert("com.chy.mapper.StudentMapper.insertStudent", student);
System.out.println(student.getId());

 No need to provide the value of the primary key field.

 

 

 

(2) mysql, sql server can set the primary key increment, if we use this oracle is not automatically incremented primary key database or mysql, sql server increment primary key is not checked, it can be:

<insert id="insertStudent" parameterType="com.chy.pojo.Student">
        <selectKey keyProperty="id" resultType="Integer" order="BEFORE">
            select if(max(id) is null ,1,max(id)+1) from student_tb
        </selectKey>
        INSERT INTO student_tb(id,name,age,score)VALUES (#{id},#{name},#{age},#{score})
</insert>

 <SelectKey> is the primary key to query the database, the return value is assigned to <insert> incoming parameters (POJO example) primary key field.

keyProperty specify which attributes corresponding to the primary key pojo class, resultType specified returns the result (the primary key) which is mapped to the data type.

order to specify the order of execution. BEFORE: In execution <selectKey> insert before into; AFTER: before performing <selectKey> after performing insert into.

 

select if(max(id) is null ,1,max(id)+1) from student_tb

Id field maximum query (int) from the table, if a record is not, returns 1; if the recording, the maximum value of +1 id returned.

 

 

BEFORE we do not need to manually set the primary key field value:

Student student = new Student();
student.setName("chy");
sqlSession.insert("com.chy.mapper.StudentMapper.insertStudent", student);
System.out.println(student.getId());

 

 

 If AFTER, need to set the primary key field value manually:

student.setId(100);

 

 

Explanation

<Update> and <insert> having at least the same attributes, sub-elements, <update> id used to return the modified records.

 

 

 


 

 

 

<Sql> Usage Example

The original wording:

<select id="queryById" parameterType="Integer" resultType="com.chy.pojo.Student">
        SELECT * FROM student_tb WHERE id=#{id}
</select>

 

 

Use <sql> wording:

<sql id="tableName">
    student_tb
</sql>
<select id="queryById" parameterType="Integer" resultType="com.chy.pojo.Student">
    SELECT * FROM <include refid="tableName" /> WHERE id=#{id}
</select>

Sql statement defined in <sql> section code, then <include /> id through the parts of the code included.

Guess you like

Origin www.cnblogs.com/chy18883701161/p/12122079.html