Defining a database connection

With MyBatis, you can define a database connection using a Java API or a configuration XML file. The easiest way is to put an XML file in the classpath (the resources directory, when using Maven). The following is an example of such a configuration file:

<?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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="org.h2.Driver"/>
<property name="url"
value="jdbc:h2:tcp://localhost/~/h2-databases/demo"/>
<property name="username" value="sa"/>
<property name="password" value=""/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper
class="packt.vaadin.datacentric.chapter06.mybatis.MessageMapper"/>
</mappers>
</configuration>

You can use any name for this file. The example for this section uses mybatis-config.xml.

As you can see, we used the same connection properties we used for JDBC and JPA, but we added a driver property. Its value should correspond to the name of JDBC driver which you are going to use for the database connection.

How do we use this file? Once again, we can use a ServletContextListener to initialize MyBatis. Moreover, the ServletContextListener can delegate to a service class like the following:

public class MyBatisService {

private static SqlSessionFactory sqlSessionFactory;

public static void init() {
InputStream inputStream = MyBatisService.class.getResourceAsStream("/mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}

public static SqlSessionFactory getSqlSessionFactory() {
return sqlSessionFactory;
}
}

The SqlSessionFactory class is the entry point to MyBatis. The previous class provides the init method that can be called from a ServletContextListener, which creates one SqlSessionFactory per instance of the application, and exposes it through a getter. This is a pattern similar to the one we previously used with JPA.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset