Implementation of SPRINGMVC Web project "original" based on Springboot + MyBatis

Source: Internet
Author: User
implementation of SPRINGMVC Web project "original" based on Springboot + MyBatisCatalog 11, warm-up 22, practice 2.11. Preview: 2.22.Maven configuration 2.33. Main function 2.44.Controller 2.55.Mybatis 33, summary 44, see 5 Appendix: first, warm up

A realistic scenario is that when we develop a Web project, architects and development engineers may be more concerned with the design of the project's technical structure. And almost all well structured software (projects) use layered design. Layered design is to divide the project into several cohesive parts according to the technical function, so as to hide the implementation details of the technology or interface.

On the other hand, structural layering can also promote the division of labor among technicians, allowing developers to focus more on the implementation of a layer of business and functionality, such as a front-end engineer who cares only about the presentation and interaction of a page (for example, focusing on HTML,JS, etc.). The backend engineer is concerned only with the processing of data and business logic (focus on JAVA,MYSQL, etc.). The two communicate through a standard interface (protocol).

We use some frameworks, such as SPRINGMVC, in the process of implementing tiering. However, the use of the framework has brought some usage problems. What we often do is configure a variety of XML files, and then we need to build the configuration of Tomcat or jetty as a container to run the project. Every time you build a new project, you have to go through this process. It's even more unfortunate that sometimes the front-end people need to configure these environments to be able to debug or test the program locally, or they need a backend to implement some service functions first. This conflicts with the "good layered structure" just mentioned.

Each technology and framework has a certain learning curve. Developers need to know the specifics of how to integrate the project into a complete solution. In fact, a well integrated project framework not only enables the separation of technology and business, but also concerns and satisfies the "quarantine" of developers.

To address this type of problem, a new framework for spring boot is created. Spring boot is used to simplify the build and development process of spring applications. The framework is dedicated to the implementation of XML-free configuration, providing a convenient, independent operating environment, to achieve "one-click operation" to meet the needs of rapid application development.

At the same time, a complete Web application is inevitably the support of the database. Using JDBC's APIs requires writing complex, repetitive, and redundant code. Using O/RM (for example, hibernate) tools requires a number of assumptions and rules, such as the most common assumption that the database is properly regulated. These specifications are not perfectly achievable in real-world projects. Thus, a mixed solution--mybatis was born. MyBatis is a persistence-layer framework that draws a great deal of good ideas from various database access tools for any size and purpose database. According to the official documentation: MyBatis is an excellent persistence layer framework that supports custom SQL, stored procedures, and advanced mapping. MyBatis avoids almost all the JDBC code and manually sets the parameters and gets the result set. MyBatis can use simple XML or annotations for configuration and native maps, mapping interfaces and Java POJOs (Plain old Java Objects, normal Java objects) to records in the database.

Finally, back to the layered technology structure, the current mainstream design model is MVC, that is, model-view-Controller (Controller). There are many frameworks for implementing this design pattern, such as struts. The Springmvc mentioned above is another, more excellent, flexible and easy-to-use MVC framework. Springmvc is a java-based, request-driven lightweight web framework designed to decouple the Web layer by using a "request-response" model that enables good tiering from an engineering structure, differentiated responsibilities, and simplifies web development.

At present, there is no relevant best practice for how to integrate these technologies into a complete solution. Fewer data and cases are used to integrate spring boot and mybatis. Therefore, this article provides (introduces) a complete case of using springboot and MyBatis to frame a Web project. This case is based on the SPRINGMVC architecture to provide a complete and concise implementation of the demo, so that developers based on different needs and business expansion.

As a hint, Spring Boot recommends a Java annotation based configuration rather than traditional XML. You can enable automatic configuration only by adding "@EnableAutoConfiguration" annotations on the primary configuration Java class. The automatic configuration feature of Spring Boot is not intrusive, but as a basic default implementation. Developers can override the functionality provided by automatic configuration by defining other beans, such as when configuring this case data source (DataSource).

Second, the practice

Some notes:

The Project IDE uses IntelliJ (the main reason is that the IntelliJ color is worth exploding eclipse, who called it a face-seeing ERA)

Engineering Dependency Management adopt the personally familiar Maven (in fact springboot and groovy are the perfect couple) 1. Preview:

(1) GitHub address

Https://github.com/djmpink/springboot-mybatis

Git:https://github.com/djmpink/springboot-mybatis.git

(2) Complete project structure

(3) database

Database name: Test

"User.sql"

SET foreign_key_checks=0--------------------------------Table structure for user------------------------------ DROP TABLE IF EXISTS ' user '; CREATE TABLE ' user ' (  ' id ' int ') 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 "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--> <!--supports WEB application 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 that apply to the 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> ;/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, as normal Java programs start.

In addition, the class contains datasource,sqlseesion configuration content that is related to the database.

Note: The @MapperScan ("Cn.no7player.mapper") represents the MyBatis mapping path (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); //datasource configuration @Bean @ConfigurationProperties (prefix= "Spring.datasource") pu    Blic DataSource DataSource () {Return to New Org.apache.tomcat.jdbc.pool.DataSource (); } //Provide sqlseesion @Bean public sqlsessionfactory Sqlsessionfactorybean () throws Exception {  SQL        Sessionfactorybean Sqlsessionfactorybean = new Sqlsessionfactorybean (); Sqlsessionfactorybean.setdatasource (DataSource ());  pathmatchingresourcepatternresolver resolver = new PathMat Chingresourcepatternresolver ();  sqlsessionfactorybean.setmapperlocations (resolver.getResources ("Classpath    :/mybatis/*.xml "));  return Sqlsessionfactorybean.getobject (); }  @Bean public Platformtransactionmanager TransactionManager () {return new datasourcetransactionmanage    R (DataSource ()); } /** * Main Start/public static void Main (string[] args) {Springapplication.run (applicatio N. class, args);    Logger.info ("============= springboot Start Success ============="); } }
4.Controller

The controller section of the request portal provides three sample interfaces: View template, json,restful style

(1) View template

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

Import Org.apache.log4j.Logger;
Import Org.springframework.stereotype.Controller;
Import Org.springframework.ui.Model;
Import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public 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, used for AJAX requests.

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;
@Controller
public 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 architectural constraints and principles. The application or design that satisfies these constraints and principles is RESTful.

In addition, there is a restful interface of the document online automatically generated + functional testing software--swagger UI, the specific configuration process can be the next "Spring Boot using swagger implementation restful test"

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 Java.util.arraylist;import java.util.List;
@RestController
@RequestMapping (value= "/users")
public class Swaggercontroller {        
     * *  http://localhost:8080/swagger/index.html * *          
@ApiOperation (value= "Get All Users", notes= "requires noting")    
@RequestMapping (Method=requestmethod.get)    
Public list<user> getusers () {        
List<user> list=new arraylist<user> ();         
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=requestmethod.get)    
Public User Getuserbyid (@PathVariable String name) {        
User User=new user ();        
User.setname ("Hello World");        
return user;    
}}

5.Mybatis

Configuration related code is embodied 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 annotation when configuring datasource

@ConfigurationProperties (prefix= "Spring.datasource")

Indicates that the associated property value will be matched from application.properties according to the prefix "Spring.datasource".

(2) "Usermapper.xml"

MyBatis SQL Map file. MyBatis also supports the annotation method, which is not an example.

<?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

Public interface Usermapper {    
Public User finduserinfo ();
}

Third, summary

(1) Running Application.java

(2) Console output:

... (skip over countless content)

(3) Visit:

Access to three types of controllers are:

View:

Http://localhost:8080/hello?name=7player

Json:

Http://localhost:8080/getUserInfo

Restful (using swagger):

Http://localhost:8080/swagger/index.html

Four, see

"Spring Boot–quick Start"

http://projects.spring.io/spring-boot/#quick-start

"MyBatis"

http://mybatis.github.io/mybatis-3/

Using spring Boot to quickly build the Spring framework application

http://www.ibm.com/developerworks/cn/java/j-lo-spring-boot/

"Using @ConfigurationProperties in Spring Boot"

Http://www.javacodegeeks.com/2014/09/using-configurationproperties-in-spring-boot.html?utm_source=tuicool

"Springboot-mybatis-mysample"

Https://github.com/mizukyf/springboot-mybatis-mysample

"Serving Web Content with Spring MVC"

http://spring.io/guides/gs/serving-web-content/

Understanding of the RESTful architecture

Http://www.ruanyifeng.com/blog/2011/09/restful

Appendix:

The base POM file recommended by Spring Boot

Name

Description

Spring-boot-starter

Core POM, which includes automatic configuration support, log library, and support for YAML configuration files.

Spring-boot-starter-amqp

Support AMQP through Spring-rabbit.

Spring-boot-starter-aop

Includes SPRING-AOP and AspectJ to support facet-oriented programming (AOP).

Spring-boot-starter-batch

Supports Spring Batch, including HSQLDB.

Spring-boot-starter-data-jpa

Contains SPRING-DATA-JPA, Sprin

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.