Spring integrates the MyBatis framework and springmybatis framework.

Source: Internet
Author: User
Tags most popular database

Spring integrates the MyBatis framework and springmybatis framework.

When writing database queries in Java, I used four methods:

1. pure Java code, Reference the corresponding database driver package, write the connection and release logic by yourself (you can use the connection pool)

In fact, the performance of this mode is very good, but it is not very convenient to use: first, to manually obtain and release the Connection, a large amount of redundant code is also prone to errors; the other is, complex SQL statements cannot be written as strings (line breaks, visual lengths, and parameters are all problems ).

2. Use Spring JdbcTemplate

This is actually quite good, the configuration is relatively simple, the function is richer than the manual management of Connection is much more comfortable, and the code is also relatively simple. The prominent problem is that SQL maintenance is quite troublesome.

3. Use the Hibernate framework

In a word, the configuration is very troublesome, and it is quite good to use. However, there is a fatal defect that does not help you complete multi-table queries like a single table query. If you have complex multi-table queries or query conditions, you still need to use SQL queries. This is a disaster for businesses with complicated business logic or frequently changed business logic, change to crying (because it is really messy, you must plan it first ).

4. Use the MyBatis framework

This is the most popular database persistence framework for my projects. Through XML configuration, it can easily and intuitively help you complete comprehensive queries for various conditions, judgments, and multiple tables, the implementation method is much more comfortable than the Java code spelling SQL, and it is even more comfortable with Hibernate. In fact, usability is quite easy to use, but the configuration also needs to map some data, but it is relatively more flexible. Its entity class is not necessarily a database physical table, but can be any queried dataset (similar to the data transmission object DTO ).

Summary:

Ease of configuration: 1> 2> 4> 3

Ease of use: 2> 3> 4> 1

Query flexibility: 4> 1 = 2> 3

The following describes how to configure and use Spring to integrate MyBatis. The project is built based on Maven to connect to the Mysql database:

 

1. 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>

For Spring package reference, the reference here is only for reference. Other web and mvc packages are referenced according to various services. If you don't need Maven, just introduce the jar package, or use other packages for 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.

1. myDataSource is a ComboPooledDataSource instance bean that implements the database connection pool function.

2. sqlSessionFactory is a factory instance used by MyBatis to create a query. It includes a mapperLocations location and a dataSource Database Connection source.

-MapperLocations specifies the path to be searched by MyBatis. SupportedAnt style path. In the specified path, MyBatis queries the xml in the path and uses it for subsequent dao ing.

-DataSource is the source database, which is the connection pool above.

3. mapperScannerConfigurer is the configuration tool for MyBatis to automatically create the database dao class.

-BasePackage specifies the name of the package to be scanned. SupportedAnt style path. Under the specified package name, MyBatis uses Spring to automatically find the dao interface under the corresponding package name. It is implemented for the interface when it needs to be queried later.

Is the general framework of MyBatis and can be used as a supplement to the above Configuration:

That is to say, MyBatis configures Mapper Based on XML to form a database query, and maps the parameters and returned results involved in the query to a Java object (or metadata type ). It is finally submitted to the database for execution and returned.

Iii. 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 @ Repository10 public interface TestDao {11 12 TestModel getTest (String name); 13 14 int addTest (String name ); 15 16}

The preceding interface is identified as the dao to be mapped because it belongs to the lekko. code. **. dao package.

The interface has only two methods: getTest and addTest. As for getTest, I have extracted the object 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}

 

Iv. Mapper ing

 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 syntax in detail. Baidu will have it at a moment. Various conditions, judgments, and parameters are explained. I personally like this kind of high degree of freedom, and SQL looks very comfortable to configure.

So far, the general introduction has been completed. MyBatis is quite good. We suggest you try it out when your business is right.

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.