MyBatis 3 – Spring integration tutorial

本文详细介绍了如何使用MyBatis和Spring框架整合实现数据库CRUD操作,包括配置数据源、事务管理、SqlSessionFactory和MapperScanner等关键步骤。

MyBatis 3 – Spring integration tutorial

As a first step of this tutorial, Spring MVC 3 CRUD example with MyBatis 3, we will define a MyBatis service that will help us to perform CRUD operation on database.

We have a domain class for User and a database table to store the User information on database. We will use xml configuration model for our example to define SQL commands that will perform CRUD operation.

Our Domain class

01package com.raistudies.domain;
02  
03import java.io.Serializable;
04  
05public class User implements Serializable{
06  
07    private static final long serialVersionUID = 3647233284813657927L;
08  
09    private String id;
10    private String name = null;
11    private String standard = null;
12    private String age;
13    private String sex = null;
14  
15    //setter and getter have been omitted to make the code short
16  
17    @Override
18    public String toString() {
19        return "User [name=" + name + ", standard=" + standard + ", age=" + age
20        + ", sex=" + sex + "]";
21    }
22}

We have five properties in our domain class called User for which have to provide database services.

Our Database Table

Following is our database table:

1CREATE TABLE `user` (
2    `id` varchar(36) NOT NULL,
3    `name` varchar(45) DEFAULT NULL,
4    `standard` varchar(45) DEFAULT NULL,
5    `age` varchar(45) DEFAULT NULL,
6    `sex` varchar(45) DEFAULT NULL,
7    PRIMARY KEY (`id`)
8) ENGINE=InnoDB DEFAULT CHARSET=utf8

Creating interface for CRUD operations

For defining the CRUD database operation using MyBatis 3, we have to specify the methods that will be used to perform CRUD operation. Following is the interface for our example:

01package com.raistudies.persistence;
02  
03import java.util.List;
04  
05import com.raistudies.domain.User;
06  
07public interface UserService {
08  
09    public void saveUser(User user);
10    public void updateUser(User user);
11    public void deleteUser(String id);
12    public List<User> getAllUser();
13}

We have four methods here to perform operations create,update , delete and get from database.

XML Mapping file for UserService interface

01<?xml version="1.0" encoding="UTF-8"?>
02<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
04  
05<mapper namespace="com.raistudies.persistence.UserService">
06  
07    <resultMap id="result" type="user">
08        <result property="id" column="id"/>
09        <result property="name" column="name"/>
10        <result property="standard" column="standard"/>
11        <result property="age" column="age"/>
12        <result property="sex" column="sex"/>
13    </resultMap>
14  
15    <select id="getAllUser" parameterType="int" resultMap="result">
16        SELECT id,name,standard,age,sex
17        FROM user;
18    </select>
19  
20    <insert id="saveUser" parameterType="user">
21        INSERT INTO user (id,name,standard,age,sex)
22        VALUE (#{id},#{name},#{standard},#{age},#{sex})
23    </insert>
24  
25    <update id="updateUser" parameterType="user">
26        UPDATE user
27        SET
28        name = #{name},
29        standard = #{standard},
30        age = #{age},
31        sex = #{sex}
32        where id = #{id}
33    </update>
34  
35    <delete id="deleteUser" parameterType="int">
36        DELETE FROM user
37        WHERE id = #{id}
38    </delete>
39</mapper>

You will see a lot of things new here:

The mapping file will contain element <mapper/> to define the SQL statement for the services. Here the property “namespace” defines the interface for which this mapping file has been defined.

<insert/> tag defines that the operation is of type insert. The value of “id” property specifies the function name for which the SQL statement is been defined. Here it is “saveUser“. The property “parameterType” defines the parameter of the method is of which type. We have used alias for the class User here. The alias will be configured in MyBatis Configuration file later. Then, we have to define the SQL Statement. #{id} defines that the property “id” of class User will be passed as a parameter to the SQL query.

<resultMap/> tag is used to specify the mapping between the User class and user table. id of <resultMap/> is a unique name to the mapping definition. Under this tag, we define the different properties and which column is bounded to which property.

<select/> tag is used to specify a select SQL statement. The value of “id” property specifies the function name for which the SQL statement is been defined.

The attribute resultMap is used to define the return type of the SQL statement as a collection.

MyBatis 3 Configuration file

Following is our configuration file for MyBatis:

01<?xml version="1.0" encoding="UTF-8"?>
02<!DOCTYPE configuration
03PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
05  
06<configuration>
07    <settings>
08        <!-- changes from the defaults -->
09       <setting name="lazyLoadingEnabled" value="false" />
10    </settings>
11    <typeAliases>
12        <typeAlias type="com.raistudies.domain.User" alias="user"/>
13    </typeAliases>
14</configuration>

You can see, we have not defined some very important properties here:

  1. Database connection properties.
  2. Transaction related properties.
  3. And also have not defined mappers configuration.

MyBatis 3 is very powerful SQL mapping framework with automatic database access class generation using a proxy implementation of the services defined by users. We get realize it’s true power if you integrate MyBatis 3 with Spring framework and use these proxy implementation. It will reduce our database work by 80%. Below, we will see how to integrate MyBatis 3 with Spring 3 framework. Previously, we created the CRUD database service for class User using MyBatis 3. Now, we will integrate the data services implemented using MyBatis with Spring framework.

Tools Used:

  • c3p0-0.9.1.2.jar – For providing pooled database connection.
  • mybatis-spring-1.0.0.jar – For integrating MyBatis with Spring (Provided by MyBatis team)
  • Spring JDBC and Core library

To integrate these two frameworks, we have to follow bellow steps:

Step 1: Defining datasource as a Spring bean
As we will use c3po data source provider, we have to define datasource bean in Spring. Following is the configuration snippet:

1<!-- Declare a datasource that has pooling capabilities -->
2<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
3destroy-method="close" p:driverClass="${app.jdbc.driverClassName}"
4p:jdbcUrl="${app.jdbc.url}" p:user="${app.jdbc.username}" p:password="${app.jdbc.password}"
5p:acquireIncrement="10" p:idleConnectionTestPeriod="60" p:maxPoolSize="100"
6p:maxStatements="50" p:minPoolSize="10" />

Here we have created a spring bean with id dataSource of class com.mchange.v2.c3p0.ComboPooledDataSource which is provided by c3p0 library for pooled data source.

We have set some properties in the bean. Following is the description of properties defined in bean:

  • driverClass : Driver class that will be used to connect to database.
  • jdbcUrl : jdbc url defining the database connection string.
  • user : username of the database user.
  • password : password of the database user.
  • acquireIncrement : how many connections will be created at a time when there will be a shortage of connections.
  • idleConnectionTestPeriod : after how much delay a connection will be closed if it is no longer in use.
  • maxPoolSize : Max number of connections that can be created.
  • maxStatements : Max number of SQL statements to be executed on a connection.
  • minPoolSize : Minimum number of connections to be created.

We have used Spring EL to define many of the property values, that will be bring from properties file.

Defining Transaction Manager in Spring

We will user Transaction Manager provided by Spring JDBC framework and for defining transaction levels we will use annotations. Following is the configuration for transaction manager:

1<!-- Declare a transaction manager -->
2<bean id="transactionManager"
3class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
4p:dataSource-ref="dataSource" />
5  
6<!-- Enable annotation style of managing transactions -->
7<tx:annotation-driven transaction-manager="transactionManager" />

Defining MyBatis SqlSessionFactory and MapperScanner

01<!-- define the SqlSessionFactory, notice that configLocation is not needed when you use MapperFactoryBean -->
02<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
03    <property name="dataSource" ref="dataSource" />
04    <property name="configLocation" value="WEB-INF/mybatis/sqlmap-config.xml" />
05</bean>
06  
07<!-- scan for mappers and let them be autowired -->
08<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
09    <property name="basePackage" value="${MapperInterfacePackage}" />
10</bean>

The SqlSessionFactory bean will provide SessionFactory instances of MyBatis. To configure SqlSessionFactory, we need to define two properties. First the data source which will be used by MyBatis to create connection database and MyBatis configuration file name to configure the environment of MyBatis.

MapperScannerConfigurer is used to publish the data service interfaces in defined for MyBatis to configure as Spring Beans. We just have to provide package in which the interfaces and their mapping XML files has been defined. We can specify more than one packages using common separation or semicolon. After that we will be able to get the instances of UserService using @Autowired annotation. We do not have to implement the interface as MyBatis will provide proxy implementation for this.

Spring configuration file as together
Here is our jdbc-context.xml as together:

01<?xml version="1.0" encoding="UTF-8"?>
05xsi:schemaLocation="
06  
08  
09  
11  
12  
14  
15  
17  
18  
20  
21  
23  
24">
25  
26<context:property-placeholder location="/WEB-INF/jdbc.properties,/WEB-INF/mybatis/mybatis.properties" />
27  
28    <!-- Enable annotation style of managing transactions -->
29    <tx:annotation-driven transaction-manager="transactionManager" />
30  
31    <!-- Declare a datasource that has pooling capabilities -->
32    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
33    destroy-method="close" p:driverClass="${app.jdbc.driverClassName}"
34    p:jdbcUrl="${app.jdbc.url}" p:user="${app.jdbc.username}" p:password="${app.jdbc.password}"
35    p:acquireIncrement="10" p:idleConnectionTestPeriod="60" p:maxPoolSize="100"
36    p:maxStatements="50" p:minPoolSize="10" />
37  
38    <!-- Declare a transaction manager -->
39    <bean id="transactionManager"
40    class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
41    p:dataSource-ref="dataSource" />
42  
43    <!-- define the SqlSessionFactory, notice that configLocation is not needed when you use MapperFactoryBean -->
44    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
45        <property name="dataSource" ref="dataSource" />
46        <property name="configLocation" value="WEB-INF/mybatis/sqlmap-config.xml" />
47    </bean>
48  
49    <!-- scan for mappers and let them be autowired -->
50    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
51        <property name="basePackage" value="${MapperInterfacePackage}" />
52    </bean>
53  
54</beans>

jdbc.properties file

1# database properties
2app.jdbc.driverClassName=com.mysql.jdbc.Driver
3app.jdbc.url=jdbc:mysql://localhost/mybatis-example
4app.jdbc.username=root
5app.jdbc.password=password

mybatis.properties file

1MapperInterfacePackage=com.raistudies.persistence

Reference:  Creating CRUD service using MyBatis 3 Mapping Framework – Part 1 & Integrating MyBatis 3 and Spring frameworks – Part 2 from our JCG partner Rahul Mondal at the Rai Studies blog.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值