MyBatis Intro
MyBatis Intro
0
ACKNOWLEDGMENT
3.3
7/3/2019 MYBATIS 2
3.3
AGENDA
1 Introduction
2 Configuration XML
4 Dynamic SQL
MYBATIS
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
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
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
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
build
SqlSessionFactoryBuilder
application scope
XML Configuration
method scope
database
7/3/2019 MYBATIS 15
1
MyBatis Break
Introduction
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
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
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
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
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
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 :
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
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
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
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
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
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})})
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
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
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
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
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>
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
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
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
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
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
#{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
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
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
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
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
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>
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
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
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
7/3/2019 MYBATIS 85
3
RESULT MAPS – NESTED SELECT COLLECTION
For example :
1
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
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
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
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"/>
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"/>
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
Features
if
choose (when, otherwise)
Dynamic SQL
7/3/2019 MYBATIS 98
IF
4
<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
<if test="title != null">
Dynamic SQL
7/3/2019 MYBATIS 99
CHOOSE, WHEN, OTHERWISE
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
<update id="updateAuthorIfNecessary">
update Author
<set>
<if test="username != null">username=#{username},</if>
<if test="password != null">password=#{password},</if>
Dynamic SQL
</select>
MODULE 5
Java API & Logging
get
SqlSession Mapper Interface
open
Introduction
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
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
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
ResultHandler<T> handler)
using mappers
<T> T getMapper(Class<T> type)
Log4j
JDK logging
...
<setting name="logImpl" value="LOG4J"/>
...
</settings>
</configuration>
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
Versioning
Spring version 3.0.0 or higher
Spring MyBatis Integration
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
<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>
2. Using MapperScannerConfigurer
Beans.xml
<bean id=“studentMapper"
class="org.mybatis.spring.mapper.MapperFactoryBean">
Spring MyBatis Integration
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
StudentMapper.java
StudentMapper.xml
"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>
<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
Spring MyBatis Integration
MyBatis Break!
Module 6 & 7
Local transactions
specific to a single transactional resource like a JDBC
connection
usually in a centralized computing environment where
Spring MyBatis Integration
Transaction Manager
Using Spring Transaction Manager
Container Managed Transaction
Spring MyBatis Integration
Beans.xml
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">
Beans.xml
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
Beans.xml
Beans.xml
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
Spring MyBatis Integration
</bean>
<aop:config>
<aop:pointcut id=“create"
expression="execution(* com.training.StudentMapper. createStudent(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref=“create"/>
</aop:config>
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
Propagation Description
PROPAGATION_MANDATORY Support a current transaction; throw an
exception if no current transaction exists.
Spring MyBatis Integration
MyBatis Break!
Module 8 & 9
3
MODULE 7
MyBatis Generator
5
MYBATIS GENERATOR
6
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>
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
http://mybatis.github.io/generator/configreference/xmlconfig.html
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
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
• 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
• 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