Spring Boot MyBatis Connection Database

Source: Internet
Author: User

Recently busy, did not have time to draw the MyBatis integration issued, in fact, MyBatis official website at the end of November 2015 has released the release version of Springboot integration, GitHub has code: https://github.com/ Mybatis/mybatis-spring-boot
Before facing the JPA and JDBC Connection database, this article is also a reference to the official code to make a summary.

Let's say a digression, springboot default use Org.apache.tomcat.jdbc.pool.DataSource
Now there is a JDBC Connection pool component called HIKARICP, which is said to have a much higher performance than the commonly used c3p0, Tomcat, Bone, Vibur.
I'm going to change the DataSource in the project to Hirakidatasource, which is simple:
First specify the DatasourceType in the application.properties configuration file

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

Then add the Hikari dependency in the Pom

<dependency>    <groupId>com.zaxxer</groupId>    <artifactId>HikariCP</artifactId>    <!-- 版本号可以不用指定,Spring Boot会选用合适的版本 --></dependency>

To the bottom, here's how to configure MyBatis in spring boot.
For the integration of MyBatis in spring boot, you can choose the annotation-based approach or the way the XML file is configured. It is also recommended to use XML in the actual use of the two (XML is also recommended by the authorities).

The following will introduce the way to implement the query through XML, followed by a brief comment on the way, and finally the integration of the paging plug-in (Pagehelper).

One, through the XML configuration file Mode 1, add pom dependency
<dependency>    <groupId>org.mybatis.spring.boot</groupId>    <artifactId>mybatis-spring-boot-starter</artifactId>    <version>1.0.1-SNAPSHOT</version></dependency>
2. Create Interface mapper (not Class) and corresponding Mapper.xml file

Define the method, and note that the method name is identical to the ID in the Mapper.xml file, which automatically corresponds to the
Studentmapper.java

package org.springboot.sample.mapper;import java.util.List;import org.springboot.sample.entity.Student;/** * StudentMapper,映射SQL语句的接口,无逻辑实现 * * @author 单红宇(365384722) * @myblog http://blog.csdn.net/catoop/ * @create 2016年1月20日 */publicinterface StudentMapper {    List<Student> likeName(String name);    Student getById(int id);    String getNameById(int id);}

Studentmapper.xml

<?xml version= "1.0" encoding= "UTF-8"?><! DOCTYPE Mapper Public "-//mybatis.org//dtd mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd" ><mapper namespace="Org.springboot.sample.mapper.StudentMapper">    <!--type is the entity class student, the package name is already configured, you can write the class name directly --    <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 ' />    </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 is like CONCAT ('% ', #{name}, '% ')</Select>    <select id="Getnamebyid" resulttype="string">SELECT NAME from STUDENT WHERE ID = #{id}</Select></mapper> 
3. Entity class
 Packageorg.springboot.sample.entity;Importjava.io.Serializable;/** * Student Entity * * @author Tan Hongyu (365384722) * @myblog http://blog.csdn.net/catoop/* @create /c15> January 12, 2016 * / Public  class Student implements Serializable{    Private Static Final LongSerialversionuid =2120869894112984147LPrivate intIdPrivateString name;PrivateString Sumscore;PrivateString Avgscore;Private intAge//Get Set method 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. Call method Test in controller or service
    @Autowired    private StudentMapper stuMapper;    @RequestMapping("/likeName")    publiclikeName(@RequestParam String name){        return stuMapper.likeName(name);    }
Second, the use of annotated way

View the official Git code using annotations, the configuration is very simple, the use of the annotations to do more understanding. As for both XML and annotations, the best way to do this is for tune to look at everyone.

1. Add @mapperscan annotations to the startup class (my)
@SpringBootApplication@MapperScan("Sample.mybatis.mapper") Public  class samplemybatisapplication implements Commandlinerunner {    @Autowired    PrivateCitymapper Citymapper; Public Static void Main(string[] args)    {Springapplication.run (samplemybatisapplication.class, args); }@Override     Public void Run(String ... args)throwsException {System.out.println ( This. Citymapper.findbystate ("CA")); }}
2. Use annotations to define CRUD statements on the interface
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 */publicinterface CityMapper {    @Select("SELECT * FROM CITY WHERE state = #{state}")    City findByState(@Param("state") String state);}

Where city is a common Java class.
Note about MyBatis, an article is very clear, you can refer to: http://blog.csdn.net/luanlouis/article/details/35780175

Three, set component page plug-in

Instead of integrating a paging plug-in, it's more about how to integrate a plugin. MyBatis provides an interceptor interface that allows us to implement our own interceptors and load them into sqlsessionfactory as a plugin.
There's a developer on GitHub who wrote a paging plugin, which I think can be very handy to use.
GitHub Project Address: Https://github.com/pagehelper/Mybatis-PageHelper

The following is a brief introduction:
The first thing to say is that spring will inject all the classes that implement the Interceptor interface in MyBatis into sqlsessionfactory as a plugin when it relies on the injected bean. That being the case, it's easy to integrate a plugin, just use @bean to create Pagehelper objects.

1. Add Pom Dependency
<dependency>    <groupId>com.github.pagehelper</groupId>    <artifactId>pagehelper</artifactId>    <version>4.1.0</version></dependency>
2. New Mybatisconfiguration.java
 PackageOrg.springboot.sample.config;ImportJava.util.Properties;ImportOrg.slf4j.Logger;ImportOrg.slf4j.LoggerFactory;ImportOrg.springframework.context.annotation.Bean;ImportOrg.springframework.context.annotation.Configuration;ImportCom.github.pagehelper.PageHelper;/** * MyBatis configuration * * @author Tan Hongyu (365384722) * @myblog http://blog.csdn.net/catoop/* @create  January 21, 2016 * /@Configuration Public  class mybatisconfiguration {    Private Static FinalLogger Logger = Loggerfactory.getlogger (Mybatisconfiguration.class);@Bean     PublicPagehelperPagehelper() {Logger.info ("Register MyBatis page plug-in Pagehelper"); Pagehelper Pagehelper =NewPagehelper (); Properties p =NewProperties (); P.setproperty ("Offsetaspagenum","true"); P.setproperty ("Rowboundswithcount","true"); P.setproperty ("reasonable","true"); Pagehelper.setproperties (P);returnPagehelper; }}
3, paged query test
    @RequestMapping("/likeName")    publiclikeName(@RequestParam String name){        PageHelper.startPage(11);        return stuMapper.likeName(name);    }

For more information on how to use the parameters, see the Pagehelper documentation (GitHub address above).

Spring Boot MyBatis Connection Database

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.