Springboot and MyBatis Simple integration

Source: Internet
Author: User

Prior to the traditional SSM framework, a lot of configuration files, a few days to see the document to the logic of the XML 7788, it is very troublesome to set up, then I completely press the online demo version requirements (JDK and Tomcat), so the end is a variety of problems did not run up successfully. Today try to use Springboot to integrate, can't believe to fail a few times on success!!

Now to record the process:

First of all, Springboot Basic establishment is not said, before the blog has written.

To Add a pom dependency :

    <Dependency>              <groupId>Org.springframework.boot</groupId>              <Artifactid>Spring-boot-starter-thymeleaf</Artifactid>      </Dependency>             <Dependency>              <groupId>Mysql</groupId>              <Artifactid>Mysql-connector-java</Artifactid>      </Dependency>              <Dependency>              <groupId>Org.mybatis.spring.boot</groupId>              <Artifactid>Mybatis-spring-boot-starter</Artifactid>              <version>1.3.0</version>      </Dependency>  

The dependency on the DAO layer is the starter of the two MySQL connector and MyBatis (this is a good thing).

Start writing code :

Here we have a simple data sheet:

Our goal is to send a request with an ID value with GET, and the server returns all the librarian's information based on the ID value and displays it directly on the page in JSON form.

Controller:

  @RestController  public  class   Librariancontroller {@Autowired  private   Librarianservice Librarianservice; @GetMapping ( "/getlibrarian"  public  Librarian Getalibrarianinfo (int   ID) {// system.out.println ("Test:id:" +id);  return      Librarianservice.selectlibrarian (ID); }}

Restcontroller is a combination of the Responsebody+controller two annotations, which are generally transmitted directly to JSON data. Why is it possible to pass an object directly past? This is because the Springboot built-in Jackson module, can be seen in Maven's dependency on this area of the jar package (previously I wrote by the online tutorial with Gson to deal with, compared to this is absolutely invincible)

And then see the sevice we injected, here's the service

Service:

 Public Interface Librarianservice {    librarian Selectlibrarian (int  ID);}

It's an interface.

Serviceimpl:

@Service  Public class Implements librarianservice{        @Autowired    private  librarianmapper librarianmapper;        @Override    Public librarian Selectlibrarian (int  ID) {        //  TODO auto-generated Method stub        return Librarianmapper.selectlibrarian (ID);}    }

Remember to add @service notes here before the bean is generated by spring and injected into the controller.

And I saw a mapper here.

Dao:

 Package Com.example.dao; Import Org.apache.ibatis.annotations.Mapper; Import Com.example.entity.Librarian; @Mapper  Public Interface Librarianmapper {    librarian Selectlibrarian (int  ID);}

The @mapper in Riga is a mybatis note to allow spring to dynamically generate an implementation of this interface based on XML and this interface. If you add @repository, Spring generates a bean that is automatically injected into the service's relevant reference.

And then the mapper XML file (my MyBatis's related SQL is XML)

mapper.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 "><Mappernamespace= "Com.example.dao.LibrarianMapper">    <!--depending on your needs, whether you want to use -    <Resultmaptype= "Librarian"ID= "Librarianmap">        <IDcolumn= "id" Property= "id"Jdbctype= "INTEGER" />        <resultcolumn= "UserName" Property= "Usename"Jdbctype= "VARCHAR" />        <resultcolumn= "Password" Property= "Password"Jdbctype= "VARCHAR" />        <resultcolumn= "Age" Property= "Age"Jdbctype= "INTEGER" />        <resultcolumn= "position" Property= "position"Jdbctype= "VARCHAR" />            </Resultmap>            <SelectID= "Selectlibrarian"ParameterType= "INTEGER"Resultmap= "Librarianmap">SELECT * from T_librarian where 1=1 and id = #{id,jdbctype=integer}</Select>        </Mapper>

The third line of namespace is important. Oh, it's specifying which DAO (Mapper) interface this XML corresponds to

Resultmap is to do a pojo and database table corresponding (here only write a librarian do not write the full path is because the settings, the following will say)

The ID of the SELECT tag corresponds to the method name in the Mapper interface, and ParameterType is the type of parameter passed in.

simple configuration and Settings :

Ok now talk about settings, here will think, those controller ah, @Service ah and mybatis annotation @mapper what spring how to know where? Don't you want to do a scan setup like MVC?

Yes, these are the simple settings we made in the startup class:

 PackageCom.example.main;ImportOrg.mybatis.spring.annotation.MapperScan;Importorg.springframework.boot.SpringApplication;Importorg.springframework.boot.autoconfigure.SpringBootApplication;/*** Specifies the package to be swept, will automatically scan the specified package under the all labeled @component class, and registered as a bean, * of course, including @component sub-annotations @service, @Repository, @Controller. * @author85060 **/@SpringBootApplication (scanbasepackages={"Com.example.*"}) @MapperScan ("Com.example.dao") Public classspringbootdemoapplication { Public Static voidMain (string[] args) {Springapplication.run (springbootdemoapplication.class, args); }}

As for this springbootapplication, it is actually a combination of several annotations (previously spoken in the blog), so you can write the settings of the package directly here, and then the @mapperscan is the mybatis provided by the settings annotation.

Then there is a bit of configuration file:

 spring.thymeleaf.cache=false     spring.devtools.restart.enabled  =true    spring.devtools.restart.additional -paths=src/main/java Spring.datasource.driver -class -name= Com.mysql.jdbc.Driverspring.datasource.url  =jdbc:mysql:// localhost:3306/db_library  spring.datasource.username= Rootspring.datasource.password  =4008mybatis.type -aliases-package  =com.example.entitymybatis.mapperlocations  = Classpath:mappers/*  .xml  

The main concern is the beginning of line fourth, the last two lines is to set the basic package (package alias) is also why in Mapper.xml can write only one librarian reason.

The last line is important to tell the system where to find the Mapper.xml file.

Previous last:

Then put a project structure diagram:

Put two springboot and MyBatis to integrate the better blog for reference:

54929287 (if you see this it will save a lot of effort!) )

50776155

Springboot and MyBatis Simple integration

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.