Spring Boot Practice Toss-Up (ii): Pointcut, a classic example of Spring MVC integrated MyBatis

Source: Internet
Author: User
Tags aop integer mysql database tomcat docker run docker toolbox

A person's life, usually to his own efforts, even if the copy of other people's life form, there are always some things, can not be copied. Do not need to worry about other people's life, live your life is the root. Understanding the life status of many people in the world, can learn from, learning, find the right model for themselves, just fine. --Mantiu water before the start ...

The theme of this chapter is the entry point, to find a spot we slowly unfold, gradually in-depth, did not come up on the reason for the new thing is: The past experience is equally important, it is because of the past experience, there will be newer and better ideas appear, new ideas to help us improve. The same contrasts make it more intuitive to see whether new solutions are faster, better, and which have obvious changes in the pros and cons. Simple does not mean easy, only hands-on practice, can really understand.

So, this chapter is to review how to use spring MVC to build a common Maven-based Web project, and eventually integrate MyBatis to display the data using the MySQL database, while MySQL, I use the Docker image installation, not using the direct installation method.

Windows
Using Boot2docker, download address, version: 1.8.0 (this version is the last version, the project will be migrated to Docker Toolbox, Toolbox I downloaded the latest 1.11.2 attempt, but is not able to start the virtual machine, temporarily regardless of, does not affect the use)

Linux
Direct installation Docker use, detailed visibility: Ubuntu 16.04 installation using Docker environment version

jdk:1.7.80//The first chapter forgot to write, follow-up unified Use this JDK version
tomcat:6.0.33//Because the parent project has 8.0.33 embedded version, the 7.0.x version of the boot-like check jar package will be error, or use 8.0.33 can also
mysql:5.5.45 
Spring mvc:4.2.6.release
mybatis:3.2.5
mybatis-spring:1.2.2
tomcat-jdbc:7.0.52
mysql-connector-java:5.1.39
Docker running MySQL
Docker pull mysql:5.5.45
Docker run-d-P 3306:3306 mysql:5.5.45-e mysql_root_password=123456
build a MAVEN project
Package Name: COM.HJF.BOOT.DEMO.BOOT_MYBATIS_MVC

New Pom.xml

    <packaging>war</packaging> <properties> <jdbc.driver.version>5.1.39</jdbc.driv Er.version> <tomcat-jdbc.version>7.0.52</tomcat-jdbc.version> <mybatis.version>3.2.5& 

    Lt;/mybatis.version> <mybatis-spring.version>1.2.2</mybatis-spring.version> </properties> <dependencies> <!--mybatis--<dependency> <groupid>org.mybat Is</groupid> <artifactId>mybatis</artifactId> <version>${mybatis.version}& Lt;/version> </dependency> <!--mybatis-spring---<dependency> & Lt;groupid>org.mybatis</groupid> <artifactId>mybatis-spring</artifactId> <
        Version>${mybatis-spring.version}</version> </dependency> <!--connection Pool-- <dependency>
            <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-jdbc</artifactId> <version>${tomcat-jdbc.version}</version> <scope>runtime</scope> </dependen
            cy> <!--JDBC Driver--<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${jdbc.driver.version}</v ersion> <scope>runtime</scope> </dependency> </dependencies> <b
            Uild> <pluginManagement> <plugins> <!--compiler plugin, set JDK version-- <plugin> <groupId>org.apache.maven.plugins</groupId> &LT;ARTIFACTID&G T;maven-compiler-plugin</artifactid> <version>3.5.1</version> <config Uration>
                    <source>${java.version}</source> <target>${java.version}</target>

            <showWarnings>true</showWarnings> </configuration> </plugin> <!--war Pack plugin, set the war package name without version number--<plugin> <groupid>org.apache.mav En.plugins</groupid> <artifactId>maven-war-plugin</artifactId> <versi On>2.6</version> <configuration> &LT;WARNAME&GT;MICKJOUST&LT;/WARNAME&G
                T </configuration> </plugin> </plugins> </pluginManagement> </bui Ld>
Change to Web project Add Web Support

First create a new WebApp folder under src/main/
Idea and then click File–>project Structure–>modules->boot-mybatis-mvc to add support for Web projects, as shown in figure:

Add Spring Context support

Added applicationcontext.xml and application.properties files under Src/main/resources, and added spring-mvc.xml MVC under web-inf/ Severlet configuration file

Applicationcontext.xml <!--use annotation auto-registration bean--> <context:component-scan base-package= " Com.hjf.boot.demo.boot_mybatis_mvc "> <context:exclude-filter type=" annotation "expression=" Org.springframew Ork.stereotype.Controller "/> <context:exclude-filter type=" annotation "expression=" org.springframework.web. Bind.annotation.ControllerAdvice "/> </context:component-scan> <!--<aop:aspectj-autoproxy Proxy-tar Get-class= "true"/>--> <!--configuration reads the Properties property file---<bean class= "org.springframework.beans.factory. Config. Propertyplaceholderconfigurer "> <property name=" fileencoding "value=" UTF-8 "/> <property name=
                "Ignoreunresolvableplaceholders" value= "true"/> <property name= "Locations" > <list> <value>classpath:/config/app.properties</value> </list> &LT;/PROPERTY&G
    T </bean> <!--pointsOpen Flag specific bean--<import resource= "Classpath:/spring/app-config.xml"/> <!--mybatis Configuration-< Bean id= "sqlsessionfactory" class= "Org.mybatis.spring.SqlSessionFactoryBean" > <property name= "DataSource" re f= "DataSource"/> <!--automatically scans the entity directory, eliminating the manual configuration in configuration.xml <property name= "typealiases Package "value=" Com.hjf.boot.demo.boot_mybatis_mvc.domain "/> <!--explicitly specify the Mapper file location--<propert Y name= "mapperlocations" value= "Classpath:/mybatis/*mapper.xml"/> </bean> <!--scan basepackage all defined as @M Apper interface--<bean class= "Org.mybatis.spring.mapper.MapperScannerConfigurer" > <property name= "base Package "value=" Com.hjf.boot.demo.boot_mybatis_mvc "/> <property name=" Annotationclass "value=" com.hjf.boot. Demo.boot_mybatis_mvc.dao.Mapper "/> </bean>//profile configuration more, omitted here ...
//application.properties jdbc.driver=com.mysql.jdbc.driver jdbc.url=jdbc:mysql://
Localhost:3306/test?useunicode=true&characterencoding=utf-8 jdbc.username=test jdbc.password=123456 jdbc.pool.maxidle=2 jdbc.pool.maxactive=5 
Spring-mvc.xml <!--AOP Dynamic Agent--<aop:aspectj-autoproxy proxy-target-class= "true"/> <mvc:annot Ation-driven> <mvc:message-converters register-defaults= "true" > <!--will Stringhttpmessagecon
                The default encoding for Verter is set to UTF-8---<bean class= "Org.springframework.http.converter.StringHttpMessageConverter" > <constructor-arg value= "UTF-8"/> </bean> <!--will Jackson2httpmessagec The default formatted output of Onverter is set to true--<bean class= "Org.springframework.http.converter.json.MappingJackson2HttpMessa Geconverter "> <property name=" Prettyprint "value=" true "/> </bean> < /mvc:message-converters> </mvc:annotation-driven> <!--velocity configuration-<bean id= "Velocitycon Fig "class=" Org.springframework.web.servlet.view.velocity.VelocityConfigurer "> <property name=" resourceload Erpath "Value="/web-inf/views/"/> <property name=" velocityproperties "> <props> <prop key=" in Put.encoding ">UTF-8</prop> <prop key=" output.encoding ">UTF-8</prop> &
    Lt;prop key= "ContentType" >text/html;charset=UTF-8</prop> </props> </property> </bean> <!--Velocity View Resolver--<bean id= "Velocityviewresolver" class= "Org.springframework.web.ser Vlet.view.velocity.VelocityLayoutViewResolver "> <property name=" contentType "value=" Text/html;charset=utf-8 "/> <property name=" prefix "value=" "/> <property name=" suffix "value=". VMs "/> &lt ;p roperty name= "order" value= "0"/> <property name= "Datetoolattribute" value= "Datetool"/> &LT;PR Operty name= "Numbertoolattribute" value= "Numbertool"/> <property name= "Requestcontextattribute" value= "RC" /> <propertY name= "exposerequestattributes" value= "true"/> <property name= "Exposespringmacrohelpers" value= "true"/&gt
        ; <!--<property name= "Layouturl" value= "/PAGE/INDEX.VM"/>--> </bean> <!--container default Defaultservlet Handler, handles all static content and non-requestmapping processing url--> <mvc:default-servlet-handler/> <!--static resource configuration--& Lt;mvc:resources location= "/static/" mapping= "/static/**" cache-period= "864000"/> <!--beans---<bea n id= "Logininterceptor" class= "Com.hjf.boot.demo.boot_mybatis_mvc.interceptor.LoginInterceptor"/> <!--Interceptor Configuration
            -<mvc:interceptors> <mvc:interceptor> <mvc:mapping path= "/**"/> <mvc:exclude-mapping path= "/favicon.ico"/> <mvc:exclude-mapping path= "/web-inf/views/error/**"/&
            Gt <ref bean= "Logininterceptor"/> </mvc:interceptor> </mvc:interceptors>

Also click File–>project STRUCTURE–>MODULES->BOOT-MYBATIS-MVC to add spring support, as shown in figure:

After the spring support is added, the velocity configuration is used, there is no explanation, and the following is specifically stated in the single page application. The focus of this article is also the configuration of Spring MVC and MyBatis. Create a static folder

Create a static folder under src/main/webapp/web-inf/, copy the bootstrap and jquery folders (This chapter simply imports the static folder, demonstrates the configuration of the static path, Follow-up to the static file configuration and view layer parsing specifically to do the boot comparison) test model

public class Info {

    private Long ID;
    private String name;
    Private Integer age;

    Omit get, set method
}
Custom Annotations @mapper

@Mapper This note starts with the 3.4.0 of MyBatis, but in the previous version, if we were to use annotations to inject the MyBatis interface, would you like to customize each mapper in the config file, to customize an annotation and manually inject it into the MyBatis:

@Retention (retentionpolicy.runtime)
@Target (elementtype.type)
@Documented
@Component
Public @interface Mapper {
    String value () default "";
}
MyBatis DAO
@Mapper Public
interface Showdao {

    list<info> findbyage (Integer age);
}
XML Mapper

Create a new Mybatis/showdaomapper.xml file under src/main/resources/using XML

<!--namespace must point to DAO interface--
<mapper namespace= "Com.hjf.boot.demo.boot_mybatis_mvc.dao.ShowDao" >

    <select id= "findbyage" parametertype= "int" resulttype= "Info" >
        SELECT
        ID,
        name, age from
        info
        WHERE age = #{age}
    </select>

</mapper >
inserting data using SQL

Use the following SQL statement to build the library in MySQL: Test, and then insert the testing data.

CREATE TABLE ' info ' (
' id '  bigint not null auto_increment,
' name '  varchar (255) NULL,
' age '  int NULL,
PRIMARY KEY (' id ')
);

INSERT into info (name,age) VALUES (' Mick ', ' a ');
INSERT into info (name,age) VALUES (' Mick1 ', ' a ');
INSERT into info (name,age) VALUES (' Mickjoust1 ', ' + ');
INSERT into info (name,age) VALUES (' Joust ', ' 22 ');
Start

View Homepage: http://localhost:8080
View database data: Http://localhost:8080/show Summary

This chapter has more space to configure, omit some of the code, detailed code can be viewed in the example. It is still a lot of trouble to configure Spring MVC today, various configurations, various associations, but the entry point is very necessary, after you have used spring boot to know the advantages and benefits of simplification. Key points in this chapter are: custom annotations (in fact, after MyBatis 3.4.0, do not need to write their own, the official has written a), Spring MVC servlet Configuration, Spring context configuration, Spring MVC maven dependency, Summary found to build a project, if not familiar with the words, or will spend a lot of time, even if there is ready, suggest that we do more hands, their own operation, will experience the taste. This chapter concludes, as to what the principle of architecture, I personally prefer to go deeper into the final discussion, the previous chapters will be actual combat, first action to say.

Example Address: BOOT-MYBATIS-MVC

Page 366 in chapter 2016

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.