Mybatis-Mapper XML Files


The true power of MyBatis is in the Mapped Statements. This is where the magic happens. For all of their power, the Mapper XML files are relatively simple. Certainly if you were to compare them to the equivalent JDBC code, you would immediately see a savings of 95% of the code. MyBatis was built to focus on the SQL, and does its best to stay out of your way.

The Mapper XML files have only a few first class elements (in the order that they should be defined):

1、cache – Configuration of the cache for a given namespace.
2、cache-ref – Reference to a cache configuration from another namespace.
3、resultMap – The most complicated and powerful element that describes how to load your objects from
   the database result sets.
4、parameterMap – `Deprecated`! Old-school way to map parameters. Inline parameters are preferred and
   this element may be removed in the future. Not documented here.
5、sql – A reusable chunk of SQL that can be referenced by other statements.
6、insert – A mapped INSERT statement.
7、update – A mapped UPDATE statement.
8、delete – A mapped DELETE statement.
9、select – A mapped SELECT statement.

The next sections will describe each of these elements in detail, starting with the statements themselves.

select

The select statement is one of the most popular elements that you'll use in MyBatis. Putting data in a database isn't terribly valuable until you get it back out, so most applications query far more than they modify the data. For every insert, update or delete, there are probably many selects. This is one of the founding principles of MyBatis, and is the reason so much focus and effort was placed on querying and result mapping. The select element is quite simple for simple cases. For example:


This statement is called selectPerson, takes a parameter of type int (or Integer), and returns a HashMap keyed by column names mapped to row values.

Notice the parameter notation:

#{id}

This tells MyBatis to create a PreparedStatement parameter. With JDBC, such a parameter would be identified by a "?" in SQL passed to a new PreparedStatement, something like this:

// Similar JDBC code, NOT MyBatis…
String selectPerson = "SELECT * FROM PERSON WHERE ID=?";
PreparedStatement ps = conn.prepareStatement(selectPerson);
ps.setInt(1,id);

Of course, there's a lot more code required by JDBC alone to extract the results and map them to an instance of an object, which is what MyBatis saves you from having to do. There's a lot more to know about parameter and result mapping. Those details warrant their own section, which follows later in this section.

The select element has more attributes that allow you to configure the details of how each statement should behave.


  select
    ,
    
  from some_table t1
    cross join some_table t2

Property value can be also used in include refid attribute or property values inside include clause, for example:


  ${prefix}Table



  from
    



相关