Вы находитесь на странице: 1из 161

MYBATIS 3.3.

0
ACKNOWLEDGMENT
3.3

 MyBatis Project, https://mybatis.github.io/mybatis-3/


MYBATIS

7/3/2019 MYBATIS 2
3.3
AGENDA
1 Introduction

2 Configuration XML

3 Mapper XML Files

4 Dynamic SQL
MYBATIS

5 Java API & Logging

6 Spring Integration

7 MyBatis Generator

7/3/2019 MYBATIS 3
1

3
MODULE 1
Introduction

5
INTRODUCTION
6

7/3/2019 MYBATIS 4
1
WHAT IS MYBATIS?
1
 MyBatis is a first class persistence framework with support for custom SQL,
stored
2
procedures and advanced mappings.
 MyBatis eliminates almost all of the JDBC code and manual setting of
parameters
3 and retrieval of results.
 MyBatis can use simple XML or Annotations for configuration and map
primitives, Map interfaces and Java POJOs (Plain Old Java Objects) to
Introduction

4
database records.
5

7/3/2019 MYBATIS 5
1
INSTALLATION
1
 To use MyBatis you just need to include the mybatis-x.x.x.jar file in the
classpath
2
 If you are using Maven just add the following dependency to your pom.xml:
3
<dependency>
Introduction

4
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
5
<version>x.x.x</version>
</dependency>
6

7/3/2019 MYBATIS 6
1
MYBATIS COMPONENTS
XML Mapper / SQL Query Parameter Object

get
SqlSession Mapper Interface

open
Introduction

SqlSessionFactory Object Result / POJO

build

SqlSessionFactoryBuilder

XML Configuration

database
7/3/2019 MYBATIS 7
1
XML CONFIGURATION
 1The XML Configuration file contains settings for the core of the MyBatis system,
including a DataSource for acquiring database Connection instances, as well as
a TransactionManager for determining how transactions should be scoped and
2
controlled.
 The full
3
details of the XML Configuration file can be found later in this
document, but here is a simple example:
Introduction

7/3/2019 MYBATIS 8
1
BUILDING SQLSESSIONFACTORY FROM XML
<?xml version="1.0" encoding="UTF-8" ?>
1
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
2
<environments default="development">
3 <environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
Introduction

4 <property name="driver" value="${driver}"/>


<property name="url" value="${url}"/>
5 <property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
6
</environment>
</environments>
7 <mappers>
<mapper resource="org/mybatis/example/BlogMapper.xml"/>
</mappers>
</configuration>
7/3/2019 MYBATIS 9
1
SqlSessionFactoryBuilder & SqlSessionFactory
 1Every MyBatis application centers around an instance of SqlSessionFactory.
 A SqlSessionFactory instance can be acquired by using the
SqlSessionFactoryBuilder.
2
 SqlSessionFactoryBuilder can build a SqlSessionFactory instance from an XML
Configuration
3 file, or from a custom prepared instance of the Configuration
class.
Introduction

4
String resource = "org/mybatis/example/mybatis-config.xml";
5
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new
6
SqlSessionFactoryBuilder().build(inputStream);
7

7/3/2019 MYBATIS 10
1
BUILDING SqlSessionFactory WITHOUT XML
 1If you prefer to directly build the configuration from Java, rather than XML, or
create your own configuration builder, MyBatis provides a complete
Configuration classes that provides all of the same configuration options as the
2
XML file.
3
DataSource dataSource = BlogDataSourceFactory.getBlogDataSource();
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Introduction

4
Environment environment = new Environment("development", transactionFactory, dataSource);
5
Configuration configuration = new Configuration(environment);
configuration.addMapper(BlogMapper.class);
6
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
7

7/3/2019 MYBATIS 11
1
SqlSession & SqlSessionFactory
 1To execute SQL command, we will need SqlSession, which can be acquired
using SqlSessionFactory. There are two ways to execute SQL command.
 Using selectOne / selectList method from SqlSession
2
SqlSession session = sqlSessionFactory.openSession();
try { 3
Blog blog = session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);
} finally {
Introduction

4
session.close();
}
5
 Using Mapper Interface
SqlSession session = sqlSessionFactory.openSession();
6
try {
BlogMapper mapper = session.getMapper(BlogMapper.class);
7 Blog blog = mapper.selectBlog(101);
} finally {
session.close();
}
7/3/2019 MYBATIS 12
1
MAPPED SQL STATEMENTS
 Here is an example of an XML based mapped statement that would satisfy the
1
above SqlSession calls.
<?xml
2 version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
3
<mapper namespace="org.mybatis.example.BlogMapper">
<select id="selectBlog" resultType="Blog"> select * from Blog where id = #{id} </select>
Introduction

</mapper>
4

Blog blog = session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);


5

7/3/2019 MYBATIS 13
1
MAPPED SQL STATEMENTS
 The mapped statements don't need to be mapped with XML at all. Instead
1
they can use Java Annotations. For example, the XML above could be
eliminated and replaced with:
2
package org.mybatis.example;
3
public interface BlogMapper {
@Select("SELECT * FROM blog WHERE id = #{id}")
Introduction

4 selectBlog(int id);
Blog
}
5
BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog = mapper.selectBlog(101);
6

7/3/2019 MYBATIS 14
1
SCOPE AND LIFECYCLE
XML Mapper / SQL Query Parameter Object

get
SqlSession Mapper Interface

open
Introduction

SqlSessionFactory Object Result / POJO

build

SqlSessionFactoryBuilder

application scope
XML Configuration
method scope

database
7/3/2019 MYBATIS 15
1

MyBatis Break
Introduction

Module 1: Getting Started

7/3/2019 MYBATIS 16
2

3
MODULE 2
Configuration XML

5
CONFIGURATION XML
6

7/3/2019 MYBATIS 17
2
CONFIGURATION
 The MyBatis configuration contains settings and properties that have a
1
dramatic effect on how MyBatis behaves. The high level structure of the
document is as follows:
2

properties

settings
3
Configuration XML


typeAliases

typeHandlers
4

objectFactory

plugins
5

environments
6
- environment
-- transactionManager
7
-- dataSource
• databaseIdProvider
• mappers

7/3/2019 MYBATIS 18
2
PROPERTIES
 1These are externalizable, substitutable properties that can be configured in a
typical Java Properties file instance, or passed in through sub-elements of the
properties element. For example:
2
<properties resource="org/mybatis/example/config.properties">
<property
3 name="username" value="dev_user"/>
Configuration XML

<property name="password" value="F2Fa3!33TYyg"/>


</properties>
4

7/3/2019 MYBATIS 19
2
PROPERTIES
 The properties can then be used throughout the configuration files to substitute
1values that need to be dynamically configured. For example:

2
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
3
Configuration XML

<property name="url" value="${url}"/>


<property name="username" value="${username}"/>
4
<property name="password" value="${password}"/>
</dataSource>
5
 The username and password in this example will be replaced by the values set
6 properties elements.
in the
7

7/3/2019 MYBATIS 20
2
SETTINGS
 These are extremely important tweaks that modify the way that MyBatis
1behaves at runtime.
 An example of the settings element fully configured is as follows:
2
<settings>
<setting name="cacheEnabled" value="true"/>
3
<setting name="lazyLoadingEnabled" value="true"/>
Configuration XML

<setting name="multipleResultSetsEnabled" value="true"/>


<setting
4 name="useColumnLabel" value="true"/>
<setting name="useGeneratedKeys" value="false"/>
<setting name="autoMappingBehavior" value="PARTIAL"/>
5
<setting name="defaultExecutorType" value="SIMPLE"/>
<setting name="defaultStatementTimeout" value="25"/>
6<setting name="safeRowBoundsEnabled" value="false"/>
<setting name="mapUnderscoreToCamelCase" value="false"/>
<setting name="localCacheScope" value="SESSION"/>
7 <setting name="jdbcTypeForNull" value="OTHER"/>
<setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
</settings>

7/3/2019 MYBATIS 21
2
TYPEALIASES
 1A type alias is simply a shorter name for a Java type. It's only relevant to the
XML configuration and simply exists to reduce redundant typing of fully
qualified classnames. For example:
2
<typeAliases>
<typeAlias
3 alias="Author" type="domain.blog.Author"/>
Configuration XML

<typeAlias alias="Blog" type="domain.blog.Blog"/>


<typeAlias alias="Comment" type="domain.blog.Comment"/>
4
<typeAlias alias="Post" type="domain.blog.Post"/>
<typeAlias alias="Section" type="domain.blog.Section"/>
5
<typeAlias alias="Tag" type="domain.blog.Tag"/>
</typeAliases>
6
<mapper namespace="org.mybatis.example.BlogMapper">
<select id="selectBlog" resultType=“domain.blog.Blog"> select * from Blog where id = #{id}
7
</select> </mapper>

7/3/2019 MYBATIS 22
2
TYPEALIASES
 You can also specify a package where MyBatis will search for beans. For
1
example:
<typeAliases>
2
<package name="domain.blog"/>
</typeAliases>
3
Configuration XML

 Each bean found in domain.blog , if no annotation is found, will be registered


as an4 alias using uncapitalized non-qualified class name of the bean. That is
domain.blog.Author will be registered as author. If the @Alias annotation is
5
found its value will be used as an alias. See the example below:
@Alias("author")
6
public class Author {
7 ...
}

7/3/2019 MYBATIS 23
2
TYPEALIASES
 There are many built-in type aliases for common Java types. They are all case
1
insensitive, note the special handling of primitives due to the overloaded
names. Such us :
2
Alias Mapped Type
3
Configuration XML

_byte byte
_long long
4
_short short
_int 5 int
_integer int
_double
6 double
_float float
7 _boolean boolean

7/3/2019 MYBATIS 24
2
TYPEHANDLERS
 1Whenever MyBatis sets a parameter on a PreparedStatement or retrieves a
value from a ResultSet, a TypeHandler is used to retrieve the value in a means
appropriate
2
to the Java type. Such us :

Type3Handler Java Types JDBC Types


Configuration XML

BooleanTypeHandler java.lang.Boolean, boolean Any compatible BOOLEAN


ByteTypeHandler
4 java.lang.Byte, byte Any compatible NUMERIC or BYTE
ShortTypeHandler java.lang.Short, short Any compatible NUMERIC or SHORT INTEGER
5
IntegerTypeHandler java.lang.Integer, int Any compatible NUMERIC or INTEGER
LongTypeHandler java.lang.Long, long Any compatible NUMERIC or LONG INTEGER
6
FloatTypeHandler java.lang.Float, float Any compatible NUMERIC or FLOAT

7 DoubleTypeHandler java.lang.Double, double Any compatible NUMERIC or DOUBLE


BigDecimalTypeHandler java.math.BigDecimal Any compatible NUMERIC or DECIMAL

7/3/2019 MYBATIS 25
2
TYPEHANDLERS
Type Handler Java Types JDBC Types
1
StringTypeHandler java.lang.String CHAR, VARCHAR
ClobTypeHandler
2 java.lang.String CLOB, LONGVARCHAR
NStringTypeHandler java.lang.String NVARCHAR, NCHAR
3
Configuration XML

NClobTypeHandler java.lang.String NCLOB


ByteArrayTypeHandler
4 byte[] Any compatible byte stream type
BlobTypeHandler byte[] BLOB, LONGVARBINARY
5
DateTypeHandler java.util.Date TIMESTAMP
DateOnlyTypeHandler
6 java.util.Date DATE
TimeOnlyTypeHandler java.util.Date TIME
7 SqlTimestampTypeHandler java.sql.Timestamp TIMESTAMP
SqlDateTypeHandler java.sql.Date DATE

7/3/2019 MYBATIS 26
2
TYPEHANDLERS
Type Handler Java Types JDBC Types
1
SqlTimeTypeHandler java.sql.Time TIME
ObjectTypeHandler
2 Any OTHER, or unspecified
EnumTypeHandler Enumeration Type VARCHAR any string compatible type, as the
3 code is stored (not index).
Configuration XML

EnumOrdinalTypeHandler Enumeration Type Any compatible NUMERIC or DOUBLE, as the


4 position is stored (not the code itself).

7/3/2019 MYBATIS 27
2
TYPEHANDLERS
 You can override the type handlers. For example:
1
// ExampleTypeHandler.java
@MappedJdbcTypes(JdbcType.VARCHAR)
2 class ExampleTypeHandler extends BaseTypeHandler<String> {
public

@Override
3 void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws
Configuration XML

public
SQLException {
4ps.setString(i, parameter);
}
@Override
5 String getNullableResult(ResultSet rs, String columnName) throws SQLException {
public
return rs.getString(columnName);
}
6@Override
public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return rs.getString(columnIndex);
7
}
}

7/3/2019 MYBATIS 28
2
TYPEHANDLERS
 Definition in configuration xml :
1
<!-- mybatis-config.xml -->
<typeHandlers>
2
<typeHandler handler="org.mybatis.example.ExampleTypeHandler"/>
</typeHandlers>
3
Configuration XML

 Or you can let MyBatis search for your ExampleTypeHandlers:


4
<!-- mybatis-config.xml -->
<typeHandlers>
5
<package name="org.mybatis.example"/>
</typeHandlers>
6

7/3/2019 MYBATIS 29
2
TYPEHANDLERS
 1You can create a generic TypeHandler that is able to handle more than one
class.
2
//GenericTypeHandler.java
public class GenericTypeHandler<E extends MyObject> extends BaseTypeHandler<E> {
3
Configuration XML

private Class<E> type;


4
public GenericTypeHandler(Class<E> type) {
5 if (type == null) throw new IllegalArgumentException("Type argument cannot
be null");
6 this.type = type;
}
7
...

7/3/2019 MYBATIS 30
2
HANDLING ENUMS
 1To map enum, you can useEnumTypeHandler or EnumOrdinalTypeHandler.
<!-- mybatis-config.xml -->
<typeHandlers>
2
<typeHandler handler="org.apache.ibatis.type.EnumOrdinalTypeHandler"
3javaType="java.math.RoundingMode"/>
Configuration XML

</typeHandlers>
4

7/3/2019 MYBATIS 31
2
ObjectFactory
 1Each time MyBatis creates a new instance of a result object, it uses an
ObjectFactory instance to do so.
2
// ExampleObjectFactory.java
public class ExampleObjectFactory extends DefaultObjectFactory {
3 Object create(Class type) {
public
Configuration XML

return super.create(type);
}
4
public Object create(Class type, List<Class> constructorArgTypes, List<Object> constructorArgs) {
return super.create(type, constructorArgTypes, constructorArgs);
}5
public void setProperties(Properties properties) {
super.setProperties(properties);
6
}
public <T> boolean isCollection(Class<T> type) {
7 return Collection.class.isAssignableFrom(type);
}
}

7/3/2019 MYBATIS 32
2
ObjectFactory
 1For the mybatis configuration xml :
<!-- mybatis-config.xml -->
2
<objectFactory type="org.mybatis.example.ExampleObjectFactory">
<property name="someProperty" value="100"/>
</objectFactory>
3
Configuration XML

7/3/2019 MYBATIS 33
2
PLUGINS
 MyBatis allows you to intercept calls to at certain points within the execution of
1
a mapped statement. By default, MyBatis allows plug-ins to intercept method
calls of:
2
• Executor (update, query, flushStatements, commit, rollback, getTransaction,
close,
3
isClosed)
Configuration XML

• ParameterHandler (getParameterObject, setParameters)


• ResultSetHandler
4 (handleResultSets, handleOutputParameters)
• StatementHandler (prepare, parameterize, batch, update, query)
5

7/3/2019 MYBATIS 34
2
PLUGINS
 Using plug-ins by implementing the Interceptor interface. Be sure to specify the
1signatures you want to intercept.

// ExamplePlugin.java
2
@Intercepts({@Signature(
type= Executor.class,
3
method = "update",
Configuration XML

args = {MappedStatement.class,Object.class})})

public4class ExamplePlugin implements Interceptor {


public Object intercept(Invocation invocation) throws Throwable {
5return invocation.proceed();
}
public Object plugin(Object target) {
6 return Plugin.wrap(target, this);
}
public void setProperties(Properties properties) {
7 }
}

7/3/2019 MYBATIS 35
2
PLUGINS
 For the mybatis configuration xml :
1
<!-- mybatis-config.xml -->
<plugins>
2 <plugin interceptor="org.mybatis.example.ExamplePlugin">
<property name="someProperty" value="100"/>
3</plugin>
Configuration XML

</plugins>

The plug-in
4 above will intercept all calls to the "update" method on the
Executor instance, which is an internal object responsible for the low level
5
execution of mapped statements.
6

7/3/2019 MYBATIS 36
2
ENVIRONMENTS
 MyBatis can be configured with multiple environments.
 1This helps you to apply your SQL Maps to multiple databases for any number
of reasons.
 For2 example :
• You might have a different configuration for your Development, Test and
3
Production environments.
Configuration XML

• You may have multiple production databases that share the same schema,
4 like to use the same SQL maps for both. There are many use cases.
• you’d
 One important thing to remember though:
While5 you can configure multiple environments, you can only choose ONE per
SqlSessionFactory instance
6

7/3/2019 MYBATIS 37
2
ENVIRONMENTS
 1To specify which environment to build, you simply pass it to the
SqlSessionFactoryBuilder as an optional parameter. The two signatures that
accept the environment are:
2
SqlSessionFactory factory = sqlSessionFactoryBuilder.build(reader, environment);
SqlSessionFactory factory = sqlSessionFactoryBuilder.build(reader, environment,properties);
3
Configuration XML

 If the environment is omitted, then the default environment is loaded, as


4
follows:
SqlSessionFactory
5 factory = sqlSessionFactoryBuilder.build(reader);
SqlSessionFactory factory = sqlSessionFactoryBuilder.build(reader,properties);
6

7/3/2019 MYBATIS 38
2
ENVIRONMENTS
 The environments element defines how the environment is configured.
1
<environments default="development">
2 <environment id="development">
<transactionManager type="JDBC">
3 <property name="..." value="..."/>
Configuration XML

</transactionManager>
<dataSource type="POOLED">
4
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
5 <property name="username" value="${username}"/>
<property name="password" value="${password}"/>
6 </dataSource>
</environment>
7 </environments>

7/3/2019 MYBATIS 39
2
ENVIRONMENTS
 Notice
1
the key sections here:
• The default Environment ID (e.g. default="development").
• The
2 Environment ID for each environment defined (e.g. id="development").
• The TransactionManager configuration (e.g. type="JDBC")
• The3 DataSource configuration (e.g. type="POOLED")
Configuration XML

 The default environment and the environment IDs are self explanatory.
Name4them whatever you like, just make sure the default matches one of them.
5

7/3/2019 MYBATIS 40
2
ENVIRONMENTS – TRANSACTION MANAGER
 1There are two TransactionManager types (i.e. type="[JDBC|MANAGED]") that
are included with MyBatis:
• 2JDBC – This configuration simply makes use of the JDBC commit and
rollback facilities directly.
• MANAGED
3 – This configuration simply does almost nothing. It never commits,
Configuration XML

or rolls back a connection.


4
<transactionManager type="MANAGED">
<property name="closeConnection" value="false"/>
5
</transactionManager>
6

7/3/2019 MYBATIS 41
2
ENVIRONMENTS – DATA SOURCE
 There are three build-in dataSource types (i.e.
1
type="[UNPOOLED|POOLED|JNDI]"):
• 2UNPOOLED – This implementation of DataSource simply opens and closes
a connection each time it is requested.
• POOLED
3 – This implementation of DataSource pools JDBC Connection
Configuration XML

objects to avoid the initial connection and authentication time required to


create
4 a new Connection instance.
• JNDI – This implementation of DataSource is intended for use with
5
containers such as EJB or Application Servers that may configure the
DataSource centrally or externally and place a reference to it in a JNDI
6
context
7

7/3/2019 MYBATIS 42
2
DATABASEIDPROVIDER
 To enable the multi vendor support add a databaseIdProvider to mybatis-
1
config.xml file as follows:
2
<databaseIdProvider type="DB_VENDOR">
<property name="SQL Server" value="sqlserver"/>
<property
3 name="DB2" value="db2"/>
Configuration XML

<property name="Oracle" value="oracle" />


</databaseIdProvider>
4
 You can build your own DatabaseIdProvider by implementing the interface
5
org.apache.ibatis.mapping.DatabaseIdProvider and registering it in mybatis-
config.xml:
6
public interface DatabaseIdProvider {
7 void setProperties(Properties p);
String getDatabaseId(DataSource dataSource) throws SQLException;
}

7/3/2019 MYBATIS 43
2
MAPPERS
 1Now that the behavior of MyBatis is configured with the above configuration
elements, we’re ready to define our mapped SQL statements.
2 Using classpath relative resources -->
<!--
<mappers>
3<mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
Configuration XML

<mapper resource="org/mybatis/builder/BlogMapper.xml"/>
<mapper
4 resource="org/mybatis/builder/PostMapper.xml"/>
</mappers>
5
<!-- Using url fully qualified paths -->
<mappers>
6
<mapper url="file:///var/mappers/AuthorMapper.xml"/>
<mapper url="file:///var/mappers/BlogMapper.xml"/>
7
<mapper url="file:///var/mappers/PostMapper.xml"/>
</mappers>

7/3/2019 MYBATIS 44
2
MAPPERS
1 <!-- Using mapper interface classes -->
<mappers>
<mapper class="org.mybatis.builder.AuthorMapper"/>
2
<mapper class="org.mybatis.builder.BlogMapper"/>
<mapper class="org.mybatis.builder.PostMapper"/>
3
Configuration XML

</mappers>

<!-- 4Register all interfaces in a package as mappers -->


<mappers>
5
<package name="org.mybatis.builder"/>
</mappers>
6

7/3/2019 MYBATIS 45
2
Configuration XML

MyBatis Break
Module 2: Using Configuration Files

7/3/2019 MYBATIS 46
3

3
MODULE 3
Mapper XML Files

5
MAPPER XML FILES
6

7/3/2019 MYBATIS 47
3
MAPPER XML FILES
 The Mapper XML files have only a few first class elements (in the order that
1
they should be defined):
• cache – Configuration of the cache for a given namespace.
• 2 cache-ref – Reference to a cache configuration from another namespace.
• resultMap – The most complicated and powerful element that describes
3
how to load your objects from the database result sets.
Mapper XML Files

• sql – A reusable chunk of SQL that can be referenced by other


4
statements.
• insert – A mapped INSERT statement.
5
• update – A mapped UPDATE statement.
• delete – A mapped DELETE statement.
6
• select – A mapped SELECT statement.
7

7/3/2019 MYBATIS 48
3
SELECT
 The select element is quite simple for simple cases. For example:
1
<select id="selectPerson" parameterType="int" resultType="hashmap">
2 SELECT * FROM PERSON WHERE ID = #{id}
</select>
3
 Notice the parameter notation:
Mapper XML Files

#{id}
4

 In SQL passed to a new PreparedStatement, something like this:


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

7/3/2019 MYBATIS 49
3
SELECT ATTRIBUTE
 The select element has more attributes that allow you to configure the details
1
of how each statement should behave.
<select
2
id="selectPerson"
3parameterType="int"
Mapper XML Files

resultType="hashmap"
resultMap="personResultMap"
4
flushCache="false"
useCache="true"
5timeout="10000"
fetchSize="256"
statementType="PREPARED"
6
resultSetType="FORWARD_ONLY">

7/3/2019 MYBATIS 50
3
SELECT ATTRIBUTE
Attribute Description
1
id A unique identifier in this namespace that can be used to reference this statement.
2 The fully qualified class name or alias for the parameter that will be passed into this
parameterType statement. This attribute is optional because MyBatis can calculate the TypeHandler
to use out of the actual parameter passed to the statement. Default is unset.
3
Mapper XML Files

The fully qualified class name or alias for the expected type that will be returned
from this statement. Note that in the case of collections, this should be the type that
resultType
4 the collection contains, not the type of the collection itself. Use resultType OR
resultMap, not both.
5 A named reference to an external resultMap. Result maps are the most powerful
resultMap feature of MyBatis, and with a good understanding of them, many difficult mapping
6 cases can be solved. Use resultMap OR resultType, not both.

7/3/2019 MYBATIS 51
3
SELECT ATTRIBUTE (2)
Attribute
1 Description
Setting this to true will cause the local and 2nd level caches to be flushed whenever
flushCache
this statement is called. Default: false for select statements.
2
Setting this to true will cause the results of this statement to be cached in 2nd level
useCache
cache. Default: true for select statements.
3
Mapper XML Files

This sets the number of seconds the driver will wait for the database to return from a
timeout
request, before throwing an exception. Default is unset (driver dependent).
4
This is a driver hint that will attempt to cause the driver to return results in batches of
fetchSize
rows numbering in size equal to this setting. Default is unset (driver dependent).
5
Any one of STATEMENT, PREPARED or CALLABLE. This causes MyBatis to use
statementType Statement, PreparedStatement or CallableStatement respectively. Default:
6 PREPARED.
Any one of FORWARD_ONLY|SCROLL_SENSITIVE|SCROLL_INSENSITIVE. Default is
resultSetType
7 unset (driver dependent).

7/3/2019 MYBATIS 52
3
SELECT ATTRIBUTE (3)
Attribute Description
1
In case there is a configured databaseIdProvider, MyBatis will load all statements
with no databaseId attribute or with a databaseId that matches the current one. If
databaseId
2 case the same statement if found with and without the databaseId the latter will be
discarded.
3 This is only applicable for nested result select statements: If this is true, it is assumed
Mapper XML Files

that nested results are contained or grouped together such that when a new main
resultOrdered
4 result row is returned, no references to a previous result row will occur anymore. This
allows nested results to be filled much more memory friendly. Default: false.
5 This is only applicable for multiple result sets. It lists the result sets that will be
resultSets returned by the statement and gives a name to each one. Names are separated by
commas.
6

7/3/2019 MYBATIS 53
3
INSERT, UPDATE AND DELETE
 The data modification statements insert, update and delete are very similar in
1
their implementation:
<insert id="insertAuthor"
2 parameterType="domain.blog.Author"
flushCache="true"
statementType="PREPARED"
3
Mapper XML Files

keyProperty=""
keyColumn=""
4
useGeneratedKeys=""
timeout="20">
<update id="updateAuthor“
5parameterType="domain.blog.Author"
flushCache="true"
6 statementType="PREPARED"
timeout="20">
<delete id="deleteAuthor"
7 parameterType="domain.blog.Author"
flushCache="true"
statementType="PREPARED"
timeout="20">

7/3/2019 MYBATIS 54
3
INSERT, UPDATE AND DELETE ATTRIBUTE
Attribute Description
1
id A unique identifier in this namespace that can be used to reference this statement.
2 The fully qualified class name or alias for the parameter that will be passed into this
parameterType statement. This attribute is optional because MyBatis can calculate the TypeHandler
to use out of the actual parameter passed to the statement. Default is unset.
3
Mapper XML Files

Setting this to true will cause the 2nd level and local caches to be flushed whenever
flushCache
this statement is called. Default: true for insert, update and delete statements.
4
This sets the maximum number of seconds the driver will wait for the database to
timeout return from a request, before throwing an exception. Default is unset (driver
5 dependent).
Any one of STATEMENT, PREPARED or CALLABLE. This causes MyBatis to use
6
statementType Statement, PreparedStatement or CallableStatement respectively. Default:
PREPARED.
7

7/3/2019 MYBATIS 55
3
INSERT, UPDATE AND DELETE ATTRIBUTE (2)
Attribute Description
1
(insert and update only) Identifies a property into which MyBatis will set the key
value returned by getGeneratedKeys, or by a selectKey child element of the insert
keyProperty
2 statement. Default: unset. Can be a comma separated list of property names if
multiple generated columns are expected.
3 (insert and update only) Sets the name of the column in the table with a generated
Mapper XML Files

key. This is only required in certain databases (like PostgreSQL) when the key column
keyColumn
4 is not the first column in the table. Can be a comma separated list of columns names
if multiple generated columns are expected.
5 In case there is a configured databaseIdProvider, MyBatis will load all statements
with no databaseId attribute or with a databaseId that matches the current one. If
databaseId
case the same statement if found with and without the databaseId the latter will be
6
discarded.

7/3/2019 MYBATIS 56
3
INSERT, UPDATE AND DELETE
 The following are some examples of insert, update and delete statements.
1
<insert id="insertAuthor">
2 insert into Author (id,username,password,email,bio) values
(#{id},#{username},#{password},#{email},#{bio})
</insert>
3
Mapper XML Files

<update id="updateAuthor">
4
update Author set username = #{username}, password = #{password}, email =
#{email}, bio = #{bio} where id = #{id}
</update>
5

<delete id="deleteAuthor">
6 delete from Author where id = #{id}
</delete>
7

7/3/2019 MYBATIS 57
3
SELECTKEY
 For example, if the Author table above had used an auto-generated column
1
type for the id, the statement would be modified as follows:
<insert
2 id="insertAuthor" useGeneratedKeys="true" keyProperty="id">
insert into Author (username,password,email,bio) values
(#{username},#{password},#{email},#{bio})
3
</insert>
Mapper XML Files

 What if database vendor does not support auto-generated column? Here's a


4
simple (silly) example that would generate a random ID
<insert
5 id="insertAuthor">
<selectKey keyProperty="id" resultType="int" order="BEFORE">
select CAST(RANDOM()*1000000 as INTEGER) a from SYSIBM.SYSDUMMY1
6 </selectKey>
insert into Author (id, username, password, email,bio, favourite_section)
7 values (#{id}, #{username}, #{password}, #{email}, #{bio},
#{favouriteSection,jdbcType=VARCHAR})
</insert>

7/3/2019 MYBATIS 58
3
SELECTKEY ATTRIBUTE
Attribute Description
1
The target property where the result of the selectKey statement should be set. Can
keyProperty be a comma separated list of property names if multiple generated columns are
2 expected.
The column name(s) in the returned result set that match the properties. Can be a
keyColumn
3
Mapper XML Files

comma separated list of column names if multiple generated columns are expected.
The type of the result. MyBatis can usually figure this out, but it doesn't hurt to add it
4 to be sure. MyBatis allows any simple type to be used as the key, including Strings. If
resultType
you are expecting multiple generated columns, then you can use an Object that
5 contains the expected properties, or a Map.
This can be set to BEFORE or AFTER. If set to BEFORE, then it will select the key first,
set the keyProperty and then execute the insert statement. If set to AFTER, it runs the
order 6
insert statement and then the selectKey statement – which is common with databases
like Oracle that may have embedded sequence calls inside of insert statements.
7
Same as above, MyBatis supports STATEMENT, PREPARED and CALLABLE statement
statementType types that map to Statement, PreparedStatement and CallableStatement
respectively.
7/3/2019 MYBATIS 59
3
SQL
 This element can be used to define a reusable fragment of SQL code that can
1
be included in other statements. For example:
<sql
2 id="userColumns"> id, username, password </sql>

3
 The SQL fragment can then be included in another statement, for example:
Mapper XML Files

4 id="selectUsers" resultType="map">
<select
select
5 <include refid="userColumns“/>
from some_table
</select>
6

7/3/2019 MYBATIS 60
3
PARAMETERS
 Parameters are very powerful elements in MyBatis, for example:
1
<select id="selectUsers" resultType="User">
2 select id, username, password from users where id = #{id}
</select>
3
 However, if you pass in a complex object, then the behavior is a little
Mapper XML Files

different. For example:


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

7/3/2019 MYBATIS 61
3
PARAMETERS DATA TYPE
 First, like other parts of MyBatis, parameters can specify a more specific data
1
type.
#{property,javaType=int,jdbcType=NUMERIC}
2

 To further customize type handling, you can also specify a specific


3
TypeHandler class (or alias), for example:
Mapper XML Files

#{age,javaType=int,jdbcType=NUMERIC,typeHandler=MyTypeHandler}
4

 For numeric types there's also a numericScale for determining how many
5
decimal places are relevant.
#{height,javaType=double,jdbcType=NUMERIC,numericScale=2}
6

 Mostly, we only use property name, and jdbcType for nullable columns
7

7/3/2019 MYBATIS 62
3
RESULT MAPS
 The resultMap element allows you to do away with 90% of the code that
1
JDBC requires to retrieve data from ResultSets.
 By default, ResultSet is presented in map, but this is not a good model. More
2
likely your application will need JavaBeans or POJOs (Plain Old Java
Objects) for the domain model.
3
Mapper XML Files

7/3/2019 MYBATIS 63
3
RESULT MAPS
public class User {
1 private int id;
private String username;
2private String hashedPassword;

public
3 int getId() {
Mapper XML Files

return id;
}
4 void setId(int id) {
public
this.id = id;
} 5
....
}
6
<select id="selectUsers" resultType="com.someapp.model.User">
7 select id, username, hashedPassword
from some_table
where id = #{id}
</select>
7/3/2019 MYBATIS 64
3
RESULT MAPS
 below example demonstrate an external resultMap, as another way to solve
1
column name mismatches.
2
<resultMap id="userResultMap" type="User">
<id property="id" column="user_id" />
3<result property="username" column="user_name"/>
Mapper XML Files

<result property="password" column="hashed_password"/>


</resultMap>
4

 And the statement that references it uses the resultMap attribute to do so


5
(notice we removed the resultType attribute). For example:
<select
6 id="selectUsers" resultMap="userResultMap">
select user_id, user_name, hashed_password from some_table
where id = #{id}
7
</select>

7/3/2019 MYBATIS 65
3
ADVANCED RESULT MAPS
<!--
1 Very Complex Statement -->
<select id="selectBlogDetails" resultMap="detailedBlogResultMap">
select
2 as blog_id,
B.id
B.title as blog_title,
B.author_id
3 as blog_author_id,
Mapper XML Files

A.id as author_id,
A.username as author_username,
4
A.password as author_password,
A.email as author_email,
5 as author_bio,
A.bio
A.favourite_section as author_favourite_section,
P.id
6 as post_id,
P.blog_id as post_blog_id,
P.author_id as post_author_id,
7 P.created_on as post_created_on,
P.section as post_section,

7/3/2019 MYBATIS 66
3
ADVANCED RESULT MAPS (2)
1 …
P.section as post_section,
P.subject as post_subject,
2
P.draft as draft,
P.body as post_body,
C.id
3 as comment_id,
Mapper XML Files

C.post_id as comment_post_id,
C.name as comment_name,
4
C.comment as comment_text,
T.id as tag_id,
5
T.name as tag_name
from Blog B
left
6 outer join Author A on B.author_id = A.id
left outer join Post P on B.id = P.blog_id
left outer join Comment C on P.id = C.post_id
7 left outer join Post_Tag PT on PT.post_id = P.id
left outer join Tag T on PT.tag_id = T.id
where B.id = #{id}
</select>
7/3/2019 MYBATIS 67
3
ADVANCED RESULT MAPS
While it may look daunting at first, it's actually very simple.
1
<!-- Very Complex Result Map -->
2
<resultMap id="detailedBlogResultMap" type="Blog">
<constructor>
<idArg
3 column="blog_id" javaType="int"/>
Mapper XML Files

</constructor>
<result property="title" column="blog_title"/>
4
<association property="author" javaType="Author">
<id property="id" column="author_id"/>
<result
5 property="username" column="author_username"/>
<result property="password" column="author_password"/>
<result property="email" column="author_email"/>
6
<result property="bio" column="author_bio"/>
<result property="favouriteSection" column="author_favourite_section"/>
7 </association>

7/3/2019 MYBATIS 68
3
ADVANCED RESULT MAPS
1…
<collection property="posts" ofType="Post">
<id property="id" column="post_id"/>
2<result property="subject" column="post_subject"/>
<association property="author" javaType="Author"/>
3
<collection property="comments" ofType="Comment">
Mapper XML Files

<id property="id" column="comment_id"/>


</collection>
4
<collection property="tags" ofType="Tag" >
<id property="id" column="tag_id"/>
5
</collection>
<discriminator javaType="int" column="draft">
6 <case value="1" resultType="DraftPost"/>
</discriminator>
</collection>
7
</resultMap>

7/3/2019 MYBATIS 69
3
RESULT MAPS ATTRIBUTE
Attribute Description
1
id A unique identifier in this namespace that can be used to reference this result map.
A fully qualified Java class name, or a type alias (see the table above for the list of
type 2
built-in type aliases).
3 If present, MyBatis will enable or disable the automapping for this ResultMap. This
autoMapping
Mapper XML Files

attribute overrides the global autoMappingBehavior. Default: unset.

7/3/2019 MYBATIS 70
3
RESULT MAPS ELEMENTS
 constructor - used for injecting results into the constructor of a class upon instantiation
1
 idArg - ID argument; flagging results as ID will help improve overall
performance
 2 arg - a normal result injected into the constructor
 id – an ID result; flagging results as ID will help improve overall performance
 result
3 – a normal result injected into a field or JavaBean property
Mapper XML Files

 association – a complex type association; many results will roll up into this type
 4nested result mappings – associations are resultMaps themselves, or can refer to
one
 collection
5 – a collection of complex types
 nested result mappings – collections are resultMaps themselves, or can refer to
one
6
 discriminator – uses a result value to determine which resultMap to use
 case – a case is a result map based on some value
7  nested result mappings – a case is also a result map itself, and thus can
contain many of these same elements, or it can refer to an external
resultMap.
7/3/2019 MYBATIS 71
3
RESULT MAPS - ID AND RESULT ATTRIBUTE
Attribute Description
1
The field or property to map the column result to. If a matching JavaBeans property
exists for the given name, then that will be used. Otherwise, MyBatis will look for a
property
2 field of the given name. In both cases you can use complex property navigation
using the usual dot notation.
3
Mapper XML Files

The column name from the database, or the aliased column label. This is the same
column
string that would normally be passed to resultSet.getString(columnName).
4 A fully qualified Java class name, or a type alias (see the table above for the list of
javaType built-in type aliases). MyBatis can usually figure out the type if you're mapping to a
5 JavaBean.
The JDBC Type from the list of supported types that follows this table. The JDBC
jdbcType
6 type is only required for nullable columns upon insert, update or delete. This is a
JDBC requirement, not a MyBatis one.
7 We discussed default type handlers previously in this documentation. Using this
property you can override the default type handler on a mapping-by-mapping
typeHandler
basis. The value is either a fully qualified class name of a TypeHandler
implementation, or a type alias.
7/3/2019 MYBATIS 72
3
RESULT MAPS - SUPPORTED JDBC TYPE
For future reference, MyBatis supports the following JDBC Types via the included
1
JdbcType enumeration.
BIT 2 FLOAT CHAR TIMESTAMP OTHER UNDEFINED
TINYINT REAL VARCHAR BINARY BLOG NVARCHAR
3
Mapper XML Files

LONGVARC
SMALLINT DOUBLE VARBINARY CLOB NCHAR
HAR
4
LONGVARBI
INTEGER NUMERIC DATE BOOLEAN NCLOB
NARY
5
BIGINT DECIMAL TIME NULL CURSOR ARRAY

7/3/2019 MYBATIS 73
3
RESULT MAPS - CONSTRUCTOR
 In order to inject the results into the constructor, MyBatis needs to identify the
1
constructor by the type of its parameters. For example :
2
<constructor>
<idArg column="id" javaType="int"/>
3<arg column="username" javaType="String"/>
Mapper XML Files

</constructor>
4

 The rest of the attributes and rules are the same as for the regular id and
5
result elements.
6

7/3/2019 MYBATIS 74
3
RESULT MAPS - ASSOCIATION
 The association element deals with a "has-one" type relationship. For
1
example:
<association
2 property="author" javaType="Author">
<id property="id" column="author_id"/>
<result property="username" column="author_username"/>
3
Mapper XML Files

</association>

 Where4 the association differs is that you need to tell MyBatis how to load the
association. MyBatis can do so in two different ways:
• Nested
5 Select: By executing another mapped SQL statement that returns
the complex type desired.
• 6 Nested Results: By using nested result mappings to deal with repeating
subsets of joined results.
7

7/3/2019 MYBATIS 75
3
RESULT MAPS – ASSOCIATION ATTRIBUTE
Attribute
1 Description
The field or property to map the column result to. If a matching JavaBeans property
property exists for the given name, then that will be used. Otherwise, MyBatis will look for a
2
field of the given name.
A fully qualified Java class name, or a type alias (see the table above for the list of
3
Mapper XML Files

javaType built- in type aliases). MyBatis can usually figure out the type if you're mapping to a
JavaBean.
4 The JDBC Type from the list of supported types that follows this table. The JDBC
jdbcType
type is only required for nullable columns upon insert, update or delete.
5 We discussed default type handlers previously in this documentation. Using this
typeHandler property you can override the default type handler on a mapping-by-mapping
6 basis.

7/3/2019 MYBATIS 76
3
RESULT MAPS – NESTED SELECT ASSOCIATION
 For example :
1
<resultMap id="blogResult" type="Blog">
2 <association property="author" column="author_id" javaType="Author"
select="selectAuthor"/>
</resultMap>
3
Mapper XML Files

<select id="selectBlog" resultMap="blogResult">


4
SELECT * FROM BLOG WHERE ID = #{id}
</select>
5
<select id="selectAuthor" resultType="Author">
SELECT * FROM AUTHOR WHERE ID = #{id}
6
</select>

7/3/2019 MYBATIS 77
RESULT MAPS – NESTED SELECT ASSOCIATION ATTRIBUTE
3

Attribute
1 Description
The column name from the database, or the aliased column
2 label that holds the value that will be passed to the nested
column
statement as an input parameter. This is the same string that
3
Mapper XML Files

would normally be passed to resultSet.getString(columnName).


4 The ID of another mapped statement that will load the complex
type required by this property mapping. The values retrieved
select 5 from columns specified in the column attribute will be passed to
the target select statement as parameters. A detailed example
6
follows this table.
7 Optional. Valid values are lazy and eager. If present, it
fetchType supersedes the global configuration parameter
lazyLoadingEnabled for this mapping.
7/3/2019 MYBATIS 78
3
RESULT MAPS – NESTED RESULTS ASSOCIATION
 For example :
1
<select id="selectBlog" resultMap="blogResult">
2 select
B.id as blog_id,
B.title as blog_title,
3
Mapper XML Files

B.author_id as blog_author_id,
A.id as author_id,
4 A.username as author_username,
A.password as author_password,
5 A.email as author_email,
A.bio as author_bio
from Blog B
6 left outer join Author A on B.author_id = A.id
where B.id = #{id}
7 </select>

7/3/2019 MYBATIS 79
3
RESULT MAPS – NESTED RESULTS ASSOCIATION
 Now we can map the results:
1

<resultMap id="blogResult" type="Blog">


2
<id property="id" column="blog_id" />
<result property="title" column="blog_title"/>
3<association property="author" resultMap="authorResult" />
Mapper XML Files

</resultMap>
4
<resultMap id="authorResult" type="Author">
<id property="id" column="author_id"/>
5<result property="username" column="author_username"/>
<result property="password" column="author_password"/>
6 <result property="email" column="author_email"/>
<result property="bio" column="author_bio"/>
</resultMap>
7

7/3/2019 MYBATIS 80
RESULT MAPS – NESTED RESULT ASSOCIATION ATTRIBUTE
3

Attribute Description
1
This is the ID of a ResultMap that can map the nested results of this association into
resultMap an appropriate object graph. This is an alternative to using a call to another select
2 statement. It allows you to join multiple tables together into a single ResultSet.
When joining multiple tables, you would have to use column alias to avoid
3
Mapper XML Files

columnPrefix duplicated column names in the ResultSet. Specifying columnPrefix allows you to map
such columns to an external resultMap.
4 By default a child object is created only if at least one of the columns mapped to
the child's properties is non null. With this attribute you can change this behaviour by
notNullColumn
5 specifiying which columns must have a value so MyBatis will create a child object
only if any of those columns is not null.
6 If present, MyBatis will enable or disable automapping when mapping the result to
autoMapping
this property. This attribute overrides the global autoMappingBehavior.
7 We discussed default type handlers previously in this documentation. Using this
typeHandler property you can override the default type handler on a mapping-by-mapping
basis.

7/3/2019 MYBATIS 81
RESULT MAPS – MULTIPLE RESULTSETS ASSOCIATION
3

 In the example, the stored procedure executes the following queries and
1
returns two result sets. The first will contain Blogs and the second Authors.
SELECT * FROM BLOG WHERE ID = #{id}
2
SELECT * FROM AUTHOR WHERE ID = #{id}

3
 A name must be given to each result set by adding a resultSets attribute to
Mapper XML Files

the mapped statement with a list of names separated by commas.


4
<select id="selectBlog" resultSets="blogs,authors" resultMap="blogResult"
statementType="CALLABLE">
5
{call getBlogsAndAuthors(#{id,jdbcType=INTEGER,mode=IN})}
</select>
6

7/3/2019 MYBATIS 82
RESULT MAPS – MULTIPLE RESULTSETS ASSOCIATION
3

 Now we can specify that the data to fill the "author" association comes in the
1
"authors" result set:
2
<resultMap id="blogResult" type="Blog">
3<id property="id" column="id" />
Mapper XML Files

<result property="title" column="title"/>


<association property="author" javaType="Author" resultSet="authors"
4
column="author_id" foreignColumn="id">
<id property="id" column="id"/>
5 <result property="username" column="username"/> <result
property="password" column="password"/>
<result property="email" column="email"/>
6
<result property="bio" column="bio"/>
</association>
7 </resultMap>

7/3/2019 MYBATIS 83
RESULT MAPS – MULTIPLE RESULTSETS ASSOCIATION ATTRIBUTE
3

1
Attribute Description
2 When using multiple resultset this attribute specifies the columns (separated by
column commas) that will be correlated with the foreignColumn to identify the parent and
3 the child of a relationship.
Mapper XML Files

Identifies the name of the columns that contains the foreing keys which values will be
foreignColumn matched against the values of the columns specified in the column attibute of the
4
parent type.
resultSet Identifies the name of the result set where this complex type will be loaded from.
5

7/3/2019 MYBATIS 84
3
RESULT MAPS - COLLECTION
 The collection element deals with a "have-many" type relationship. For
1
example:
<collection
2 property="posts" ofType="domain.blog.Post">
<id property="id" column="post_id"/>
<result property="subject" column="post_subject"/>
3
Mapper XML Files

<result property="body" column="post_body"/>


</collection>
4
 To map a set of nested results to a List like this, we use the collection element.
Just5 like the association element, we can use a nested select, or nested results
from a join.
6

7/3/2019 MYBATIS 85
3
RESULT MAPS – NESTED SELECT COLLECTION
 For example :
1

<resultMap id="blogResult" type="Blog">


2 <collection property="posts" javaType="ArrayList" column="id"
ofType="Post" select="selectPostsForBlog"/>
3
</resultMap>
Mapper XML Files

<select id="selectBlog" resultMap="blogResult">


4
SELECT * FROM BLOG WHERE ID = #{id}
</select>
5
<select id="selectPostsForBlog" resultType="Post">
6 SELECT * FROM POST WHERE BLOG_ID = #{id}
</select>
7

7/3/2019 MYBATIS 86
3
RESULT MAPS – NESTED RESULTS COLLECTION
 For example :
1
<select id="selectBlog" resultMap="blogResult">
2 select
B.id as blog_id,
B.title as blog_title,
3
Mapper XML Files

B.author_id as blog_author_id,
P.id as post_id,
4 P.subject as post_subject,
P.body as post_body,
5from Blog B
left outer join Post P on B.id = P.blog_id
where B.id = #{id}
6
</select>

7/3/2019 MYBATIS 87
3
RESULT MAPS – NESTED RESULTS COLLECTION
 Now we can map the results:
1

<resultMap
2 id="blogResult" type="Blog">
<id property="id" column="blog_id" />
<result property="title" column="blog_title"/>
3
Mapper XML Files

<collection property="posts" ofType="Post">


<id property="id" column="post_id"/>
4 <result property="subject" column="post_subject"/>
<result property="body" column="post_body"/>
5</collection>
</resultMap>

7/3/2019 MYBATIS 88
3
RESULT MAPS – MULTIPLE RESULTSETS COLLECTION
 In the example, we can call an stored procedure that executes two queries
1
and returns two result sets, one with Blogs and another with Posts:
SELECT * FROM BLOG WHERE ID = #{id}
2
SELECT * FROM POST WHERE BLOG_ID = #{id}

3
 A name must be given to each result set by adding a resultSets attribute to
Mapper XML Files

the mapped statement with a list of names separated by commas.


4
<select id="selectBlog" resultSets="blogs,posts" resultMap="blogResult">
5 {call getBlogsAndPosts(#{id,jdbcType=INTEGER,mode=IN})}
</select>
6

7/3/2019 MYBATIS 89
3
RESULT MAPS – DISCRIMINATOR
 Sometimes a single database query might return result sets of many different
1 (but hopefully somewhat related) data types.
 The discriminator element was designed to deal with this situation, and others,
including
2 class inheritance hierarchies. For example:
<resultMap id="vehicleResult" type="Vehicle">
3
<id property="id" column="id" />
Mapper XML Files

<result property="vin" column="vin"/>


<result
4 property="year" column="year"/>
<result property="make" column="make"/>
<result property="model" column="model"/>
5<result property="color" column="color"/>
<discriminator javaType="int" column="vehicle_type">
6 <case value="1" resultMap="carResult"/>
<case value="2" resultMap="truckResult"/>
7 <case value="3" resultMap="vanResult"/>
<case value="4" resultMap="suvResult"/>
</discriminator>
</resultMap>
7/3/2019 MYBATIS 90
3
RESULT MAPS – DISCRIMINATOR
<resultMap id="vehicleResult" type="Vehicle">
1 <id property="id" column="id" />
<result property="vin" column="vin"/>
<result property="year" column="year"/>
2<result property="make" column="make"/>
<result property="model" column="model"/>
<result property="color" column="color"/>
3
<discriminator javaType="int" column="vehicle_type">
Mapper XML Files

<case value="1" resultType="carResult">


<result property="doorCount" column="door_count" />
4
</case>
<case value="2" resultType="truckResult">
<result property="boxSize" column="box_size" />
5
<result property="extendedCab" column="extended_cab" />
</case>
<case value="3" resultType="vanResult">
6 <result property="powerSlidingDoor" column="power_sliding_door" />
</case>
<case value="4" resultType="suvResult">
7 <result property="allWheelDrive" column="all_wheel_drive" />
</case>
</discriminator>
</resultMap>

7/3/2019 MYBATIS 91
3
RESULT MAPS – AUTO-MAPPING
 Auto-mapping works even when there is an specific result map.
1
 All columns that are present in the ResultSet that have not a manual
mapping will be auto-mapped, then manual mappings will be processed.
2
For example:
<select
3 id="selectUsers" resultMap="userResultMap">
Mapper XML Files

select
user_id as "id",
4 user_name as "userName",
hashed_password
5from some_table
where id = #{id}
</select>
6
<resultMap id="userResultMap" type="User">
7 <result property="password" column="hashed_password"/>
</resultMap>

7/3/2019 MYBATIS 92
3
RESULT MAPS – CACHE
 MyBatis includes a powerful transactional query caching feature which is
very configurable and customizable.
 To enable a global second level of caching you simply need to add one
line to your SQL Mapping file:
<cache/>
Mapper XML Files

 Literally that's it. The effect of this one simple statement is as follows:
• All results from select statements in the mapped statement file will be cached.
• All insert, update and delete statements in the mapped statement file will flush the
cache.
• The cache will use a Least Recently Used (LRU) algorithm for eviction.
• The cache will not flush on any sort of time based schedule (i.e. no Flush Interval).
• The cache will store 1024 references to lists or objects (whatever the query method
returns).
• The cache will be treated as a read/write cache, meaning objects retrieved are not
shared and can be safely modified by the caller, without interfering with other
potential modifications by other callers or threads.

7/3/2019 MYBATIS 93
3
RESULT MAPS – CACHE
 All of these properties are modifiable through the attributes of the cache
element. For example:
<cache eviction="FIFO"
flushInterval="60000"
size="512"
Mapper XML Files

readOnly="true"/>

 The available eviction policies available are:


• LRU – Least Recently Used: Removes objects that haven't been used for the longst
period of time.
• FIFO – First In First Out: Removes objects in the order that they entered the cache.
• SOFT – Soft Reference: Removes objects based on the garbage collector state and the
rules of Soft References.
• WEAK – Weak Reference: More aggressively removes objects based on the garbage
collector state and rules of Weak References.

7/3/2019 MYBATIS 94
3
RESULT MAPS – CUSTOM CACHE
 You can also completely override the cache behavior by implementing your
own cache, or creating an adapter to other 3rd party caching solutions.
<cache type="com.domain.something.MyCustomCache"/>

public interface Cache {


Mapper XML Files

String getId();
int getSize();
void putObject(Object key, Object value);
Object getObject(Object key);
boolean hasKey(Object key);
Object removeObject(Object key);
void clear();
}

<cache type="com.domain.something.MyCustomCache">
<property name="cacheFile" value="/tmp/my-custom-cache.tmp"/>
</cache>

7/3/2019 MYBATIS 95
3
Mapper XML Files

MyBatis Break
Module 3: Mapper XML Files

7/3/2019 MYBATIS 96
3

MODULE 4
Dynamic SQL

DYNAMIC SQL

7/3/2019 MYBATIS 97
DYNAMIC SQL
4

 Convenient way to conditionally concatenate strings of SQL together, making


sure not to forget spaces or to omit a comma at the end of a list of columns.

Features
 if
 choose (when, otherwise)
Dynamic SQL

 trim (where, set)


 foreach
 bind
 Multi DB Vendor Support

7/3/2019 MYBATIS 98
IF
4

 conditionally include a part of a where clause

<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
<if test="title != null">
Dynamic SQL

AND title like #{title}


</if>
<if test="author != null and author.name != null">
AND author_name like #{author.name}
</if>
</select>

7/3/2019 MYBATIS 99
CHOOSE, WHEN, OTHERWISE
4

 choose only one case among many options


<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
<choose>
<when test="title != null">
Dynamic SQL

AND title like #{title}


</when>
<when test="author != null and author.name != null">
AND author_name like #{author.name}
</when>
<otherwise>
AND featured = 1
</otherwise>
</choose>
</select>
7/3/2019 MYBATIS 100
WHERE
4

 only insert "WHERE" if there is any content returned by the containing tags,
and if that content begins with "AND" or "OR", strip it off.
<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG
<where>
<if test="state != null">
Dynamic SQL

state = #{state}
</if>
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null and author.name != null">
AND author_name like #{author.name}
</if>
</where>
</select>
7/3/2019 MYBATIS 101
SET
4

 used to dynamically include columns to update, and leave out others

<update id="updateAuthorIfNecessary">
update Author
<set>
<if test="username != null">username=#{username},</if>
<if test="password != null">password=#{password},</if>
Dynamic SQL

<if test="email != null">email=#{email},</if>


<if test="bio != null">bio=#{bio}</if>
</set>
where id=#{id}
</update>

7/3/2019 MYBATIS 102


TRIM
4

 adding more flexibility, below trim is equivalent to where element


<trim prefix="WHERE" prefixOverrides="AND |OR ">
...
</trim>

 below trim is equivalent to set element


Dynamic SQL

<trim prefix="SET" suffixOverrides=",">


...
</trim>

7/3/2019 MYBATIS 103


FOREACH
4

 iterate over a collection, often to build an IN condition

<select id="selectPostIn" resultType="domain.blog.Post">


SELECT *
FROM POST P
WHERE ID in
Dynamic SQL

<foreach item="item" index="index" collection="list"


open="(" separator="," close=")">
#{item}
</foreach>
</select>

7/3/2019 MYBATIS 104


BIND
4

 create a variable out of an OGNL expression and bind it to the context.

<select id="selectBlogsLike" resultType="Blog">


<bind name="pattern" value="'%' + _parameter.getTitle() + '%'" />
SELECT * FROM BLOG
WHERE title LIKE #{pattern}
Dynamic SQL

</select>

7/3/2019 MYBATIS 105


MULTI-DB VENDOR SUPPORT
4

 build different statements depending on database vendor (under condition


databaseIdProvider is specified)
<insert id="insert">
<selectKey keyProperty="id" resultType="int" order="BEFORE">
<if test="_databaseId == 'oracle'">
Dynamic SQL

select seq_users.nextval from dual


</if>
<if test="_databaseId == 'db2'">
select nextval for seq_users from sysibm.sysdummy1"
</if>
</selectKey>
insert into users values (#{id}, #{name})
</insert>

7/3/2019 MYBATIS 106


3

MODULE 5
Java API & Logging

JAVA API & LOGGING

7/3/2019 MYBATIS 107


1
MYBATIS COMPONENTS
XML Mapper / SQL Query Parameter Object

get
SqlSession Mapper Interface

open
Introduction

SqlSessionFactory Object Result / POJO

build

SqlSessionFactoryBuilder

XML Configuration

database
7/3/2019 MYBATIS 108
SqlSessionFactoryBuilder
4

 has five build() methods, each which allows you to build a SqlSession
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)
Dynamic SQL

7/3/2019 MYBATIS 109


SqlSessionFactoryBuilder
4

 has five build() methods, each which allows you to build a SqlSession
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)
Dynamic SQL

7/3/2019 MYBATIS 110


SqlSessionFactory
4

 has five build() methods, each which allows you to build a SqlSession
SqlSession openSession()
SqlSession openSession(boolean autoCommit)
SqlSession openSession(Connection connection)
SqlSession openSession(TransactionIsolationLevel level)
SqlSession openSession(ExecutorType execType,TransactionIsolationLevel level)
SqlSession openSession(ExecutorType execType)
Dynamic SQL

SqlSession openSession(ExecutorType execType, boolean autoCommit)


SqlSession openSession(ExecutorType execType, Connection connection)
Configuration getConfiguration();

 decisions base on choosing method:


 Transaction: auto-commit or follow current transaction scope
 Connection: acquire a Connection from the configured DataSource, or
provided by caller
 Execution: reuse PreparedStatements and/or batch updates?
 ExecutorType.SIMPLE, ExecutorType.REUSE, ExecutorType.BATCH

7/3/2019 MYBATIS 111


SqlSession
4

 provide methods to execute statements, commit or rollback transactions and


acquire mapper instances.
 statement execution methods:
<T> T selectOne(String statement, Object parameter)
<E> List<E> selectList(String statement, Object parameter)
<K,V> Map<K,V> selectMap(String statement, Object parameter, String mapKey)
Dynamic SQL

int insert(String statement, Object parameter)


int update(String statement, Object parameter)
int delete(String statement, Object parameter)

overloaded version (without object parameter)


<T> T selectOne(String statement)
<E> List<E> selectList(String statement)
<K,V> Map<K,V> selectMap(String statement, String mapKey)
int insert(String statement)
int update(String statement)
int delete(String statement)

7/3/2019 MYBATIS 112


SqlSession
4

advance version with rowbound


<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,
Dynamic SQL

ResultHandler<T> handler)

 transaction control methods


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

7/3/2019 MYBATIS 113


SqlSession
4

 managing local cache


void clearCache()

 ensuring that SqlSession is closed


void close()
Dynamic SQL

 using mappers
<T> T getMapper(Class<T> type)

7/3/2019 MYBATIS 114


LOGGING
4

 MyBatis provides logging information through the use of an internal log


factory, which will delegate logging information to one of the following log
implementations:
 SLF4J
 Apache Commons Logging
 Log4j 2
Dynamic SQL

 Log4j
 JDK logging

7/3/2019 MYBATIS 115


LOGGING
4

 The logging solution chosen is based on runtime introspection by the internal


MyBatis log factory. The MyBatis log factory will use the first logging
implementation it finds (implementations are searched in the above order)
 To select different logging implementation modify mybatis-config.xml
<configuration>
<settings>
Dynamic SQL

...
<setting name="logImpl" value="LOG4J"/>
...
</settings>
</configuration>

 Valid values are SLF4J, LOG4J, LOG4J2, JDK_LOGGING,


COMMONS_LOGGING, STDOUT_LOGGING, NO_LOGGING

7/3/2019 MYBATIS 116


LOGGING
4

 Turning on logging to specific mapper with LOG4J


# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
Dynamic SQL

log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

 To specific method
log4j.logger.org.mybatis.example.BlogMapper.selectBlog=TRACE

 To group of mapper
log4j.logger.org.mybatis.example=TRACE

 in case you want to see the statement but not the result, set the level to
DEBUG (instead of TRACE)
7/3/2019 MYBATIS 117
6

MODULE 6
Spring MyBatis Integration

5
SPRING MYBATIS INTEGRATION
6

7/3/2019 MYBATIS 118


THE BRIDGE
6

 Library that we use for Spring MyBatis integration is MyBatis-Spring

 Versioning
 Spring version 3.0.0 or higher
Spring MyBatis Integration

 Database Connector, in this lab HSQL Connector (org.hsqldb:hsqldb)


version 2.3.1

MyBatis MyBatis-Spring
3.0.1 to 3.0.5 1.0.0 and 1.0.1
3.0.6 1.0.2
3.1.0 or higher 1.1.0 or higher

7/3/2019 MYBATIS 119


ADDITIONAL DEFINITION TO APPLICATIONCONTEXT
6

<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
Spring MyBatis Integration

</bean>

<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.hsqldb.jdbcDriver" />
<property name="url" value="jdbc:hsqldb:mem:embeddedDataSource" />
<property name="username" value=“sa" />
<property name="password" value="" />
</bean>

7/3/2019 MYBATIS 120


MAPPER INTERFACE
6

Definition of Mapper in ApplicationContext

1. Using Individual Definition for Each Mapper


Spring MyBatis Integration

2. Using MapperScannerConfigurer

7/3/2019 MYBATIS 121


MAPPER INTERFACE - INDIVIDUAL DEFINITION
6

Beans.xml

<bean id=“studentMapper"
class="org.mybatis.spring.mapper.MapperFactoryBean">
Spring MyBatis Integration

<property name="mapperInterface" value=“com.tutorialspoint.StudentMapper" />


<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>

7/3/2019 MYBATIS 122


MAPPER INTERFACE - MAPPER SCANNER CONFIGURER
6

Beans.xml

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.tutorialspoint" />
Spring MyBatis Integration

</bean>

Notes
• No need to define individual mapper

7/3/2019 MYBATIS 123


SQL DEFINITION – ANNOTATION-BASED
6

StudentMapper.java

public interface StudentMapper {


Spring MyBatis Integration

@Select("SELECT * FROM students WHERE id = #{studentId}")


Student getStudent(@Param(“studentId") String studentId);
}

7/3/2019 MYBATIS 124


SQL DEFINITION – XML-BASED
6

StudentMapper.xml

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
Spring MyBatis Integration

"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.tutorialspoint.StudentMapper">
<cache />
<select id="getStudent" resultType="com.tutorialspoint.Student“ parameterType=“String">
SELECT ID, NAME, AGE
FROM STUDENT
WHERE STUDENT.ID = #{studentId}
</select>
</mapper>

* Complete reference: http://www.mybatis.org/core/sqlmap-xml.html

7/3/2019 MYBATIS 125


SQL DEFINITION – XML-BASED (CONT)
6

• Cleaner code when dealing with complex queries


• Classpath of xml must be the same as Mapper (unless specified in
SqlSessionFactoryBean)
Spring MyBatis Integration

7/3/2019 MYBATIS 126


PROPERTIES OF SqlSessionFactoryBean
6

<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
Spring MyBatis Integration

<property name="mapperLocations" value="classpath*:mapper/*.xml" />


<property name=“configLocation" value="classpath*:config/mybatis-config.xml"
/>
</bean>

7/3/2019 MYBATIS 127


6
Spring MyBatis Integration

MyBatis Break!
Module 6 & 7

7/3/2019 MYBATIS 128


DATABASE TRANSACTION
6

 Database Transaction, is a sequence of actions that are treated as a single


unit of work

 Characteristics of Database Transaction


Spring MyBatis Integration

 Atomicity: A transaction should be treated as a single unit of operation


which means either the entire sequence of operations is successful or
unsuccessful.
 Consistency: This represents the consistency of the referential integrity of
the database, unique primary keys in tables etc.
 Isolation: There may be many transactions processing with the same data
set at the same time, each transaction should be isolated from others to
prevent data corruption.
 Durability: Once a transaction has completed, the results of this
transaction have to be made permanent and cannot be erased from the
database due to system failure.

7/3/2019 MYBATIS 129


TYPICAL DATABASE TRANSACTION
6

 Begin the transaction using begin transaction command.


 Perform various deleted, update or insert operations using SQL
queries.
 If all the operation are successful then perform commit otherwise
Spring MyBatis Integration

rollback all the operations.

7/3/2019 MYBATIS 130


LOCAL VS. GLOBAL TRANSACTIONS
6

 Local transactions
 specific to a single transactional resource like a JDBC
connection
 usually in a centralized computing environment where
Spring MyBatis Integration

application components and resources are located at a single


site, and transaction management only involves a local data
manager running on a single machine
 easier to be implemented.
 Global transactions
 can span multiple transactional resources like transaction in a
distributed system.
 also involving local transaction level

7/3/2019 MYBATIS 131


TRANSACTIONS HANDLING
6

 Transaction Manager
 Using Spring Transaction Manager
 Container Managed Transaction
Spring MyBatis Integration

 Type of Transaction Management


 Programmatic (manually coded in application), gives extreme flexibility,
but it is difficult to maintain
 Declarative, separate transaction management from the business code,
less flexible but can be modularized with the AOP approach. Spring
supports:
 XML-based
 Proxy-based
 AOP-based
 Annotation-based

7/3/2019 MYBATIS 132


TRANSACTIONS HANDLING – NAMESPACES
6

Beans.xml

<!-- add namespaces definition -->


<beans xmlns="http://www.springframework.org/schema/beans"
Spring MyBatis Integration

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

7/3/2019 MYBATIS 133


TRANSACTION MANAGER – USING SPRING
6

Beans.xml

<!-- Initialization for TransactionManager -->


<bean id="transactionManager"
Spring MyBatis Integration

class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">


<property name="dataSource" ref="dataSource" />
<property name="transactionFactory">
<bean class="org.mybatis.spring.transaction.SpringManagedTransactionFactory" />
</property>
</bean>

7/3/2019 MYBATIS 134


TRANSACTION MANAGER – USING CONTAINER
6

Beans.xml

<!-- Initialization for TransactionManager -->


<tx:jta-transaction-manager />
Spring MyBatis Integration

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">


<property name="dataSource" ref="dataSource" />
<property name="transactionFactory">
<bean class="org.apache.ibatis.transaction.managed.ManagedTransactionFactory" />
</property>
</bean>

7/3/2019 MYBATIS 135


DECLARATIVE TRANSACTION MANAGEMENT
6

 If a method name has been included in the transactional configuration then


created advice will begin the transaction before calling the method.
 Target method will be executed in a try / catch block.
 If the method finishes normally, the AOP advice commits the transaction
Spring MyBatis Integration

successfully otherwise it performs a rollback.

7/3/2019 MYBATIS 136


DECLARATIVE TRX MNGMT – USING XML
6

Beans.xml

<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
Spring MyBatis Integration

</bean>

<tx:advice id="txAdvice" transaction-manager="transactionManager">


<tx:attributes>
<tx:method name=“createStudent"/>
</tx:attributes>
</tx:advice>

<aop:config>
<aop:pointcut id=“create"
expression="execution(* com.training.StudentMapper. createStudent(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref=“create"/>
</aop:config>

7/3/2019 MYBATIS 137


DECLARATIVE TRX MNGMT – USING ANNOTATION
6

Beans.xml
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
Spring MyBatis Integration

</bean>

<tx:annotation-driven/>

StudentService.java

public interface StudentService {


public void setStudentMapper(StudentMapper studentMapper);

@Transactional( propagation = Propagation.REQUIRED, readOnly = true)


public void createStudent(Student student);
}

7/3/2019 MYBATIS 138


DECLARATIVE TRX MNGMT – USING ANNOTATION
6

Transaction Definition Description


ISOLATION_DEFAULT This is the default isolation level.
ISOLATION_READ_COMMITTED Indicates that dirty reads are prevented; non-
Spring MyBatis Integration

repeatable reads and phantom reads can


occur.
ISOLATION_READ_UNCOMMITTED Indicates that dirty reads, non-repeatable
reads and phantom reads can occur.
ISOLATION_REPEATABLE_READ Indicates that dirty reads and non-repeatable
reads are prevented; phantom reads can
occur.
ISOLATION_SERIALIZABLE Indicates that dirty reads, non-repeatable
reads and phantom reads are prevented
7/3/2019 MYBATIS 139
DECLARATIVE TRX MNGMT – USING ANNOTATION
6

Propagation Description
PROPAGATION_MANDATORY Support a current transaction; throw an
exception if no current transaction exists.
Spring MyBatis Integration

PROPAGATION_NESTED Execute within a nested transaction if a


current transaction exists.
PROPAGATION_NEVER Do not support a current transaction; throw
an exception if a current transaction exists.
PROPAGATION_NOT_SUPPORTED Do not support a current transaction; rather
always execute non-transactionally.
PROPAGATION_REQUIRED Support a current transaction; create a new
one if none exists.

7/3/2019 MYBATIS 140


6
Spring MyBatis Integration

MyBatis Break!
Module 8 & 9

7/3/2019 MYBATIS 141


BENEFIT OF USING SPRING
6

Consistent Exception Handling


• Spring has it’s own exception handling hierarchy for DAO logic
• No more copy and pasting redundant exception logic!
Spring MyBatis Integration

• Exceptions from JDBC, or a supported ORM, are wrapped up into


an appropriate, and consistent, DataAccessException and thrown
• This allows you to decouple exceptions in your business logic
• These exceptions are treated as unchecked exceptions that you can
handle in your business tier if needed. No need to try/catch in
your DAO
• Define your own exception translation by subclassing classes such as
SQLErrorCode, SQLExceptionTranslator

7/3/2019 MYBATIS 142


7

3
MODULE 7
MyBatis Generator

5
MYBATIS GENERATOR
6

7/3/2019 MYBATIS 143


MYBATOR
7

Tools to generate MyBatis code:


 Java POJOs for tables, may includes
 a class for primary key
 a class for non-primary key fields
 a class for BLOB fields
MyBatis Generator

 a class to enable dynamic selects, updates, deletes (example class)


 SQL Map XML Files, contains
 insert
 update by primary key, update by example
 delete by primary key, delete by example
 select by primary key, select by example
 count by example
 Java clients
 A mapper interface that works with the MyBatis 3.x mapper infrastructure

7/3/2019 MYBATIS 144


GETTING STARTED
7

It requires an XML configuration files, consist of below information

 <jdbcConnection> to specify how to connect to the target


database
MyBatis Generator

 <javaModelGenerator> element to specify target package and


target project for generated Java model objects
 <sqlMapGenerator> element to specify target package and
target project for generated SQL map files
 optional <javaClientGenerator> element to specify target
package and target project for generated client interfaces and
classes
 at least one database <table> element

7/3/2019 MYBATIS 145


RUNNING MYBATOR
7

MyBator can be run:


 from command prompt
 as Ant Task
 as a Maven Plugin
MyBatis Generator

 from another Java program with an XML configuration


 from another Java program with a Java based
configuration
 by using Eclipse plugin

7/3/2019 MYBATIS 146


RUNNING MYBATOR FROM COMMAND PROMPT
7

C:\>java -jar mybatis-generator-core-x.x.x.jar <arguments>


-configfile file_name required specifies the the configuration file.
-overwrite optional If specified, then existing Java files will be
overwritten. If not specified, and a Java file
MyBatis Generator

already exists, then MyBator will write the newly


generated Java file with a unique name (e.g.
MyClass.java.1, MyClass.java.2, etc.).
Important: The generator will always merge and
overwrite XML files.
-verbose optional If specified, then progress messages will be written
to the console.
-forceJavaLogging optional If specified, then MyBator will use Java logging
rather than Log4J
7/3/2019 MYBATIS 147
RUNNING MYBATOR FROM COMMAND PROMPT
7

-contextids optional If specified, then this is a comma delimited list of


context1,context2,... contexts to use in the current run. Any id specified
in the list must exactly match the value of the id
attribute of an <context> configuration element.
Only ids specified in this list will be active for this
MyBatis Generator

run. If this argument is not specified, then all


contexts will be active.
-tables table1, optional If specified, then this is a comma delimited list of
table2,... tables to use in the current run. Any table specified
in the list must exactly match the fully qualified
table name specified in a <table> configuration
element. Only tables specified in this list will be
active for this run. If this argument is not specified,
then all tables will be active.
7/3/2019 MYBATIS 148
RUNNING MYBATOR AS ANT TASK
7

Define MyBator task in your build.xml


<project default="genfiles" basedir=".">
<property name="generated.source.dir" value="${basedir}" />
<target name="genfiles" description="Generate the files">
<taskdef name="mbgenerator"
classname="org.mybatis.generator.ant.GeneratorAntTask"
MyBatis Generator

classpath="mybatis-generator-core-x.x.x.jar" />
<mbgenerator overwrite="true" configfile="generatorConfig.xml"
verbose="false" >
<propertyset>
<propertyref name="generated.source.dir"/>
</propertyset>
</mbgenerator>
</target>
</project>

7/3/2019 MYBATIS 149


RUNNING MYBATOR WITH MAVEN PLUGIN
7

mvn mybatis-generator:generate

pom.xml
<project ...>
...
<build>
MyBatis Generator

...
<plugins>
...
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.0</version>
</plugin>
...
</plugins>
...
</build>
...
</project>
7/3/2019 MYBATIS 150
RUNNING MYBATOR WITH JAVA (XML CONFIG)
7

List<String> warnings = new ArrayList<String>();


boolean overwrite = true;
File configFile = new File("generatorConfig.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
MyBatis Generator

Configuration config = cp.parseConfiguration(configFile);


DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,
callback, warnings);
myBatisGenerator.generate(null);

7/3/2019 MYBATIS 151


RUNNING MYBATOR WITH JAVA (JAVA CONFIG)
7

List<String> warnings = new ArrayList<String>();


boolean overwrite = true;
Configuration config = new Configuration();
MyBatis Generator

// ... fill out the config object as appropriate...

DefaultShellCallback callback = new DefaultShellCallback(overwrite);


MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback,
warnings);
myBatisGenerator.generate(null);

7/3/2019 MYBATIS 152


RUNNING MYBATOR WITH ECLIPSE PLUGIN
7

 Install software from update site:


http://mybatis.googlecode.com/svn/sub-projects/generator/trunk/eclipse/UpdateSite/

 Make sure your jdbc driver is added in your build classpath


MyBatis Generator

 Right click your configuration file, and choose Generate


MyBatis/iBATIS Artifacts

7/3/2019 MYBATIS 153


RUNNING MYBATOR WITH ECLIPSE PLUGIN
7
MyBatis Generator

7/3/2019 MYBATIS 154


XML CONFIGURATION REFERENCE
7

http://mybatis.github.io/generator/configreference/xmlconfig.html

<classPathEntry> opt add classpath locations to the classpath


<columnOverride> opt change certain attributes of an introspected database column from
the values that would be calculated by default
MyBatis Generator

<columnRenamingRule> opt rename database columns before calculating the corresponding


property name in an introspected table
<commentGenerator> opt define properties of the Comment Generator
<context> opt specify the environment for generating a set of objects
<generatedKey> opt specify properties for auto generated keys (from identity field or
sequences)
<generatorConfiguration> req root element of a MyBatis Generator configuration file.
<ignoreColumn> opt ignore a column in an introspected table

7/3/2019 MYBATIS 155


XML CONFIGURATION REFERENCE
7

<javaClientGenerator> opt define properties of the Java client generator


<javaModelGenerator> req define properties of the Java model generator
<javaTypeResolver> opt define properties of the Java Type Resolver
<jdbcConnection> req specify the properties of the database connection required to
MyBatis Generator

introspect tables
<plugin> opt define a plugin
<properties> opt specify an external properties file for use in the parsing of the
configuration
<property> opt specify properties for many of the other elements
<sqlMapGenerator> req define properties of the SQL map generator
<table> req elect a table in the database for introspection

7/3/2019 MYBATIS 156


ITERATIVE DEVELOPMENT SUPPORT
7

MyBator can be run iteratively using:


 Ant Task
 Maven Plug-In

When run iteratively, please notes:


MyBatis Generator

 automatically merge XML files if there is an existing file with the same name
as the newly generated XML file
 will not merge Java files, it can either overwrite existing files or save newly
generated files with a different unique name

When run from Eclipse plugin:


 Will also automatically merge Java files if there is an existing file with the
same name as the newly generated Java file

7/3/2019 MYBATIS 157


SUPPLIED PLUGINS
7

• org.mybatis.generator.plugins.CachePlugin
• adds a <cache> element to generated SQL maps.
• org.mybatis.generator.plugins.CaseInsensitiveLikePlugin
• adds methods to the Example class (actually to the Criteria inner class) to
support case insensitive LIKE searches
MyBatis Generator

• org.mybatis.generator.plugins.EqualsHashCodePlugin
• adds equals and hashCode methods to the Java model objects generated
by MBG
• org.mybatis.generator.plugins.MapperConfigPlugin
• generates a skeleton MapperConfig.xml
• org.mybatis.generator.plugins.RenameExampleClassPlugin
• demonstrates usage of the initialized method by renaming the generated
example classes generated by MBG

7/3/2019 MYBATIS 158


SUPPLIED PLUGINS
6

• org.mybatis.generator.plugins.RowBoundsPlugin
• adds a new version of the selectByExample method that accepts a
RowBounds parameter.
• org.mybatis.generator.plugins.SerializablePlugin
• adds the marker interface java.io.Serializable to the Java model objects
MyBatis Generator

generated by MBG. This plugin also adds the serialVersionUID field to the
model classes
• org.mybatis.generator.plugins.ToStringPlugin
• adds toString() methods to the generated model classes
• org.mybatis.generator.plugins.VirtualPrimaryKeyPlugin
• can be used to specify columns that act as primary keys, even if they are
not defined as primary key in the database.
<table tableName="foo">
<property name="virtualKeyColumns" value="ID1, ID2" />
</table>
7/3/2019 MYBATIS 159
7
MyBatis Generator

MyBatis Break!
Module 10 & 11

7/3/2019 MYBATIS 160


THE END

7/3/2019 MYBATIS 161

Вам также может понравиться