Springboot Integrated mybatis (map file mode and annotation mode)

Source: Internet
Author: User

Springboot as a micro-service framework, to provide our developers with great convenience, faith is more than the principle of configuration, through the form of starter package for us to do a lot of default configuration, when the data persisted to the relational database, we generally preferred spring data Jpa,springboot provides us with a starter package that can be easily configured with very few parameters to meet our needs. But when we encounter more complex queries, multi-table associative queries, and dynamic SQL, MyBatis is better at this, and we can use SQL optimizations to improve query efficiency when using MyBatis. Springboot does not provide us with an integrated MyBatis starter package, so we need to integrate it ourselves. Keep a record of my integration process for further reference.

I am using STS, new Springboot project joined the web, MySQL, mybatis module, springboot version 2.0.1.

1, Pom.xml

<?xml version= "1.0" encoding= "UTF-8"? ><project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "http ://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation=" http://maven.apache.org/POM/4.0.0/http Maven.apache.org/xsd/maven-4.0.0.xsd "><modelVersion>4.0.0</modelVersion><groupId> Com.example</groupid><artifactid>springboot-mybatis</artifactid><version>0.0.1- snapshot</version><packaging>jar</packaging><name>springboot-mybatis</name>< Description>demo Project for Spring boot</description><parent><groupid> org.springframework.boot</groupid><artifactid>spring-boot-starter-parent</artifactid>< Version>2.1.0.build-snapshot</version><relativepath/> <!--lookup parent from repository to </parent><properties><project.build.sourceencoding>utf-8</project.build.sourceencoding ><project.reporting.outputencoding>utf-8</project.reporting.outputencoding><java.version>1.8</java.version></properties>< Dependencies><dependency><groupid>org.springframework.boot</groupid><artifactid> Spring-boot-starter-web</artifactid></dependency><dependency><groupid> org.mybatis.spring.boot</groupid><artifactid>mybatis-spring-boot-starter</artifactid>< version>1.3.2</version></dependency><dependency><groupid>mysql</groupid>< Artifactid>mysql-connector-java</artifactid><scope>runtime</scope></dependency> < !--Paging Plug-in <dependency> <groupId>com.github.pagehelper</groupId> <a Rtifactid>pagehelper-spring-boot-starter</artifactid> <version>1.2.5</version> < /dependency> <!--Alibaba Druid database connection pool-<dependency> <groupid>com.alibAba</groupid> <artifactId>druid-spring-boot-starter</artifactId> <version>1. 1.9</version> </dependency><dependency><groupid>org.springframework.boot</groupid ><artifactid>spring-boot-starter-test</artifactid><scope>test</scope></ Dependency></dependencies><build><plugins><plugin><groupid> org.springframework.boot</groupid><artifactid>spring-boot-maven-plugin</artifactid></ plugin></plugins></build><repositories><repository><id>spring-snapshots</ Id><name>spring snapshots</name><url>https://repo.spring.io/snapshot</url>< Snapshots><enabled>true</enabled></snapshots></repository><repository><id >spring-milestones</id><name>spring milestones</name><url>https://repo.spring.io/ Milestone</url><snapshots><enabled>false</enabled></snapshots></repository></repositories>< Pluginrepositories><pluginrepository><id>spring-snapshots</id><name>spring Snapshots </name><url>https://repo.spring.io/snapshot</url><snapshots><enabled>true</ enabled></snapshots></pluginrepository><pluginrepository><id>spring-milestones</ Id><name>spring milestones</name><url>https://repo.spring.io/milestone</url>< snapshots><enabled>false</enabled></snapshots></pluginrepository></ Pluginrepositories></project>

2. Entity class Userdomain.java

Package Com.example.demo.model;public class UserDomain {    private Integer userId;    Private String userName;    private String password;    Private String phone;        Get and Set Methods}

3. Persistent interface

Package Com.example.demo.dao;import Java.util.list;import Com.example.demo.model.userdomain;public interface Userdao {    int insert (UserDomain record);    List<userdomain> selectusers ();}

4, build the table statement, note the database IP and name

CREATE TABLE t_user (  user_id INT not null PRIMARY KEY auto_increment,  user_name VARCHAR (255) is not NULL,  PASSWO RD varchar (255) NOT NULL,  phone varchar (255) is not null) Engine=innodb auto_increment=1000 DEFAULT Charset=utf8;

5. Service Layer

Package Com.example.demo.service;import Com.example.demo.model.userdomain;import Com.github.pagehelper.PageInfo;    public interface UserService {int addUser (userdomain user); pageinfo<userdomain> findalluser (int pagenum, int pageSize);} Package Com.example.demo.service.impl;import Java.util.list;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.service;import Com.example.demo.dao.userdao;import Com.example.demo.model.userdomain;import Com.example.demo.service.userservice;import Com.github.pagehelper.pagehelper;import Com.github.pagehelper.PageInfo; @Service (value = "UserService") public class Userserviceimpl implements UserService {@A    utowired private Userdao Userdao;    @Override public int AddUser (UserDomain user) {return userdao.insert (user); }//Paging query @Override public pageinfo<userdomain> findalluser (int pagenum, int pageSize) {PAGEHELPER.S        Tartpage (Pagenum, pageSize); List<userdomain> userdomains = Userdao.selectusers ();        PageInfo result = new PageInfo (userdomains);    return result; }}

6, Control layer

Package Com.example.demo.controller;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.controller;import Org.springframework.web.bind.annotation.getmapping;import Org.springframework.web.bind.annotation.postmapping;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.requestparam;import Org.springframework.web.bind.annotation.responsebody;import Com.example.demo.model.userdomain;import Com.example.demo.service.UserService; @Controller @requestmapping (value = "/user") public class Usercontroller {@    autowired private UserService UserService;    @ResponseBody @PostMapping ("/add") public int addUser (UserDomain user) {return userservice.adduser (user); } @ResponseBody @GetMapping ("/all") public Object Findalluser (@RequestParam (name = "Pagenum", Requir ed = false, DefaultValue = "1") int pagenum, @RequestParam (name = "PagEsize ", required = false, DefaultValue =" ten ") int pageSize) {return Userservice.findalluser (pag    Enum,pagesize); }}

7, Application.yml

Server:port:8080spring:datasource:name:mysql_test Type:com.alibaba.druid.pool.DruidDataSource #druid相关配置 Druid: #监控统计拦截的filters filters:stat Driver-class-name:com.mysql.jdbc.dri Ver #基本属性 Url:jdbc:mysql://127.0.0.1:3306/test?useunicode=true&characterencoding=utf-8&allowmul Tiqueries=true username:root password:root #配置初始化大小/min/MAX initial-size:1 m          In-idle:1 max-active:20 #获取连接等待超时时间 max-wait:60000 #间隔多久进行一次检测 to detect idle connections that need to be closed          time-between-eviction-runs-millis:60000 #一个连接在池中最小生存的时间 min-evictable-idle-time-millis:300000 Validation-query:select ' x ' test-while-idle:true test-on-borrow:false test-on-return:fals e #打开PSCache and specify the size of the Pscache on each connection. Set the Oracle setting to True,mysql to false. The list of sub-Libraries is more recommended set to False Pool-prepared-statements:false Max-pool-prePared-statement-per-connection-size:20mybatis:mapper-locations:classpath:mapper/*.xml Type-aliases-package:    Com.example.demo.model#pagehelperpagehelper:helperdialect:mysql reasonable:true Supportmethodsarguments:true Params:count=countsql Returnpageinfo:check

8, Usermapper.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= "Com.example.demo.dao.UserDao" > <sql id= "base_table" > T_user </sql> <sql id= "BAS E_column "> Userid,username,password,phone </sql> <insert id=" Insert "parametertype=" Com.example.demo.model.UserDomain "> INSERT into <include refid=" base_table "/> <trim prefix=" ("Suff     ix= ")" suffixoverrides= "," > Username,password, <if test= "Phone! = NULL" > Phone, </if> </trim> <trim prefix= "VALUES (" suffix= ")" suffixoverrides= "," > #{username, Jdbctype=varchar},#{pas Sword, Jdbctype=varchar}, <if test= "Phone! = null" > #{phone, Jdbctype=varchar}, </if> <        /trim> </insert> <select id= "selectusers" resulttype= "Com.example.demo.model.UserDomain" > select<include refid= "Base_column"/> from <include refid= "base_table"/> </select></mapper> 

9. The project directory structure is as follows

Add @mapperscan ("Com.example.demo.dao") annotations on the project startup class Springbootmybatisapplication so that the spring container can scan to the persisted interface and create the corresponding proxy class. Start a project, Access Localhost:8080/user/add, add users, and access Localhost:8080/user/all to see the results of a paged query.

Add: Compared with the map file mode, the annotation method will be more convenient, but the function is limited, using the annotation method only need to make the following changes

1, the persistent interface is modified as follows

Package Com.example.demo.dao;import Java.util.list;import Org.apache.ibatis.annotations.insert;import Org.apache.ibatis.annotations.mapper;import Org.apache.ibatis.annotations.param;import Org.apache.ibatis.annotations.select;import com.example.demo.model.UserDomain; @Mapperpublic interface Userdao {@ Insert ("INSERT into T_user (name, password, phone) VALUES (#{name}, #{password}, #{phone})" int insert (@Param ("name") String name, @Param ("password") string password, @Param ("phone") string phone), @Select ("SELECT * from T_user")    list& Lt Userdomain> selectusers ();}

2, delete the Usermappper.xml file, and start the @mapperscan on the class can be removed.

Springboot Integrated mybatis (map file mode and annotation mode)

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.