Implementing MVC projects based on Springboot + MyBatis

Source: Internet
Author: User

1. Preview:

(1) Complete project structure

(2) Create DATABASE, data table:

"User.sql"

SET foreign_key_checks=0;--------------------------------Table structure for user------------------------------ DROP TABLE IF EXISTS ' user '; CREATE TABLE ' user ' (  ' id ' int (one) ' NOT null,  ' name ' varchar (255) Default NULL,  ' age ' int (one) ' Default null,
   
     ' password ' varchar (255) Default NULL,  PRIMARY KEY (' id ')) engine=innodb default charset=latin1;------------------ --------------Records of user------------------------------INSERT into ' user ' VALUES (' 1 ', ' 7player ', ' 18 ', ' 123456 ');
   

2.Maven Configuration

The complete "pom.xml" configuration is as follows:

<?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> Cn.7player.framework</groupid> <artifactId>springboot-mybatis</artifactId> <version>1.0- snapshot</version> <parent> <groupId>org.springframework.boot</groupId> <artif Actid>spring-boot-starter-parent</artifactid> <version>1.2.5.RELEASE</version> </parent&    Gt <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> &LT;JAVA.V            Ersion>1.7</java.version> </properties> <dependencies> <!--Spring boot--> <!--support Web app development, including Tomcat and SPRING-MVC. --> <dependency> <groupId>org.springframework.boot</groupId> <artifacti D>spring-boot-starter-web</artifactid> </dependency> <!--template engine--<dependency&            Gt <groupId>org.springframework.boot</groupId> <artifactid>spring-boot-starter-thymeleaf</art Ifactid> </dependency> <!--support access to databases using JDBC--<dependency> <groupi        D>org.springframework.boot</groupid> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!--add features for your production environment, such as performance metrics and monitoring. -<dependency> <groupId>org.springframework.boot</groupId> &LT;ARTIFAC Tid>spring-boot-starter-actuator</artifactid> </dependency> <!--mybatis--> <d Ependency> <groupId>org.mybatis</groupId>            <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> &lt ;/dependency> <dependency> <groupId>org.mybatis</groupId> <artifactid >mybatis</artifactId> <version>3.2.8</version> </dependency> <!--My sql/datasource--> <dependency> <groupId>org.apache.tomcat</groupId> &L t;artifactid>tomcat-jdbc</artifactid> </dependency> <dependency> <groupid        >mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>            <!--Json support--> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.43</version> </dependency&gt        ; <!--Swaggersupport--> <dependency> <groupId>com.mangofactory</groupId> <artifact Id>swagger-springmvc</artifactid> <version>0.9.5</version> </dependency> & lt;/dependencies> <build> <plugins> <plugin> <groupid>org.s            Pringframework.boot</groupid> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <repositories> <repository> & Lt;id>spring-milestone</id> <url>https://repo.spring.io/libs-release</url> </rep ository> </repositories> <pluginRepositories> <pluginRepository> <id>sp Ring-milestone</id> <url>https://repo.spring.io/libs-release</url> </pluginreposito Ry> </pluginrepOsitories></project> 
3. Main function

"Application.java" contains the main function, which can be started as a normal Java program.

In addition, the class contains the Datasource,sqlseesion configuration content associated with the database.

Note: The @MapperScan ("Cn.no7player.mapper") represents the mapping path of the MyBatis (package path)

Package Cn.no7player; import Org.apache.ibatis.session.sqlsessionfactory;import Org.apache.log4j.Logger; Import Org.mybatis.spring.sqlsessionfactorybean;import Org.mybatis.spring.annotation.mapperscan;import Org.springframework.boot.springapplication;import Org.springframework.boot.autoconfigure.enableautoconfiguration;import Org.springframework.boot.autoconfigure.springbootapplication;import Org.springframework.boot.context.properties.configurationproperties;import Org.springframework.context.annotation.bean;import Org.springframework.context.annotation.componentscan;import Org.springframework.core.io.support.pathmatchingresourcepatternresolver;import Org.springframework.jdbc.datasource.datasourcetransactionmanager;import Org.springframework.transaction.platformtransactionmanager; import javax.sql.datasource; @ Enableautoconfiguration@springbootapplication@componentscan@mapperscan ("Cn.no7player.mapper") public class    Application {private static Logger Logger = Logger.getlogger (Application.class);
    public static void Main (string[] args) {        springapplication.run (application.class, args);       logger.info ("============= springboot boot Success =============");    }
    DataSource configuration    @Bean    @ConfigurationProperties (prefix= "Spring.datasource") Public    DataSource DataSource () {        return new Org.apache.tomcat.jdbc.pool.DataSource ();    }    Provide sqlseesion    @Bean public    sqlsessionfactory Sqlsessionfactorybean () throws Exception {        Sqlsessionfactorybean Sqlsessionfactorybean = new Sqlsessionfactorybean ();        Sqlsessionfactorybean.setdatasource (DataSource ());        pathmatchingresourcepatternresolver resolver = new Pathmatchingresourcepatternresolver ();        Sqlsessionfactorybean.setmapperlocations (Resolver.getresources ("Classpath:/mybatis/*.xml"));         return Sqlsessionfactorybean.getobject ();    }    @Bean public    Platformtransactionmanager TransactionManager () {        return new Datasourcetransactionmanager (DataSource ());    }
}
4.Controller

Request Portal Controller section provides three interface samples: view template, json,restful style

(1) View template

Returns the result as a view file path. View related files are placed by default under path Resource/templates:

Package Cn.no7player.controller; Import Org.apache.log4j.logger;import Org.springframework.stereotype.controller;import Org.springframework.ui.model;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.RequestParam; @Controllerpublic class Hellocontroller {    private Logger Logger = Logger.getlogger (hellocontroller.class);    /* *   Http://localhost:8080/hello?name=cn.7player *    /@RequestMapping ("/hello") public    String Greeting (@RequestParam (value= "name", Required=false, defaultvalue= "World") String name, model model) {        Logger.info ("Hello");        Model.addattribute ("name", name);        return "Hello";    }    }

(2) Json

Returns JSON-formatted data, which is used for AJAX requests.

package cn.no7player.controller; import cn.no7player.model.user;import Cn.no7player.service.userservice;import Org.apache.log4j.logger;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.controller;import Org.springframework.web.bind.annotation.requestmapping;import org.springframework.web.bind.annotation.responsebody;  @Controllerpublic class Usercontroller {  private Logger Logger = Logger.getlogger (usercontroller.class);  @Autowired private UserService userservice; /  * * Http://localhost:8080/getUserInfo */  @RequestMapping ("/getuserinfo")         @ResponseBody  Public User GetUserInfo () {User user = Userservice.getuserinfo ();            if (user!=null) {System.out.println ("User.getname ():" +user.getname ());        Logger.info ("User.getage ():" +user.getage ());    } return user; }}

(3) RESTful

REST refers to a set of schema constraints and principles. Applications or designs that meet these constraints and principles are RESTful.

In addition, there is a restful interface document online automatic generation + functional testing function software--swagger UI, the specific configuration process can step to "Spring Boot use Swagger to achieve restful testing"

Package Cn.no7player.controller; import Cn.no7player.model.user;import Com.wordnik.swagger.annotations.apioperation;import Org.springframework.web.bind.annotation.pathvariable;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.requestmethod;import Org.springframework.web.bind.annotation.restcontroller; import Java.util.arraylist;import java.util.List;   @RestController @requestmapping (value= "/users") public class Swaggercontroller {/* * http://localhost:808 0/swagger/index.html */  @ApiOperation (value= "Get All Users", notes= "requires noting") @RequestMapping (Metho d=requestmethod.get) public list<user> getusers () {list<user> list=new arraylist<user> (); &nbsp        ;        User User=new user ();        User.setname ("Hello");        List.add (user);  user user2=new User ();        User.setname ("World");        List.add (User2);    return list; }  @ApiOPeration (value= "Get user with id", notes= "requires the ID of user") @RequestMapping (value= "/{name}", Method=requestmetho        d.get) Public user Getuserbyid (@PathVariable String name) {User user=new user ();        User.setname ("Hello World");    return user; }}
5.Mybatis

The configuration-related code is reflected in the Application.java.

(1) "Application.properties"

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useunicode=true&characterencoding=gbk& zerodatetimebehavior=converttonullspring.datasource.username=rootspring.datasource.password= 123456spring.datasource.driver-class-name=com.mysql.jdbc.driver

Note that in the Application.java code, the annotations when configuring DataSource

@ConfigurationProperties (prefix= "Spring.datasource")

Indicates that the correlation property value will be matched from application.properties based on the prefix "Spring.datasource".

(2) "Usermapper.xml"

The SQL mapping file for MyBatis. MyBatis also supports annotation methods, which are not examples here.

<?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= "Cn.no7player.mapper.UserMapper" >   <select id= "Finduserinfo" resulttype= " Cn.no7player.model.User ">    select Name, Age,password from User;  </select> </mapper>

(3) interface Usermapper

Package cn.no7player.mapper; Import Cn.no7player.model.User; Public interface Usermapper {public    User finduserinfo ();}
Iii. Summary

(1) Running Application.java

(2) Console output:

.... (Skip over countless content)

Implementing MVC projects based on Springboot + MyBatis

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.