Spring Integrated MyBatis Framework

Keywords: Java Mybatis Spring Database xml

When Java writes database queries, I have been exposed to four ways:

1. Pure Java code, refer to the corresponding database driver package, write the connection and release logic (you can use connection pool)

In fact, the performance of this mode is very good, but it is not very convenient to use: first, it needs to be manually acquired and released for Connection, and a lot of redundant code is prone to errors; second, complex SQL written in strings is simply not maintainable (newline, visual length, parameters are all problems).

2. Use Spring JdbcTemplate

In fact, it's quite good. It's easy to configure, more functional and more comfortable than manual management of Connection, and the code is more concise. The outstanding problem is that the maintenance of SQL is still troublesome.

3. Using Hibernate Framework

In a word, the configuration is troublesome, and it's good to use. But there is a fatal flaw, it can not help us to complete multi-table queries like single-table queries. If there are complex multi-table queries or query conditions, it is still necessary to use SQL to check. For some businesses with complex business logic or frequent changes, post-maintenance is a disaster, instead of crying (because it is really chaotic, we must start planning).

4. Using MyBatis Framework

This is the most popular database persistence framework in my current project. It can easily and intuitively help you complete comprehensive queries of various conditions, judgments and tables through XML configuration. It is much more comfortable than using Java code to spell SQL. In this respect, it is a street to reject Hibernate. Easy to use, in fact, is quite easy to use, but the configuration also needs to map some data, but relatively more flexible. Its entity class is not necessarily a database physical table, but can be arbitrarily queried data sets (similar to data transfer object DTO).

   

To summarize briefly:

Configuration ease: 1 > 2 > 4 > 3

Convenience of use: 2 > 3 > 4 > 1

Query flexibility: 4 > 1 = 2 > 3

Next, I will introduce the configuration and use of Spring integrated MyBatis. The project is based on Maven and connects to Mysql database.

 

Maven configuration

 1         <!-- Spring Base -->
 2         <dependency>
 3             <groupId>org.springframework</groupId>
 4             <artifactId>spring-beans</artifactId>
 5             <version>4.2.5.RELEASE</version>
 6         </dependency>
 7         <dependency>
 8             <groupId>org.springframework</groupId>
 9             <artifactId>spring-context</artifactId>
10             <version>4.2.5.RELEASE</version>
11         </dependency>
12         <dependency>
13             <groupId>org.springframework</groupId>
14             <artifactId>spring-jdbc</artifactId>
15             <version>4.2.5.RELEASE</version>
16         </dependency>
17         <!-- MySql -->
18         <dependency>
19             <groupId>mysql</groupId>
20             <artifactId>mysql-connector-java</artifactId>
21             <version>5.1.39</version>
22         </dependency>
23         <dependency>
24             <groupId>com.mchange</groupId>
25             <artifactId>c3p0</artifactId>
26             <version>0.9.5.2</version>
27         </dependency>
28         <dependency>
29             <groupId>org.mybatis</groupId>
30             <artifactId>mybatis</artifactId>
31             <version>3.4.1</version>
32         </dependency>
33         <dependency>
34             <groupId>org.mybatis</groupId>
35             <artifactId>mybatis-spring</artifactId>
36             <version>1.3.0</version>
37         </dependency>

With regard to Spring's package reference, my reference here is only for reference, while other web and mvc packages are referenced by business. If you don't use Maven, do it yourself, or use other package management.

 

II. Spring Configuration

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 4 
 5     <bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
 6         <property name="driverClass" value="com.mysql.jdbc.Driver" />
 7         <property name="jdbcUrl" value="jdbc:mysql://xxx.xxx.xxx.xxx:3306/xxxdb" />
 8         <property name="user" value="lekko" />
 9         <property name="password" value="xxx" />
10         <property name="minPoolSize" value="2" />
11         <property name="maxPoolSize" value="100" />
12     </bean>
13 
14     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
15         <property name="mapperLocations" value="classpath:mapper/**/*Mapper.xml" />
16         <property name="dataSource" ref="myDataSource" />
17     </bean>
18  
19     <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
20         <property name="basePackage" value="lekko.code.**.dao" />
21     </bean>
22 
23 </beans>

The configuration here is critical.

myDataSource is an instance bean of ComboPooled DataSource type, which implements the function of database connection pool.

2. sqlSession Factory is a factory instance used by MyBatis to create queries. It includes a mapperLocations location and a dataSource database connection source.

- MaperLocations specifies the path MyBatis will search for, supporting Ant-style paths. Under the specified path, MyBatis will read the xml query and use it for subsequent dao mappings.

- The dataSource is the source database, which is directly in front of the connection pool.

3. MapperScanner Configurer is MyBatis's configurator for automatically creating database dao classes.

- basePackage specifies the package name to scan and supports Ant-style paths. Under the specified package name, MyBatis automatically discovers the dao interface under the corresponding package name through Spring, and provides implementation for the interface when queries are needed later.

The following figure is the general framework of MyBatis and can be used as a supplement to the above configuration:

    That is to say, MyBatis configures Mapper to compose database queries based on XML, and then maps the parameters involved in the queries and the returned results into Java objects (or metadata types). Finally, it is left to the database to execute and return.

3. dao interface
 1 package lekko.code.test.dao;
 2 
 3 import lekko.code.test.model.TestModel;
 4 import org.springframework.stereotype.Repository;
 5 
 6 /**
 7  * Test DAO
 8  */
 9 @Repository
10 public interface TestDao {
11 
12     TestModel getTest(String name);
13 
14     int addTest(String name);
15 
16 }

The above interface, which belongs to the package lekko.code.**.dao, is identified as the Dao that needs to be mapped.

The interface has only two methods, one is to query getTest and the other is to add Test. As for getTest, I have extracted an entity class TestModel as needed:

 1 package lekko.code.test.model;
 2 
 3 /**
 4  * Test data class
 5  */
 6 public class TestModel {
 7 
 8     private int id;
 9     private String name;
10 
11     public String getName() {
12         return name;
13     }
14     public void setName(String name) {
15         this.name = name;
16     }
17 
18     public int getId() {
19         return id;
20     }
21     public void setId(int id) {
22         this.id = id;
23     }
24 
25 }

 

Mapper Mapping

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 3 
 4 <mapper namespace="lekko.code.test.dao.TestDao">
 5 
 6     <select id="getTest" resultType="lekko.code.test.model.TestModel">
 7         select id, name from Test where name = #{name}
 8     </select>
 9 
10     <insert id="addTest">
11         insert into Test (name, createdTime) values (#{name}, now())
12     </insert>
13 
14 </mapper>

I will not explain the grammar in detail, Baidu will have it. All kinds of conditions, judgments and parameters are explained. I personally like this high degree of freedom, sql looks very comfortable configuration.

    

At this point, the general introduction of use has been completed. MyBatis is still quite good, I suggest you try it out when the business is right.

For reprinting, please indicate the original address: http://www.cnblogs.com/lekko/p/6367732.html 

Posted by saltious on Fri, 22 Mar 2019 15:00:53 -0700