My official account: MarkerHub, Java website: Markerhub.com

For more selected articles, please click: Java Notes Complete.md


Author: TyCoding

Link: www.jianshu.com/p/897b5943c…

Following on from the previous article: Setting up an environment for getting started with Spring-Boot. This time we integrate Springboot-Mybatis to achieve simple CRUD business.

Requirements:

  • Explain the construction of SpringBoot project and the difference between SSM project and SSM project in engineering construction.
  • Realize SpringBoot-Mybatis integration conquest database.
  • Solve the page jump, explain the difference with SSM stage.
  • Implement paging queries using the PaheHelper plug-in and the ElementUI paging control.
  • Upload files.
  • Use Spring AOP aspect programming to achieve a simple implementation of the login interception project.

Github repository: Teach you elegant introduction to the Spring Boot framework

If you like it, please click star in the upper right corner to encourage me.

Teach you elegant introduction to the Spring Boot framework

Technology stack

  • Backend: SpringBoot + Mybatis
  • Front end: vue.js + ElementUI

The test environment

  • The IDEA + SpringBoot – at 2.0.5

The project design

. ├ ─ ─ the db - SQL file ├ ─ ─ MVNW ├ ─ ─ MVNW. CMD ├ ─ ─ pom. The XML - project depend on └ ─ ─ the SRC ├ ─ ─ the main │ ├ ─ ─ Java │ │ └ ─ ─ cn │ │ └ ─ ─ tycoding │ │ ├ ─ ─ SpringbootApplication. Java -- -- Spring Boot startup class │ │ ├ ─ ─ the controller - the MVC - WEB layer │ │ ├ ─ ─ the entity - entity class │ │ ├ ─ ─ Interceptor - custom interceptors │ │ ├ ─ ─ mapper, mybatis mapper - layer interface │ │ └ ─ ─ service - service business layer │ └ ─ ─ resources - Spring Boot resource file │ ├ ─ ─ application. Yml - Spring Boot core configuration file │ ├ ─ ─ mapper, Mybatis mapper layer configuration file │ ├ ─ ─ the static - front static file │ └ ─ ─ Templates -- Thymeleaf HTML page directory, ├ ─ test -- Test filesCopy the code

To prepare

To start the Spring Boot project, first you need to build the Spring Boot project.

See my blog: Getting started with Spring Boot

Spring Boot applies the initiator

Spring Boot provides a number of application initiators, which are used to support different functions. Basically, it is the dependency configuration in THE POP.xml. Because of the automatic configuration feature of Spring Boot, we do not need to consider the dependency version of the project. It automatically imports all of our dependencies into the project.

Here are a few common application initiators:

  • spring-boot-starter: The core launcher for Spring Boot, including automatic configuration, logging, and YAML
  • spring-boot-starter-aop: Supports AOP’s aspect oriented programming features, including Spring-AOP and AspecJ
  • spring-boot-starter-cache: Supports Spring Cache abstraction
  • spring-boot-starter-artermis: Supports Java Message Service (JMS) APIS by Apache Artemis
  • spring-boot-starter-data-jpa: support for JPA
  • spring-boot-starter-data-solr: Support Apache Solr search platform, including Spring-data-solr
  • spring-boot-starter-freemarker: Supports the FreeMarker template engine
  • spring-boot-starter-jdbc: Supports JDBC databases
  • spring-boot-starter-Redis: Supports Redis key store databases, including Spring-Redis
  • spring-boot-starter-security: support spring ws-security
  • spring-boot-starter-thymeleaf: Supports the Thymeleaf template engine, including integration with Spring
  • spring-boot-starter-web: Support full stack Web development, including Tomcat and Spring-WebMVC
  • spring-boot-starter-log4j: Supports the Log4J logging framework
  • spring-boot-starter-logging: Introduces the default Spring Boot logging framework Logback

Spring Boot project structure design

The Spring Boot project, or Maven project, certainly has the most basic Maven project structure. In addition:

  1. The WebApp (Webroot) directory is not included in the Spring Boot project.

  2. Spring Boot provides static resource directories by default that must be placed in classpath and must be named according to certain rules.

  3. By default, Spring Boot does not recommend using XML configuration files. YML is recommended as the configuration file format, which has a more concise syntax. Properties can also be used as a configuration file format.

  4. Spring Boot officially recommends Thymeleaf as the front-end template engine, and Thymeleaf defaults to Templates as the directory for storing static pages (as specified by the configuration file).

  5. Spring Boot uses Resources as the default directory for storing static resources, including front-end static files and project configuration files.

  6. Spring Boot specifies that the name of the subdirectory under resources must comply with certain rules. Generally, we set resources/static as the front-end static (JS,CSS) directory. Set Resources /templates as the directory to store your HTML pages.

  7. Spring Boot specifies that the Thymeleaf template engine directory /resources/templates is a protected directory. Unlike the previous WEB-INF folder, static resources in the Thymeleaf template engine directory cannot be accessed directly.

  8. It is recommended that Mybatis-Mapper XML mapping file be placed in the resources/ directory, I set it as resources/ Mapper directory, and SRC /main/ Java /Mapper Mapper layer interface should be identified by @mapper annotation. Otherwise, Mybatis cannot find the XML mapping file corresponding to the interface.

  9. Starter class SpringBootApplication. Java for the project, project don’t need to be deployed in Tomcat, provided by SpringBoot server deployment project (running starter class); And SpringBoot automatically scans annotated beans at the sibling and child levels of the initiator.

  10. Spring Boot is not recommended to use JSP pages, if you want to use, please find your own solution.

  11. The resources/templates directory that Spring Boot provides for static HTML pages is a protected directory, and HTML pages are accessed through Controller mapping. This means that you need to configure the Spring view parser. And the Controller class cannot use the @restController identifier.

start

First of all: I want to emphasize that SpringBoot is not an enhancement to Spring functionality, but rather provides a quick way to use Spring. Keep that in mind.

Learning the SpringBoot framework, just for easier use of the Spring framework, we learned in the SSM stage now on the SpringBoot framework development is fully applicable, we learned most of the automatic configuration of SpringBoot.

Because one of the advantages of the Spring Boot framework is automated configuration, this is evident in the configuration of POM.xml.

So here I recommend my previous SSM phase integration project: SSM detailed introduction integration case SSM+Redis+Shiro+Solr+ vue.js integration project

Project depend on

See Github repository spring-boot/ pum.xml for the dependency files of this project

Initializing the database

For database table design of this project, please refer to GitHub warehouse: Spring-boot /db/

Please set up the database table structure before running the project

Mybatis SpringBoot integration

As stated earlier, the SpringBoot framework is not an enhancement to Spring functionality, but rather provides a quick way to use Spring

Therefore, the idea of SpringBoot integrating Mybatis is basically the same as Spring integrating Mybatis. There are two differences:

  • 1. The XML configuration file of the Mapper interface is changed. Before we use Mybatis interface agent development, Mapper mapping file and interface in the same directory; Mapper/SRC /main/ Java /; SRC /main/ Java /; SRC /main/ Java /;

  • 2.SpringBoot recommends using YAML as the configuration file, which has an easier configuration method. So the integration of Mybatis has certain differences in configuration files, but ultimately is the configuration of those several parameters.

Please search for the syntax of YAML. Here I only meet the basic configuration requirements and do not involve the syntax that is difficult to understand.

Consolidating configuration files

This example code detailed look at making warehouse: spring – the boot/resources/application. The yml

Configuring Mybatis with XML in the Spring phase is nothing more than configuration: 1. The connection pool; 2. Database URL connection; 3. The mysql driver; 4. Perform other initial configurations

Spring: a datasource: name: springboot type: com. Alibaba. Druid. Pool. # DruidDataSource druid related configuration druid: Filter filter: stat #mysql driver driver-class-name: com.mysql.jdbc.driver JDBC: mysql: / / 127.0.0.1:3306 / springboot? useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true username: root password: Root # initial-size: 1 min-idle: 1 max-active: 20 Mybatis: mapper-locations: 60000 #mybatis: mapper-locations: 60000 #mybatis: mapper-locations: 60000 #mybatis: mapper-locations: 60000 #mybatis: mapper-locations: classpath:mapper/*.xml type-aliases-package: cn.tycoding.entityCopy the code

Note: Spaces represent node levels; The comment section uses#tag

explain

  1. We have implemented the integration of Spring-MyBatis, including the configuration of MyBatis and datasource datasource is certainly part of the Spring configuration, so it needs to be under Spring:.

  2. Mapper-locations =

  3. Type-aliases-package is similar to the alias configuration in XML, generally using the entity class name as the alias.

  4. The datasource configuration, where name is the name of the current datasource, is similar to the

    id property, which can be specified arbitrarily since we don’t care how Spring injects the bean object.

  5. Driver-class-name: ; ; ; ; Other Druids’ private property configurations are no longer explained. Note that the druid connection pool and the C3P0 connection pool have different names in the XML, as well as different names in the SpringBoot configuration.

If Spring’s integrated Mybtis configuration is already familiar to you, this configuration is also familiar to you, and is easily distinguishable from the English name. It is important to note that YAML syntax dictates that different lines of whitespace represent different hierarchies.

Now that springboot-Mybatis basic configuration is complete, we will explain how to implement the basic CRUD.

To achieve the query

1. In the SRC/main/Java/cn/tycoding/entity/under the new User. Java entity class

public class User implements Serializable { private Long id; Private String username; // Username private String password; // password //getter/setter}Copy the code

2. In the SRC/main/Java/cn/tycoding/service/create BaseService. Java common interface, the purpose is to simplify the service interface layer basic CRUD methods of writing.

Public interface BaseService<T> {List<T> findAll(); List<T> findById(Long ID); // add void create(T T); // delete(batch) void delete(Long... ids); Void update(T T); }Copy the code

That’s my shorthand encapsulation of the basic CRUD interface at the Service layer, using generic classes whose inheriting interfaces specify whatever generics T represents.

3. The SRC/main/Java/cn/tycoding/service/create UserService. Java interface:

public interface UserService extends BaseService<User> {}

Copy the code

4. The SRC/main/Java/cn/tycoding/service/impl/create UserServiceImpl. Java implementation class:

@Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public List<User> findAll() { return userMapper.findAll(); } // other methods omit}Copy the code

5. The SRC/main/Java/cn/tycoding/mapper/create UserMapper. JavaMapper interface class:

@Mapper
public interface UserMapper {
    List<User> findAll();
}

Copy the code

As mentioned above, we must use @mapper interface to identify this interface, otherwise Mybatis cannot find its corresponding XML mapping file.

6. The SRC/main/resources/mapper/create UserMapper. The XML mapping file:

<? The 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.tycoding.mapper.UserMapper"> <! <select id="findAll" resultType="cn.tycoding.entity.User"> select * FROM tb_user </select> </mapper>Copy the code

7. The SRC/main/Java/cn/tycoding/controller/admin/create UserController. Java

@RestController public class UserController { @Autowired private UserService userService; @RequestMapping("/findAll") public List<User> findAll() { return userService.findAll(); }}Copy the code

8. To run the SRC/main/Java/cn/tycoding/SpringbootApplication Java main method, start springboot

To get a string of JSON data, visit localhost:8080/findAll in your browser.

thinking

Read the above step by step explanation. As you can see, CRUD is basically the same as THE SSM phase, so I won’t give any examples here.

Let’s explain the different places:

Realize page hopping

Because Thymeleaf specified directory SRC/main/resources/templates/directory is protected, its resources cannot be accessed directly through the browser, you can use the access Controller mapping, mapping?

1. Add the configuration in application.yml

spring:
  thymeleaf:
    prefix: classpath:/templates/
    check-template-location: true
    suffix: .html
    encoding: UTF-8
    mode: LEGACYHTML5
    cache: false

Copy the code

Specify the Thymeleaf template engine to scan for.html-terminated files in the Templates folder under Resources. This implements the MVC configuration of the view parser:

<! - the parser configuration view - > < bean class = "org. Springframework. Web. Servlet. The InternalResourceViewResolver" > < property name = "prefix" value="/"/> <property name="suffix" value=".jsp"/> </bean>Copy the code

Doesn’t it feel a lot easier? The important thing to note here is that classpath: must be preceded by a /, such as classpath:/templates/.

2. Add mapping methods to Controller

    @GetMapping(value = {"/", "/index"})
    public String index() {
        return "home/index";
    }

Copy the code

So, access localhost: 8080 / index will jump straight to the resources/templates/home/index. The HTML page.

Implementing paging query

First we need to configure the pageHelper plugin in application.yml

pagehelper:
  pagehelperDialect: mysql
  reasonable: true
  support-methods-arguments: true

Copy the code

I’m using Mybatis PageHelper and ElementUI for pagination. For a tutorial, see my blog: SpringMVC+ElementUI for paging queries

Core configuration:

UserServiceImp.java

Public PageBean findByPage(Goods Goods, int pageCode, int pageSize) {public PageBean findByPage(Goods Goods, int pageCode, int pageSize) { pageSize); Page<Goods> Page = goodsmapper.findbypage (Goods); return new PageBean(page.getTotal(), page.getResult()); }Copy the code

Implementing file upload

See my blog: SpringMVC File Upload and Download for a full tutorial

Because the front end of this project uses ElementUI+ vue.js technology, see my blog: SpringMVC+ElementUI for a file upload and echo tutorial on the front end

In addition to writing the code, there is also configuration in application.yml:

spring:
  servlet:
    multipart:
      max-file-size: 10Mb
      max-request-size: 100Mb

Copy the code

This is equivalent to SpringMVC’s XML configuration:

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="500000"/>
</bean>

Copy the code

Implement a simple login interceptor using Spring AOP aspect programming

In this project, we first unintegrate Shiro and Spring Security, and use Spring AOP to implement simple login interception:

@Component @Aspect public class MyInterceptor { @Pointcut("within (cn.tycoding.controller.. *) &&! within(cn.tycoding.controller.admin.LoginController)") public void pointCut() { } @Around("pointCut()") public Object trackInfo(ProceedingJoinPoint joinPoint) throws Throwable { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); User user = (User) request.getSession().getAttribute("user"); if (user == null) { attributes.getResponse().sendRedirect("/login"); // Manually forward to /login mapping path} return joinPoint.proceed(); }}Copy the code

explain

For more details on Spring AOP programming, please do your own search, or you can read my blog: Spring AOP Ideas. We need to note the following points

  1. Be sure to familiarize yourself with AspectJ’s pointcut expressions, here:.. * represents all methods and subdirectory methods under its directory.

  2. If login interception is performed, that is, the user’s login information is not retrieved in the session, we may need to manually forward to the LOGIN page, which accesses the Login map.

  3. If the Controller intercepted by AOP returns a view address, the Controller should return to that view address, but AOP intercepts it, so the Controller will still return. But the view address 404 is not found.

  4. Proceed () : Executes the notified method. Failure to proceed will prevent the notified method from being called, resulting in a 404 return in the Controller.

Preview

communication

If you are interested, welcome to join my Java communication technology group: 671017003, exchange and learn Java technology together. At present, the blogger has been learning JAVA by himself, the technology is limited, if possible, will try to provide you with some help, or some learning methods, of course, the big guy in the group will actively answer questions for the novice. So don’t hesitate to come and join us!

contact

If you have some questions after you see this article, you can contact me or you can find some info by clicking these links.

  • Blog@TyCoding’s blog
  • GitHub@TyCoding
  • ZhiHu@TyCoding

Recommended reading

Java Notes Complete.md

Great, this Java site, everything! https://markerhub.com

The UP master of this B station, speaks Java really good!