MyBatis XML mapping file

MyBatis XML mapping file only a few top-level elements:
Cache: For a given namespace cache configuration,
cache-ref: other cache configuration namespace reference
resultMap: the most complex elements to describe how to load objects from the database result set
sql : reusable statement block can be referenced by other statements
insert: insert mapped statement
update: map update statement
delete: mapping delete statement
select: map query

select:

<select id="selectPerson" parameterType="int" resultType="hashmap">
  SELECT * FROM PERSON WHERE ID = #{id}
</select>

The statement called selectPerson, a receiving int (or Integer) type parameter and returns the object type of a HashMap. Wherein # {id} statement tells MyBatis to create a pretreatment (the PreparedStatement) parameters, mapping select substantially equal to the above (return results omitted):

String selectPerson = "SELECT * FROM PERSON WHERE ID=?";
PreparedStatement ps = conn.prepareStatement(selectPerson);
ps.setInt(1,id);

It can be seen using MyBatis mapping more simple and convenient.
Here are the attributes select:

<select
 <!--命名空间中唯一标识符,可以被用来引用这条语句8 -->
  id="selectPerson"
   <!--可选属性,传入语句的参数类完全限定名或别名,可通过类型处理器推断具体传入语句的参数,默认值为unset -->
  parameterType="int"
   <!--返回期望类型的类的完全限定名或别名,如果返回的是集合,应该设置为集合包含的类型,而不是集合本身, resultType 或 resultMap不能同时使用-->
  resultType="hashmap"
   <!-同上- -->
  resultMap="personResultMap"
   <!--如果设置为true,只要语句被调用,都会导致本地缓存和二级缓存被清空,默认值为false -->
  flushCache="false"
   <!--设置为true后,将会导致本条语句的结果被二级缓存,默认值为true -->
  useCache="true"
   <!-- 驱动程序等待数据库返回请求结果的秒数,默认值为unset,依赖驱动-->
  timeout="10"
   <!--驱动提示,尝试让驱动程序每次批量返回的结果行数和这个设置值相等,默认值为未设置(依赖驱动) -->
  fetchSize="256"
   <!--STATEMENT,PREPARED 或 CALLABLE 中的一个。这会让 MyBatis 分别使用 Statement,PreparedStatement 或 CallableStatement,默认值:PREPARED -->
  statementType="PREPARED"
   <!--FORWARD_ONLY,SCROLL_SENSITIVE, SCROLL_INSENSITIVE 或 DEFAULT(等价于 unset) 中的一个,默认值为 unset (依赖驱动) -->
  resultSetType="FORWARD_ONLY">

insert, update and delete:
Attribute description:
ID: A unique identifier for the namespace may be used to represent this statement
parameterType: To pass the fully qualified class name or alias parameter statement, optionally
flushCache: set to true, will result in the local cache and secondary cache is cleared, the default value to true
timeout: before the exception is thrown, the driver waits for a request to return a result of the number of seconds the database, the default value is not set (the unset)
useGeneratedKeys: this will make use JDBC MyBatis the method getGeneratedKeys internal database to remove the generated primary key, the default value to false
the keyProperty :( only useful to insert and update), a property unique indicia, MyBatis will selectKey getGeneratedKeys child element by the return value, or it is provided by the insert statement bond value
keyColumn :( only useful for insert and update) by the key value table column names generated in this database is provided only in some (like PostgreSQL) is necessary, when the first column is not the primary key columns of the table when You need to be set. If you want to generate a plurality of columns may be provided as a comma-separated list of attributes name.
databaseId: If the configuration database vendor identification (databaseIdProvider), MyBatis will load all without databaseId or match the current databaseId statement; if statement with or without have, no band will be ignored.

If your database supports auto-generated primary key fields (such as MySQL and SQL Server), then you can set useGeneratedKeys = "true", then put keyProperty set to the target property on OK. For example, if the Author table column type have been used for the automatic generation of the id, the sentence may be modified as follows:

<insert id="insertAuthor" useGeneratedKeys="true"
    keyProperty="id">
  insert into Author (username,password,email,bio)
  values (#{username},#{password},#{email},#{bio})
</insert>

If your database supports multiple-row inserts, you can also pass an Author array or collection, and return to the main auto-generated keys:

<insert id="insertAuthor" useGeneratedKeys="true"
    keyProperty="id">
  insert into Author (username, password, email, bio) values
  <foreach item="item" collection="list" separator=",">
    (#{item.username}, #{item.password}, #{item.email}, #{item.bio})
  </foreach>
</insert>

sql:
This element is used to define reusable SQL code segment, which may be included in the SQL code other statements, it may be statically set parameters. You may be set to different values in the different parameter placeholder statements comprising:

<sql id="userColumns"> ${alias}.id,${alias}.username,${alias}.password </sql>

The SQL fragment may be contained in other statements:

<select id="selectUsers" resultType="map">
  select
    <include refid="userColumns"><property name="alias" value="t1"/></include>,
    <include refid="userColumns"><property name="alias" value="t2"/></include>
  from some_table t1
    cross join some_table t2
</select>

Parameters:
simple parameter passing Example:

<select id="selectUsers" resultType="User">
  select id, username, password
  from users
  where id = #{id}
</select>

Example transfer complex objects:

<insert id="insertUser" parameterType="User">
  insert into users (id, username, password)
  values (#{id}, #{username}, #{password})
</insert>

A special data type specified in the parameter:

#{property,javaType=int,jdbcType=NUMERIC}

Number of digits after the decimal point is specified settings:

#{height,javaType=double,jdbcType=NUMERIC,numericScale=2}

MyBatis also supports more advanced data types such as structures (structs), but when using an out parameter, you must explicitly set the type of name. For example (again, in practice not do something like this to change):

#{middleInitial, mode=OUT, jdbcType=STRUCT, jdbcTypeName=MY_TYPE, resultMap=departmentResultMap}

String substitution:
inserting an escape character string directly in SQL statements. For example, like ORDER BY, it can be to use:

ORDER BY ${columnName}

When metadata (e.g., table name or column names) in the SQL statement is generated dynamically, string replacement can be very useful. For example, if you want to pass any one select data from a table, you do not need to write like this:

@Select("select * from user where id = #{id}")
User findById(@Param("id") long id);

@Select("select * from user where name = #{name}")
User findByName(@Param("name") String name);

@Select("select * from user where email = #{email}")
User findByEmail(@Param("email") String email);

You can write only one way:

@Select("select * from user where ${column} = #{value}")
User findByColumn(@Param("column") String column, @Param("value") String value);

Where $ {column} be directly replaced, and # {value} will be used? Pretreatment. Like this it is possible to achieve the above functions:

User userOfId1 = userMapper.findByColumn("id", 1L);
User userOfNameKid = userMapper.findByColumn("name", "kid");
User userOfEmail = userMapper.findByColumn("email", "[email protected]");

The results map:
about ResultMaps is designed with the thought, for the simple statements do not need to configure explicit mapping results, and for a bit more complex statements need only describe their relationship on the line
, for example:

<select id="selectUsers" resultMap="userResultMap">
  select user_id, user_name, hashed_password
  from some_table
  where id = #{id}
</select>

Guess you like

Origin blog.csdn.net/weixin_43638314/article/details/93378040