Spring Boot MyBatis connects to the database

Source: Internet
Author: User

Spring Boot MyBatis connects to the database

Recently busy, did not have time to extract the integration of MyBatis out, in fact, mybatis official website in late November 2015 has released the SpringBoot integrated Release version, Github has code: https://github.com/mybatis/mybatis-spring-boot
I have explained how to connect to the database using JPA and JDBC. This article also provides a summary by referring to the official code.

To put it bluntly, SpringBoot uses org. apache. tomcat. jdbc. pool. DataSource by default.
Now there is a JDBC connection pool component named HikariCP, which is said to have a much higher performance than the commonly used c3p0, tomcat, bone, and vibur components.
I plan to change the DataSource in the project to HirakiDataSource. The procedure is simple:
First, specify cetcetype in the application. properties configuration file.

spring.datasource.type=com.zaxxer.hikari.HikariDataSource

Then add the Hikari dependency to pom.


      
   
    com.zaxxer
       HikariCP     
  

To put it bluntly, configure MyBatis in Spring Boot.
For integration of MyBatis in Spring Boot, you can use the annotation-based method or the xml file configuration method. We recommend that you use XML for actual use (XML is also officially recommended ).

The following describes how to use xml to implement queries. Next, we will briefly describe the annotation method. Finally, we will attach the PageHelper integration.

1. Add pom dependency through xml configuration file

      
   
    org.mybatis.spring.boot
       mybatis-spring-boot-starter    
   
    1.0.1-SNAPSHOT
   
  
2. Create the Mapper (not a class) interface and corresponding Mapper. xml file.

Define related methods. Note that the method name must be consistent with the id in the Mapper. xml file.
StudentMapper. java

Package org. springboot. sample. mapper; import java. util. list; import org. springboot. sample. entity. student;/*** StudentMapper, ing SQL statement interface, non-logical implementation ** @ author single Hongyu (365384722) * @ myblog http://blog.csdn.net/catoop/ * @ create January 20, 2016 */public interface StudentMapper {List
  
   
LikeName (String name); Student getById (int id); String getNameById (int id );}
  

StudentMapper. xml

<code class=" hljs xml"><!--{cke_protected}{C}%3C!%2D%2D%3Fxml%20version%3D%221.0%22%20encoding%3D%22UTF-8%22%3F%2D%2D%3E--><mapper namespace="org.springboot.sample.mapper.StudentMapper">    <!--{cke_protected}{C}%3C!%2D%2D%20type%E4%B8%BA%E5%AE%9E%E4%BD%93%E7%B1%BBStudent%EF%BC%8C%E5%8C%85%E5%90%8D%E5%B7%B2%E7%BB%8F%E9%85%8D%E7%BD%AE%EF%BC%8C%E5%8F%AF%E4%BB%A5%E7%9B%B4%E6%8E%A5%E5%86%99%E7%B1%BB%E5%90%8D%20%2D%2D%3E-->    <resultmap id="stuMap" type="Student">        <id property="id" column="id">        <result property="name" column="name">        <result property="sumScore" column="score_sum">        <result property="avgScore" column="score_avg">        <result property="age" column="age">    </result></result></result></result></id></resultmap>    <select id="getById" resultmap="stuMap" resulttype="Student">        SELECT *        FROM STUDENT        WHERE ID = #{id}    </select>    <select id="likeName" resultmap="stuMap" parametertype="string" resulttype="list">        SELECT *        FROM STUDENT        WHERE NAME LIKE CONCAT('%',#{name},'%')    </select>    <select id="getNameById" resulttype="string">        SELECT NAME        FROM STUDENT        WHERE ID = #{id}    </select></mapper> </code>
3. entity class
Package org. springboot. sample. entity; import java. io. serializable;/*** Student Entity ** @ author single Hongyu (365384722) * @ myblog http://blog.csdn.net/catoop/ * @ create January 12, 2016 */public class Student implements Serializable {private static final long serialVersionUID = 2120869894112984147L; private int id; private String name; private String sumScore; private String avgScore; private int age; // The get set method is omitted}
4. modify the application. properties configuration file.
mybatis.mapper-locations=classpath*:org/springboot/sample/mapper/sql/mysql/*Mapper.xmlmybatis.type-aliases-package=org.springboot.sample.entity
5. Test the call method in the Controller or Service.
    @Autowired    private StudentMapper stuMapper;    @RequestMapping("/likeName")    public List
  
    likeName(@RequestParam String name){        return stuMapper.likeName(name);    }
  
Ii. Annotation

View the code on the official git using the annotation method, the configuration is very simple, you need to learn more about the annotation. Which of the following methods is better for xml and annotation.

1. Add the @ MapperScan annotation to the startup class (my ).
@SpringBootApplication@MapperScan("sample.mybatis.mapper")public class SampleMybatisApplication implements CommandLineRunner {    @Autowired    private CityMapper cityMapper;    public static void main(String[] args) {        SpringApplication.run(SampleMybatisApplication.class, args);    }    @Override    public void run(String... args) throws Exception {        System.out.println(this.cityMapper.findByState("CA"));    }}
2. Define CRUD statements using Annotations on interfaces
package sample.mybatis.mapper;import org.apache.ibatis.annotations.Param;import org.apache.ibatis.annotations.Select;import sample.mybatis.domain.City;/** * @author Eddú Meléndez */public interface CityMapper {    @Select("SELECT * FROM CITY WHERE state = #{state}")    City findByState(@Param("state") String state);}

City is a common Java class.

3. Integrated paging plug-in

The integration of the page plug-in is not so much as an introduction to how to integrate a plug-in. MyBatis provides an interceptor interface. We can implement our own interceptor and load it into SqlSessionFactory as a plugin.
A developer on Github wrote a paging plug-in. I think it is quite convenient to use.
Github address: https://github.com/pagehelper/Mybatis-PageHelper

The following is a brief introduction:
First, Spring injects all classes implementing the Interceptor interface in MyBatis into SqlSessionFactory as plugin when injecting bean dependencies. In this case, it is easy to integrate a plugin. You only need to use @ Bean to create a PageHelper object.

1. Add pom dependency

      
   
    com.github.pagehelper
       pagehelper    
   
    4.1.0
   
  
2. Added MyBatisConfiguration. java.
Package org. springboot. sample. config; import java. util. properties; import org. slf4j. logger; import org. slf4j. loggerFactory; import org. springframework. context. annotation. bean; import org. springframework. context. annotation. configuration; import com. github. pagehelper. pageHelper;/*** MyBatis configuration ** @ author single redwoo (365384722) * @ myblog http://blog.csdn.net/catoop/ * @ create January 21, 2016 */@ Configurationpublic class MyBatisConfiguration {private static final Logger logger = LoggerFactory. getLogger (MyBatisConfiguration. class); @ Bean public PageHelper pageHelper () {logger.info ("register MyBatis PageHelper"); PageHelper pageHelper = new PageHelper (); Properties p = new Properties (); p. setProperty ("offsetAsPageNum", "true"); p. setProperty ("rowBoundsWithCount", "true"); p. setProperty ("reasonable", "true"); pageHelper. setProperties (p); return pageHelper ;}}
3. Paging query Test
    @RequestMapping("/likeName")    public List
  
    likeName(@RequestParam String name){        PageHelper.startPage(1, 1);        return stuMapper.likeName(name);    }
  

For more information about how to use parameters, see the PageHelper instruction (Github address above ).

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.