Chapter IV Spring-Boot + Mybatis set of Web development projects

Examples of the third chapter, we learned how to create a Spring Boot Web project, how to configure, as well as some special treatment problems in the environment. This example Mybatis us to achieve the next set of MVC mode, the view layer, control layer, business layer, complete project program data layer, simple and clear to understand Mybatis applications, compared to Hibernate familiar friends, Mybatis change is easier a.

4.1 New Spring Boot Web project

Create a Spring Boot Web project name "Springboot_Mybatis_01":

Complete the project creation, project directory structure is as follows:

4.2 Configuration pom.xml

 Maven resource management in the framework of the configuration file, frame spring, mybatis, detailed configuration information 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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.gg</groupId>
    <artifactId>Springboot_Mybatis_01</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>Springboot_Mybatis_01</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
View Code

4.3   配置application.properties

配置数据库连接、mybatis映射文件路径:

#tomcat
server.port=8080
server.servlet.context-path=/
server.tomcat.uri-encoding=UTF-8

spring.thymeleaf.mode=HTML
spring.thymeleaf.cache=true
spring.thymeleaf.enabled=true
spring.thymeleaf.encoding=utf-8
spring.thymeleaf.prefix=/resources/templates/
spring.thymeleaf.suffix=.html

#database
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

#xml configs
mybatis.mapper-locations=classpath:mapping/*Mapping.xml
mybatis.type-aliases-package=com.gg.bean

4.4   项目结构与源代码

本例子来实现一个用户信息的查询功能,按照顺序来逐步的完成数据库表结构创建、以及编写每一层的代码实现:

1、这里使用Mysql数据库中的test库,并在该库中创建一个表user

CREATE TABLE `user` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `userName` VARCHAR(32) CHARACTER SET utf8_unicode_ci DEFAULT NULL,
  `passWord` VARCHAR(32) CHARACTER SET utf8_unicode_ci DEFAULT NULL,
  `realName` VARCHAR(32) CHARACTER SET utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) 

并添加一条数据记录:

2、在项目中建立对应的数据原型,新建包“com.gg.bean”,在这个包下面新建数据原型类User.java:

package com.gg.bean;

public class User {
    private Integer id;
    private String userName;
    private String passWord;
    private String realName;
 
    public Integer getId() {
        return id;
    }
 
    public void setId(Integer id) {
        this.id = id;
    }
 
    public String getUserName() {
        return userName;
    }
 
    public void setUserName(String userName) {
        this.userName = userName;
    }
 
    public String getPassWord() {
        return passWord;
    }
 
    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }
 
    public String getRealName() {
        return realName;
    }
 
    public void setRealName(String realName) {
        this.realName = realName;
    }

    
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", passWord='" + passWord + '\'' +
                ", realName='" + realName + '\'' +
                '}';
    }

}
View Code

3、在项目中建立数据映射mapper,新建包“com.gg.mapper”,在这个包下面新建接口映射类UserMapper.java:

package com.gg.mapper;

import com.gg.bean.User;
import org.springframework.stereotype.Repository;

@Repository
public interface UserMapper {
    User getUser(int id);
}
View Code

4、在项目中建立Service类,新建包“com.gg.service”,在这个包下面新建服务类UserService.java:

package com.gg.service;

import com.gg.bean.User;
import com.gg.mapper.UserMapper;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

@Service
public class UserService {
    @Autowired
    UserMapper userMapper;
    
    public User getUser(int id) {
        return userMapper.getUser(id);
    }
}
View Code

5、在项目中建立控制器,新建包“com.gg.controller”,在这个包下面新建控制器类UserController.java:

package com.gg.controller;

import com.gg.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/userBoot")
public class UserController {
    @Autowired
    private UserService userService;
 
    @RequestMapping("getUser/{id}")
    public String GetUser(@PathVariable int id){
        return userService.getUser(id).toString();
    }

}
View Code

6、  Application启动类,在应用程序启动类的头部增加Mapper扫描的包名称:

package com.gg;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.gg.mapper") //扫描的mapper
public class SpringbootMybatis01Application {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootMybatis01Application.class, args);
    }
}
View Code

4.5   Mybatis的配置与数据映射

在resources目录下创建mapping目录,在此目录下创建UserMapping.xml,文件信息内容:

<?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="com.gg.mapper.UserMapper">
 
    <resultMap id="BaseResultMap" type="com.gg.bean.User">
        <result column="id" jdbcType="INTEGER" property="id" />
        <result column="userName" jdbcType="VARCHAR" property="userName" />
        <result column="passWord" jdbcType="VARCHAR" property="passWord" />
        <result column="realName" jdbcType="VARCHAR" property="realName" />
    </resultMap>
 
    <select id="getUser" resultType="com.gg.bean.User">
        select * from user where id = #{id}
    </select>
</mapper>
View Code

4.6   项目最终的结构

4.7   项目运行与测试

Maven构建项目,然后启动运行,在浏览器输入:http://127.0.0.1:8080/userBoot/getUser/1,结果如下:

Guess you like

Origin www.cnblogs.com/fengguozhong/p/12084551.html