Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

MyBatis Java API


May 16, 2021 MyBatis


Table of contents


Java API

Now that you know how to configure MyBatis and create mapping files, you're ready to upgrade your skills. M yBatis' Java API is where you get what you're trying to do. A s you'll soon see, MyBatis greatly simplifies your code and remains concise, easy to understand and maintain compared to JDBC. MyBatis 3 has introduced a number of important improvements to make SQL mapping even better.

Apply the directory structure

Before we dive into the Java API, it's important to understand best practices about directory structures. M yBatis is very spiritual, you can do almost anything with your own files. But there are some best ways for any framework.

Let's take a look at the directory structure of a typical application:

/my_application
  /bin
  /devlib
  /lib                <-- MyBatis *.jar文件在这里。
  /src
    /org/myapp/
      /action
      /data           <-- MyBatis配置文件在这里, 包括映射器类, XML配置, XML映射文件。
        /mybatis-config.xml
        /BlogMapper.java
        /BlogMapper.xml
      /model
      /service
      /view
    /properties       <-- 在你XML中配置的属性 文件在这里。
  /test
    /org/myapp/
      /action
      /data
      /model
      /service
      /view
    /properties
  /web
    /WEB-INF
      /web.xml

Remember, these are preferences, not requirements, but others will thank you for using a common directory structure.

The remaining examples in this section will assume that you are using this directory structure.

SqlSessions

The main Java interface that uses MyBatis is SqlSession. A lthough you can use this interface to execute commands, get a mapping machine and manage transactions. W e'll talk more about SqlSession itself, but first we need to understand if we get a SqlSession instance. S qlSessions was created by an instance of SqlSessionFactory. S qlSesionFactory has a way of creating sqlSession for examples like packages. SqlSesionFactory itself was created by SqlSesionFactory Builder to create SqlSesionFactory from XML configuration, annotation, or manual configuration of Java.

NOTE When using MyBatis with a dependency injection framework like Spring or Guice, SqlSessions are created and injected by the DI framework so you don't need to use the SqlSessionFactoryBuilder o r SqlSessionFactory and can go directly to the SqlSession section. Please refer to the MyBatis-Spring or MyBatis-Guice manuals for further info.

SqlSessionFactoryBuilder

SqlSesionFactoryBuilder has five build() methods, each of which allows you to create a SqlSesion instance from a different resource.

    SqlSessionFactory build(InputStream inputStream)
    SqlSessionFactory build(InputStream inputStream, String environment)
    SqlSessionFactory build(InputStream inputStream, Properties properties)
    SqlSessionFactory build(InputStream inputStream, String env, Properties props)
    SqlSessionFactory build(Configuration config)

The first method is the most commonly used, using a Reader instance that refers to an XML document or a more specific mybatis-config file .xml discussed above. T he optional parameters are environment and properties. E nvironment determines which environment to load, including data sources and transaction managers. Like what:

<environments default="development">
  <environment id="development">
    <transactionManager type="JDBC">
        ...
    <dataSource type="POOLED">
        ...
  </environment>
  <environment id="production">
    <transactionManager type="MANAGED">
        ...
    <dataSource type="JNDI">
        ...
  </environment>
</environments>

If you call a build method that uses the environment parameter square, MyBatis will use the configuration object to configure the environment. O f course, if you specify an illegal environment, you get an error prompt. If you call one of these build methods that does not have an environment parameter, use the default environment (which in the example above is specified as default"development").

If you call methods that use properties instances, MyBatis loads those properties (attribute profiles) and you can use them in your configuration. Those properties can be used more than once in the configuration file in the form of a $(propName) syntax.

Recall that a property can be referenced from a mybatis-config .xml, or you can specify it directly. T herefore, it is important to understand the priority level. We mentioned it earlier in the documentation, but here's again:

If a property exists in these locations, MyBatis will load them in the following order:

  • The properties specified in the properties element body are read first.
  • The second property specified from the class path resource or url of the properties element is read, which overrides the duplicate properties that have already been specified.
  • Properties passed as method parameters are read at the most and can override any duplicate properties that have been loaded from the properties metasome and resource/url properties.

Therefore, the highest priority properties are passed through method parameters, followed by the resource/url property, and most later specified in the properties element body.

To sum up, the first four methods are largely the same, but because they can be overwritten, you are allowed to specify environment and/or properties optionally. Here's an example of creating sqlSessionfactory .xml from a mybatis-config file:

    String **resource** = "org/mybatis/builder/mybatis-config.xml";
    InputStream **inputStream** = Resources.getResourceAsStream(resource);
    SqlSessionFactoryBuilder **builder** = new SqlSessionFactoryBuilder();
    SqlSessionFactory **factory** = builder.build(inputStream);

Note that here we use the Resources tool class, which is org.mybatis.io package. T he Resources class, as its name says, helps you load resource files from under the class path, from the file system, or from a web URL. I f you look at the source code for this class or look at it through your IDE, you'll see a whole range of useful methods. Here's a short table:

    URL getResourceURL(String resource)
    URL getResourceURL(ClassLoader loader, String resource)
    InputStream getResourceAsStream(String resource)
    InputStream getResourceAsStream(ClassLoader loader, String resource)
    Properties getResourceAsProperties(String resource)
    Properties getResourceAsProperties(ClassLoader loader, String resource)
    Reader getResourceAsReader(String resource)
    Reader getResourceAsReader(ClassLoader loader, String resource)
    File getResourceAsFile(String resource)
    File getResourceAsFile(ClassLoader loader, String resource)
    InputStream getUrlAsStream(String urlString)
    Reader getUrlAsReader(String urlString)
    Properties getUrlAsProperties(String urlString)
    Class classForName(String className)

The last build method uses a Configuration instance. T he configuration class contains everything you might need to solve sqlSessionFactory instances. T he Configuration class is useful for configured self-examination and includes finding and operating SQL maps (not recommended because the app is receiving requests). T he configuration class has all the configured switches, which you already know and are only exposed in the Java API. Here's a simple example of how to manually configure a configuration instance and pass it to the build() method to create SqlSesionFactory.

    DataSource dataSource = BaseDataTest.createBlogDataSource();
    TransactionFactory transactionFactory = new JdbcTransactionFactory();

    Environment environment = new Environment("development", transactionFactory, dataSource);

    Configuration configuration = new Configuration(environment);
    configuration.setLazyLoadingEnabled(true);
    configuration.setEnhancementEnabled(true);
    configuration.getTypeAliasRegistry().registerAlias(Blog.class);
    configuration.getTypeAliasRegistry().registerAlias(Post.class);
    configuration.getTypeAliasRegistry().registerAlias(Author.class);
    configuration.addMapper(BoundBlogMapper.class);
    configuration.addMapper(BoundAuthorMapper.class);

    SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
    SqlSessionFactory factory = builder.build(configuration);

Now you have a SqlSessionFactory that you can use to create SqlSession instances.

SqlSessionFactory

SqlSesionFactory has six ways to create sqlSession instances. In general, how to decide is when you choose these methods:

  • Transaction: Do you want to use transactions for session or auto-commit (usually meaning that many databases and/or JDBC drivers do not have transactions)?
  • Connection: Do you want MyBatis to get a connection from a configured data source or provide it yourself
  • Execution: Do you want MyBatis to use preprocessed statements and/or bulk update statements (including insertion and deletion)?

Overloaded openSession() method signature settings allow you to select any of these optional combinations.

    SqlSession openSession()
    SqlSession openSession(boolean autoCommit)
    SqlSession openSession(Connection connection)
    SqlSession openSession(TransactionIsolationLevel level)
    SqlSession openSession(ExecutorType execType,TransactionIsolationLevel level)
    SqlSession openSession(ExecutorType execType)
    SqlSession openSession(ExecutorType execType, boolean autoCommit)
    SqlSession openSession(ExecutorType execType, Connection connection)
    Configuration getConfiguration();

The default openSession() method has no parameters, and it creates SqlSession with the following characteristics:

  • A transaction is opened (i.e. not automatically committed)
  • Connection objects are available from instances of data sources configured by the active environment.
  • The transaction isolation level will use the default settings for the driver or data source.
  • Preprocessed statements are not re-used and updates are not processed in bulk.

Most of these methods can be self-explanatory. T urn on auto-commit, and "true" is passed to the optional autoCommit parameter. P rovides a custom connection that passes a Connection instance to the connection parameter. N ote that there is no way to override setting both Connection and autoCommit, because MyBatis uses the settings provided by the current connection object. MyBatis uses a Java enumeration wrapper for transaction isolation level calls, called TransactionIsolationLevel, otherwise they work as expected and have JDBC-supported Level 5 (NONE, READ_UNCOMMITTED,READ_COMMITTED, REPEA TABLE_READ, SERIALIZA BLE)

Another parameter that may be new to you is ExecutorType. This enumeration type defines three values:

  • ExecutorType.SIMPLE This executor type doesn't do anything special. It creates a new preprocessed statement for the execution of each statement.
  • ExecutorType.REUSE This executor type reuses preprocessed statements.
  • ExecutorType.BATCH This executor executes all update statements in bulk, and if SELECT executes among them, it also descens them as necessary to ensure a simple and easy-to-understand behavior.

Note There's another method in SqlSessionFactory that we didn't mention, which is getConfiguration(). This method returns a Configuration instance that you can use at runtime from the configuration of The MyBatis.

Note If you've already used the previous version of MyBatis, you'll want to recall that those sessions, transactions, and batch are all separate. I t's different now and then, and it's all within the scope of session. You need to handle separate transactions or bulk operations to get their effect.

SqlSession

As mentioned above, sqlSession instances are a very powerful class in MyBatis. Here you'll find all the methods for executing statements, commit or roll back transactions, and get mapping instances.

There are more than 20 methods in the SqlSession class, so separate them into easy-to-understand combinations.

The execution method of the statement

These methods are used to execute SELECT, INSERT, UPDA E T, and DELETE statements defined in the XML file of SQL mapping. They all interpret themselves, and each sentence uses the statement's ID properties and parameter objects, which can be native types (auto-boxing or wrapping classes), JavaBean, POJO, or Map.

     T selectOne(String statement, Object parameter)
     List selectList(String statement, Object parameter)
     Map selectMap(String statement, Object parameter, String mapKey)
    int insert(String statement, Object parameter)
    int update(String statement, Object parameter)
    int delete(String statement, Object parameter)

The difference between selectOne and selectList is simply that selectOne must return an object. I f there is one more, or if no return (or null is returned), an exception is thrown. If you don't know how many objects you need, use selectList.

If you want to check for the existence of an object, it's a good idea to return a statistic (0 or 1). Because not all statements require parameters, these methods have different overloaded versions, and they can not require parameter objects.

     T selectOne(String statement)
     List selectList(String statement)
     Map selectMap(String statement, String mapKey)
    int insert(String statement)
    int update(String statement)
    int delete(String statement)

Finally, there are three advanced versions of query methods that allow you to limit the range of rows returned, or provide self-determined result control logic, which is typically used for large collections of data.

<E> List<E> selectList (String statement, Object parameter, RowBounds rowBounds)
<K,V> Map<K,V> selectMap(String statement, Object parameter, String mapKey, RowBounds rowbounds)
void select (String statement, Object parameter, ResultHandler<T> handler)
void select (String statement, Object parameter, RowBounds rowBounds, ResultHandler<T> handler)

The RowBounds parameter tells MyBatis to skip a specified number of records and limits the number of returned results. The RowBounds class has a construction method to receive offset and limit, otherwise it cannot be changed.

    int offset = 100;
    int limit = 25;
    RowBounds rowBounds = new RowBounds(offset, limit);

Different drivers achieve different levels of efficiency in this regard. For the best performance, use the SCROLL_SENSITIVE or SCROLL_INSENSITIVE of the result set type (or say: FORWARD_ONLY).

The ResultHandler parameter allows you to handle each row the way you like. Y ou can add it to the List, create a Map, or throw each result instead of just keeping the total. Set There are a lot of nice things you can do with ResultHandler, which is create a list of result sets inside MyBatis.

Its interface is simple.

    package org.apache.ibatis.session;
    public interface ResultHandler {
      void handleResult(ResultContext context);
    }

The ResultContext parameter gives you a way to access the result object itself, a large number of result objects are created, and you can use the stop() method of the Buer return value to stop MyBatis from loading more results.

The transaction control method

There are four ways to control the scope of a transaction. O f course, if you've chosen auto-commit or you're using an external transaction stewer, it doesn't work. However, if you are using a JDBC transaction administrator, controlled by the Connection practice, these four methods come in use:

    void commit()
    void commit(boolean force)
    void rollback()
    void rollback(boolean force)

MyBatis does not automatically commit transactions by default, unless it detects that there is an insert, update or delete operation that changes the database. I f you've made some changes and haven't used these methods, you can pass the commit to and rollback methods to ensure that it's committed (note that you can't force session in auto-commit mode, or when you use an external transaction manager). A lot of times you don't have to call rollback(), because MyBatis will do it for you if you don't call commit. However, if you need more fine-grained control of sessions that are possible for multiple commits and rollbacks, you can use the rollback selection to make it possible.

NOTE MyBatis-Spring and MyBatis-Guice provide declarative transaction handling. So if you are using MyBatis with Spring or Guice please refer to their specific manuals.

Clean up the Session-level cache
void clearCache()

The SqlSession instance has a local cache that is cleaned up when performing update, commit, rollback, and close. To explicitly close it (get intended to do more work), you can call clearCache().

Make sure that SqlSession is turned off
void close()

The most important thing you have to make sure is that you want to close any sessions that are opened. The best way to ensure this is the following working mode:

    SqlSession session = sqlSessionFactory.openSession();
    try {
        // following 3 lines pseudocod for "doing some work"
        session.insert(...);
        session.update(...);
        session.delete(...);
        session.commit();
    } finally {
        session.close();
    }

Or, If you are using jdk 1.7+ and MyBatis 3.2+, you can use the try-with-resources statement:

    try (SqlSession session = sqlSessionFactory.openSession()) {
        // following 3 lines pseudocode for "doing some work"
        session.insert(...);
        session.update(...);
        session.delete(...);
        session.commit();
    }

Note Just like SqlSessionFactory, you can get the Configuration instance that SqlSession uses by calling the getConfiguration() method

    Configuration getConfiguration()
Use a map
     T getMapper(Class type)

The insert, update, delete, and select methods above are powerful, but they are cumbersome, type-safe, not helpful to your IDE, and possibly unit testing. We've seen an example of using a maper in the Getting Started section above.

Therefore, a more general way to execute a mapping statement is to use a mapster class. A mapor class is a simple interface where the method definition matches the SqlSession method. The following example shows some method signatures and how they map to SqlSession.

    public interface AuthorMapper {
      // (Author) selectOne("selectAuthor",5);
      Author selectAuthor(int id);
      // (List) selectList("selectAuthors")
      List selectAuthors();
      // (Map) selectMap("selectAuthors", "id")
      @MapKey("id")
      Map selectAuthors();
      // insert("insertAuthor", author)
      int insertAuthor(Author author);
      // updateAuthor("updateAuthor", author)
      int updateAuthor(Author author);
      // delete("deleteAuthor",5)
      int deleteAuthor(int id);
    }

In summary, each mapping method signature should match the associated SqlSesion method without a string parameter ID. Instead, the method name must match the ID of the mapping statement.

In addition, the return type must match the desired result type. All commonly used types are supported, including native classes, Map, POJO, and JavaBean.

The map interface does not need to implement any interface or extend any class. As long as the method can be used earlier to uniquely identify the mapping statement to .

Map interfaces can extend other interfaces. W hen using XML to build a maper interface, make sure that there are statements in the appropriate namespace. Also, the only limitation is that you can't have the same method signature on the interfaces of the two inheritance relationships (which is also a bad idea).

You can pass multiple parameters to a mapping method. I f you do, by default they will be named after where they are in the list of parameters, such as: . If you want to change the name of the argument (in the case of multiple parameters only), you can use @Param ("paramName") annotations on the parameter.

You can also pass a RowBounds instance to the method to limit the query results.

Maper annotations

Because MyBatis was originally designed as an XML-driven framework. C onfiguration information is XML-based, and mapping statements are defined in XML. A nd with MyBatis 3, there are new options available. M yBatis 3 builds on a comprehensive and powerful Java configuration API. T his configuration API is the foundation of the XML-based MyBatis configuration and the basis for the new annotation-based configuration. Annotations provide an easy way to implement simple mapping statements without introducing a lot of overhead.

Note Unfortunately, Java annotations limit their performance and flexibility. A lthough a lot of time is spent investigating, designing, and experimenting, it's not funny that the most powerful MyBatis mapping can't be built with annotations. T here are no such limitations in the C#property (as an example), so MyBatis.NET will have a richer choice than XML. That is, Java annotation-based configuration is dependent on its characteristics.

The annotations have the following:

Annotations Use objects XML equivalent Describe
@CacheNamespace Class <cache> Configure the cache for a given namespace, such as a class. implemetation eviction flushInterval size readWrite blocking properties
@Property N/A <property> Specifies a parameter value or placeholder can be replaced mybatis-config.xml in the file. P roperty: name value (Available only in MyBatis 3.4.2 or more)
@CacheNamespaceRef Class <cacheRef> Refers to the cache of another namespace for use. N ote that even if you share the same fully qualified class name, the cache declared in the XML mapping file is recognized as a separate namespace. P roperties: value name . I f you use this annotation, you should value of the value or name properties. value property specifies the Java type that can represent the namespace (the namespace name is the fully qualified class name of name property (this property is only available above MyBatis 3.4.2) directly specifies the name of the namespace.
@ConstructorArgs Method <constructor> Collect a set of results to pass to a result object's construction method. Property: value, which is an Arg array.
@Arg N/A
  • <arg>
  • <idArg>
Part of the ConstructorArgs collection that represents a construction method parameter. P roperties: id, column, javaType, jdbcType, typeHandler, select, resultMap. T he id property is similar to the XML element, slt;idArg, which is a Boolean value that indicates whether the property is used for unique identification and comparison objects. Starting with version 3.5.4, the annotation becomes repeatable.
@TypeDiscriminator Method <discriminator> A set of values (case) that determines what result mapping to use. P roperties: column, javaType, jdbcType, typeHandler, cases. The case property is an array of Cases.
@Case N/A <case> Represents a value that is taken and the map that corresponds to that value. P roperties: value, type, results. The results property is an array of Results, so this annotation is actually similar to ResultMap and is specified by the Results annotation below.
@Results Method <resultMap> A set of result maps that specify how a particular result column is mapped to a property or field. P roperties: value, id. T he value property is an array of Result annotations. T he id property, on the other hand, is the name of the result map. Starting with version 3.5.4, the annotation becomes repeatable.
@Result N/A
  • <result>
  • <id>
A single result map between a column and a property or field. P roperties: id, column, javaType, jdbcType, typeHandler, one, many. T he id property is similar to the XML element , which is a Boolean value that indicates whether the property is used for unique identification and comparison objects. T he one property is an association, similar to the .lt;association,, while the many property is a collection association, and the .lt;collection is similar. This is named to avoid name conflicts.
@One N/A <association> A single property map of a complex type. P roperty: select, which specifies a fully qualified name for a mapping statement (that is, a mapping method) that can load a suitable type of instance; fetchType, which specifies that the global configuration parameter lazyLoadingEnabled is overwritten in the map; resultMap (3.5.5), is which the fully qualified name of the a result map map to a s ingle container object from select result; columnPrefix(available since 3.5.5), which is column prefix for grouping select columns at nested result map. T ip The Annotation API does not support federation mapping. This is because Java annotations do not allow circular references to be generated.
@Many N/A <collection> Collection property mapping of complex types. P roperty: select, which specifies that the mapping statement (i.e. the mapping method) of the appropriate set of instances can be loaded, fetchType, which specifies that the global configuration parameter lazyLoadingEnabled resultMap (3.5.5) is overwritten in the map, and is there the fully qualified name of the a result map that map map to c ollection object from select result; columnPrefix(available since 3.5.5), which is column prefix for grouping select columns at nested result map. T ip The Annotation API does not support federation mapping. This is because Java annotations do not allow circular references to be generated.
@MapKey Method Annotations for methods that return a value of Map. I t uses a property of the object as key to convert the object List into Map. Property: value, which specifies the name of the object property that is the key value of map.
@Options Method The property of the mapping statement This annotation allows you to specify most of the switches and configuration options that typically appear as properties on the mapping statement. O ptions annotations provide a consistent and clear way to specify options compared to providing a large number of properties on annotations. P roperties: useCache=true, FlushCache=FlushCachePolicy.DEFAULT, resultSetType=DEFAULT, statementType=PREPARED, fetchSize=-1, timeout=-1, useGeneratedKeys=false, keyProperty=", k eyColumn=""、resultSets="", databaseId=""。 N ote that Java annotations cannot specify null values. T herefore, once you use Options annotations, your statements are affected by the default values of the properties described above. B e careful to avoid unexpected behavior from default values. T he databaseId(Available since 3.5.5), in case there is a configured DatabaseIdProvider, the MyBatis use the Options with no databaseId attribute or with a databaseId that matches the current o ne. I f found with and without the databaseId the latter will be discarded.

Note: The keyColumn property is only valid in some databases (e.g. Oracle, PostgreSQL, etc.). To learn more about keyColumn and keyProperty optional values, check out the "insert, update, and delete" section.
  • @Insert
  • @Update
  • @Delete
  • @Select
Method
  • <insert>
  • <update>
  • <delete>
  • <select>
Each annotation represents the SQL statement that will be executed. T hey use an array of strings (or a single string) as arguments. I f you pass an array of strings, the string array is connected to a single complete string, with a space added between each string. T his effectively avoids the "missing spaces" problem of building SQL statements with Java code. O f course, you can also manually connect strings in advance. P roperty: value, which specifies the array of strings used to make up a single SQL statement. T he databaseId(Available since 3.5.5), in case there is a configured DatabaseIdProvider, the MyBatis use a statement with no databaseId attribute or with a databaseId that matches the current o ne. If found with and without the databaseId the latter will be discarded.
  • @InsertProvider
  • @UpdateProvider
  • @DeleteProvider
  • @SelectProvider
Method
  • <insert>
  • <update>
  • <delete>
  • <select>
Allows you to build dynamic SQL. T hese alternative SQL annotations allow you to specify classes and methods that return SQL statements for runtime execution. ( Starting with MyBatis 3.4.6, you can use CharSequence instead of String as the return type.) W hen a mapping statement is executed, MyBatis instantiates the class specified by the annotation and calls the method specified by the annotation. Y ou can pass the parameters received through the ProviderContext delivery mapping method, "Mapper interface type" and "Mapper method" (supported only above MyBatis 3.4.5). ( MyBatis 3.4 above supports passing in multiple parameters) properties: type, method. T he type property is used to specify the class name. M ethod is used to specify the method name of the class (starting with version 3.5.1, the method property can be omitted, and MyBatis will use the specific implementation of the ProviderMethodResolver interface resolution method). I f parsing fails, MyBatis will use a demotion implementation called provideSql). T ip The next chapter, SQL Statement Builder, will discuss this topic to help you build dynamic SQL in a clearer, easier-to-read way. T he databaseId(Available since 3.5.5), in case there is a configured DatabaseIdProvider, the MyBatis will use a provider method with no databaseId attribute or with a databaseId that matches the c urrent one. If found with and without the databaseId the latter will be discarded.
@Param Parameters N/A If your mapping method accepts more than one parameter, you can use this annotation to customize the name of each parameter. O therwise, by default, parameters other than RowBounds are named with "param" plus parameter positions. F or example, . If you @Param ("person"), the parameter will be named .
@SelectKey Method <selectKey> The functionality of this annotation is exactly the same as that of the .lt;selectKey.gt; tag. T his annotation can only be @Insert @InsertProvider methods @Update or @UpdateProvider or labels, otherwise it will be ignored. I f the @SelectKey annotation is noted, MyBatis ignores the build primary key or configuration property set by the @Options annotation. P roperty: Statement specifies the SQL statement that will be executed as an array of strings, keyProperty specifies the name of the corresponding property of the object passed in as an argument, the property is updated to a new value, and before can be specified as true or false to indicate whether the SQL statement should be executed before or after the statement is inserted. r esultType specifies the Java type of keyProperty. S tatementType is used to select statement types, select one of STATEMENT, PREPARED, or CALLABLE, which corresponds to Statement, PreparedState, and CallableStatement, respectively. T he default is PREPARED. T he databaseId(Available since 3.5.5), in case there is a configured DatabaseIdProvider, the MyBatis will use a statement with no databaseId attribute or with a databaseId that matches the current one. If found with and without the databaseId the latter will be discarded.
@ResultMap Method N/A This annotation @Select or @SelectProvider specifies the id of the element in the XML map. T his allows the annotation's select to re-use The ResultMap, which is already defined in XML. If there is a @Results or @ConstructorArgs in the @ConstructorArgs annotation, both annotations will be overwritten by this annotation.
@ResultType Method N/A This annotation is required when the result processor is used. B ecause the return type at this time is void, Mybatis needs a way to determine the type of object returned by each row. I f you have a corresponding result map in XML, use the @ResultMap to annotation. I f the result type is specified in the XML's element, no additional annotations are required. O therwise, you need to use this annotation. F or example, if a method labeled @Select wants to use a result processor, its return type must be void and the annotation (or @ResultMap). This annotation takes effect only if the method return type void.
@Flush Method N/A If you use this annotation, the method defined in the Mapper interface will be able to call the SqlSession s flushStates() method. (Mybatis 3.3 or more available)


The mapping states the sample

This example shows how to @SelectKey to read the value of a database sequence before inserting:

@Insert("insert into table3 (id, name) values(#{nameId}, #{name})")
@SelectKey(statement="call next value for TestSequence", keyProperty="nameId", before=true, resultType=int.class)
int insertTable3(Name name);

This example shows how to @SelectKey to read the value of a database recognition column after insertion:

@Insert("insert into table2 (name) values(#{name})")
@SelectKey(statement="call identity()", keyProperty="nameId", before=false, resultType=int.class)
int insertTable2(Name name);