第四章 Spring-Boot+Mybatis 集合开发Web项目

第三章的例子中,我们掌握了如何来创建Spring Boot Web项目,如何配置,以及环境中的一些特殊问题的处理方法。本示例我们集合Mybatis来实现一个MVC模式下,视图层、控制层、业务层、数据层的完整的项目程序,简单清晰的了解Mybatis的应用,相比熟悉Hibernate的朋友,Mybatis变的是更简单了。

4.1   新建Spring Boot Web项目

先创建一个Spring Boot Web项目,名称“Springboot_Mybatis_01”:

完成项目创建,项目目录结构如下:

4.2   配置pom.xml

 在Maven的框架资源管理文件中配置了,spring、mybatis的框架,详细的配置信息如下:

<?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”,在这个包下面新建JavaBean类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,结果如下:

4.8   项目Git源代码

https://github.com/FengGuoZhong/java-spring-web

https://github.com/FengGuoZhong/java-spring-web/tree/master/Springboot_Mybatis_01

posted @ 2019-12-23 16:43  柴高八斗  阅读(488)  评论(0编辑  收藏  举报