Implement SPRINGMVC Web Project "original" based on Springboot + MyBatis

Source: Internet
Author: User
Tags aop bind json xmlns tomcat log4j
Implement SPRINGMVC Web Project "original" based on Springboot + MyBatisTable 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 Appendix 5: 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. Almost all well-structured software (projects) use a layered design. Layered design is to divide the project into several cohesive parts according to the technical function, thus hiding the implementation details of the technology or interface.

From another point of view, structural layering often also facilitates the division of labor, allowing developers to focus on the implementation of a layer of business and functionality, such as front-end engineers only care about the page display and interactive effects (such as focus on HTML,JS, etc.), The backend engineer only cares about the processing of data and business logic (focusing on java,mysql, etc.). Communication between the two is through a standard interface (protocol).

We use some frameworks, such as SPRINGMVC, in the process of implementing hierarchies. However, the use of the framework poses a number of usage issues. What we often do is to configure various XML files, and then we need to build the configuration tomcat or jetty as a container to run the project. Every time you build a new project, you have to go through this process. Even more unfortunate is that sometimes the front-end personnel need to configure these environments to be able to debug or test the program locally, or require the backend to implement some service functions first. This is in conflict 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 a project into a complete solution. In fact, a well-integrated project framework not only enables separation of technology and business, but also focuses on and satisfies the "isolation" of developers.

To solve such problems, a new framework for spring boot is created. Spring boot is designed to simplify the building and development of spring applications. The framework is dedicated to the implementation of XML-free configuration, providing a convenient, independent operating environment for "One-click operation" to meet the needs of rapid application development.

At the same time, a complete Web application inevitably has database support. Using the JDBC API requires writing complex, repetitive, and redundant code. The use of 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 hybrid solution--mybatis was born. MyBatis is a persistent layer framework that draws a lot of good ideas from a variety of 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 JDBC code and manually sets parameters and gets the result set. MyBatis can use simple XML or annotations for configuration and native maps to map interfaces and Java POJOs (Plain old Java Objects, ordinary Java objects) to records in a database.

Finally, back to the technical structure stratification, the current mainstream advocated the design pattern is MVC, namely Model-view (the controller). There are many frameworks for implementing this design pattern, such as struts. The Springmvc mentioned earlier 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 layering, differentiated responsibilities, and simplified web development from the engineering structure.

At present, there is no relevant best practice for how to integrate these technologies into a complete solution. Less data and cases are used to integrate spring boot and mybatis. Therefore, this article provides (introduction) a 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, enabling developers to expand according to different needs and business.

Supplemental hints, Spring Boot recommends a Java annotation-based configuration instead of traditional XML. You only need to add "@EnableAutoConfiguration" annotations on the master configuration Java class to enable automatic configuration. Spring Boot's Auto-configuration feature is not intrusive, just as a basic default implementation. Developers can override the functionality provided by the automatic configuration by defining other beans, such as when configuring this case data source (DataSource).

Second, practice

Some notes:

The Project IDE uses IntelliJ (the main reason is that IntelliJ Yan value end of Eclipse, who called it a look at the face of the era)

Project-dependent management employs a familiar Maven (in fact springboot and groovy is a natural pair) 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 (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); //datasource configuration @Bean @ConfigurationProperties (prefix= "Spring.datasource") pu    Blic DataSource DataSource () {return 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

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:

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 (the @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.

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

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

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

Public interface Usermapper {    
Public User finduserinfo ();
}

Iii. Summary

(1) Running Application.java

(2) Console output:

.... (Skip over countless content)

(3) Visit:

Access to three controllers is:

View:

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

Json:

Http://localhost:8080/getUserInfo

Restful (using swagger):

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

Iv. See

"Spring Boot–quick Start"

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

"MyBatis"

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

Quick Build Spring Framework app with spring Boot

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/

The understanding of the restful architecture

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

Appendix:

Spring Boot recommended base POM file

Name

Description

Spring-boot-starter

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

Spring-boot-starter-amqp

Support AMQP via 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.