We are using the ps.setString() and rs.getString() methods because the phone number is being stored in a VARCHAR type column

Một phần của tài liệu Java persistence with mybatis 3 (Trang 48 - 55)

Here XXX Here XXX can be any one of Int , String , Date , and so on, based on the type

2. We are using the ps.setString() and rs.getString() methods because the phone number is being stored in a VARCHAR type column

3. Once the custom type handler is implemented, we need to register it in mybatis-config.xml.

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

<!DOCTYPE configuration

PUBLIC "-//mybatis.org//DTD Config 3.0//EN"

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

<configuration>

<properties resource="application.properties"/>

<typeHandlers>

<typeHandler handler="com.mybatis3.typehandlers.

PhoneTypeHandler"/>

</typeHandlers>

</configuration>

After registering PhoneTypeHandler, MyBatis will be able to store the Phone type object value into any VARCHAR type column.

Bootstrapping MyBatis

[ 38 ]

Settings

The default MyBatis global settings, which can be overridden to better suit application-specific needs, are as follows:

<settings>

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

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

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

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

<setting name="useGeneratedKeys" value="false"/>

<setting name="autoMappingBehavior" value="PARTIAL"/>

<setting name="defaultExecutorType" value="SIMPLE"/>

<setting name="defaultStatementTimeout" value="25000"/>

<setting name="safeRowBoundsEnabled" value="false"/>

<setting name="mapUnderscoreToCamelCase" value="false"/>

<setting name="localCacheScope" value="SESSION"/>

<setting name="jdbcTypeForNull" value="OTHER"/>

<setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode ,toString"/>

</settings>

Mappers

Mapper XML files contain the mapped SQL statements that will be executed by the application using statement id. We need to configure the locations of the SQL Mapper files in mybatis-config.xml.

<mappers>

<mapper resource="com/mybatis3/mappers/StudentMapper.xml"/>

<mapper url="file:///D:/mybatisdemo/app/mappers/TutorMapper.xml"/>

<mapper class="com.mybatis3.mappers.TutorMapper"/>

<package name="com.mybatis3.mappers"/>

</mappers>

Each of the <mapper> tag attributes facilitates to load mappers from different kinds of sources:

• The attribute resource can be used to point to a mapper file that is in the classpath

• The attribute url can be used to point to a mapper file by its fully qualified filesystem path or web URL

Chapter 2

[ 39 ]

• The attribute class can be used to point to a Mapper interface

• The package element can be used to point to a package name where Mapper interfaces can be found

Configuring MyBatis using Java API

In the previous section, we have discussed various MyBatis configuration elements, such as environments, typeAliases, and typeHandlers, and how to configure them using XML. Even though you want to use the Java-API-based MyBatis configuration, it would be good to go through the previous section to have a better idea about these configuration elements. In this section, we will be referring to some of the classes described in the previous section.

MyBatis' SqlSessionFactory interface can be created programmatically using the Java API instead of using the XML-based configuration. Each configuration element used in an XML-based configuration can be created programmatically.

We can create the SqlSessionFactory object using the Java API as follows:

public static SqlSessionFactory getSqlSessionFactory() {

SqlSessionFactory sqlSessionFactory = null;

try{

DataSource dataSource = DataSourceFactory.getDataSource();

TransactionFactory transactionFactory = new JdbcTransactionFactory();

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

Configuration configuration = new Configuration(environment);

configuration.getTypeAliasRegistry().registerAlias("student", Student.class);

configuration.getTypeHandlerRegistry().register(PhoneNumber.

class,PhoneTypeHandler.class);

configuration.addMapper(StudentMapper.class);

sqlSessionFactory = new SqlSessionFactoryBuilder().

build(configuration);

}catch (Exception e){

throw new RuntimeException(e);

}

return sqlSessionFactory;

}

Bootstrapping MyBatis

[ 40 ]

Environment

We need to create an Environment object for each database that we want to connect to using MyBatis. To work with multiple databases, we'll need to create a SqlSessionFactory object for each environment. To create an instance of Environment, we'll need the javax.sql.DataSource and TransactionFactory instances. Let us see how to create the DataSource and TransactionFactory objects.

DataSource

MyBatis supports three built-in DataSource types: UNPOOLED, POOLED, and JNDI.

• The UNPOOLED dataSource creates a new database connection every time for each user request and is not advisable for concurrent multiuser applications.

• The POOLED dataSource creates a pool of Connection objects, and for every user request, it will use one of the Connection objects readily available in the pool, thereby increasing performance. MyBatis provides org.apache.

ibatis.datasource.pooled.PooledDataSource that implements javax.

sql.DataSource to create a Connection pool.

• The JNDI dataSource uses the Connection pool configured in the application server and obtains a connection using a JNDI lookup.

Let us see how we can get a DataSource object using MyBatis' PooledDataSource interface:

public class DataSourceFactory {

public static DataSource getDataSource() {

String driver = "com.mysql.jdbc.Driver";

String url = "jdbc:mysql://localhost:3306/mybatisdemo";

String username = "root";

String password = "admin";

PooledDataSource dataSource = new PooledDataSource(driver, url, username, password);

return dataSource;

} }

Generally in production environments, DataSource will be configured in the application server and get the DataSource object using JNDI as follows:

public class DataSourceFactory {

public static DataSource getDataSource()

Chapter 2

[ 41 ] {

String jndiName = "java:comp/env/jdbc/MyBatisDemoDS";

try {

InitialContext ctx = new InitialContext();

DataSource dataSource = (DataSource) ctx.lookup(jndiName);

return dataSource;

}

catch (NamingException e) { throw new RuntimeException(e);

} } }

There are many popular third-party libraries, such as commons-dbcp and c3p0, implementing javax.sql.DataSource, and you can use any of these libraries to create a dataSource.

TransactionFactory

MyBatis supports the following two types of TransactionFactory implementations:

• JdbcTransactionFactory

• ManagedTransactionFactory

If the application is running in a non-managed environment, you should use JdbcTransactionFactory.

DataSource dataSource = DataSourceFactory.getDataSource();

TransactionFactory txnFactory = new JdbcTransactionFactory();

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

If the application is running in a managed environment and uses container-supported transaction management services, you should use ManagedTransactionFactory.

DataSource dataSource = DataSourceFactory.getDataSource();

TransactionFactory txnFactory = new ManagedTransactionFactory();

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

Bootstrapping MyBatis

[ 42 ]

typeAliases

MyBatis provides several ways of registering Type Aliases with the Configuration object.

• To register an alias for a single class with an uncapitalized, nonqualified class name according to the default alias rule, use the following code:

configuration.getTypeAliasRegistry().registerAlias(Student.class);

• To register a single class alias with a given alias name, use the following code:

configuration.getTypeAliasRegistry().registerAlias("Student", Student.class);

• To register a single class alias name for the given fully qualified class name, use the following code:

configuration.getTypeAliasRegistry().registerAlias("Student",

"com.mybatis3.domain.Student");

• To register aliases for all the classes in the com.mybatis3.domain package, use the following code:

configuration.getTypeAliasRegistry().registerAliases("com.

mybatis3.domain");

• To register aliases for the classes that extend the Identifiable type in the com.mybatis3.domain package, use the following code

configuration.getTypeAliasRegistry().registerAliases("com.

mybatis3.domain", Identifiable.class);

typeHandlers

MyBatis provides several ways of registering type handlers with the Configuration object. We can register custom type handlers using the Configuration object as follows:

• To register a type handler for a specific Java class:

configuration.getTypeHandlerRegistry().register(PhoneNumber.

class,PhoneTypeHandler.class);

• To register a type handler:

configuration.getTypeHandlerRegistry().register(PhoneTypeHandler.

class);

Chapter 2

[ 43 ]

• To register all the type handlers in the com.mybatis3.typehandlers package:

configuration.getTypeHandlerRegistry().register("com.mybatis3.

typehandlers");

Settings

MyBatis comes with a set of default global settings that suit well for most

applications. However, you can tweak these settings to better suit your application needs. You can use the following methods to set the values of the global settings to the desired values.

configuration.setCacheEnabled(true);

configuration.setLazyLoadingEnabled(false);

configuration.setMultipleResultSetsEnabled(true);

configuration.setUseColumnLabel(true);

configuration.setUseGeneratedKeys(false);

configuration.setAutoMappingBehavior(AutoMappingBehavior.PARTIAL);

configuration.setDefaultExecutorType(ExecutorType.SIMPLE);

configuration.setDefaultStatementTimeout(25);

configuration.setSafeRowBoundsEnabled(false);

configuration.setMapUnderscoreToCamelCase(false);

configuration.setLocalCacheScope(LocalCacheScope.SESSION);

configuration.setAggressiveLazyLoading(true);

configuration.setJdbcTypeForNull(JdbcType.OTHER);

Set<String> lazyLoadTriggerMethods = new HashSet<String>();

lazyLoadTriggerMethods.add("equals");

lazyLoadTriggerMethods.add("clone");

lazyLoadTriggerMethods.add("hashCode");

lazyLoadTriggerMethods.add("toString");

configuration.setLazyLoadTriggerMethods(lazyLoadTriggerMethods );

Mappers

MyBatis provides several ways of registering Mapper XML files and Mapper interfaces with the Configuration object.

• To add a single Mapper interface, use the following code:

configuration.addMapper(StudentMapper.class);

• To add all the Mapper XML files or interfaces in the com.mybatis3.mappers package, use the following code:

configuration.addMappers("com.mybatis3.mappers");

Bootstrapping MyBatis

[ 44 ]

• To add all the Mapper interfaces that extend an interface, say BaseMapper, in the com.mybatis3.mappers package, use the following code:

configuration.addMappers("com.mybatis3.mappers", BaseMapper.

class);

Mappers should be added to the configuration only after registering typeAliases and typeHandlers if they have been used.

Customizing MyBatis logging

MyBatis uses its internal LoggerFactory as a facade to actual logging libraries.

The internal LoggerFactory will delegate the logging task to one of the following actual logger implementations, with the priority decreasing from top to bottom in the given order:

Một phần của tài liệu Java persistence with mybatis 3 (Trang 48 - 55)

Tải bản đầy đủ (PDF)

(133 trang)