美文网首页
Spring Boot 入门篇:SpringBoot+Sprin

Spring Boot 入门篇:SpringBoot+Sprin

作者: 离线中__ | 来源:发表于2019-02-13 18:07 被阅读0次

    概述

    通过使用整合 SpringBoot + SpringMVC + MyBatis ,实现对users表进行CRUD操作

    工具

    eclipse + mvn + jdk1.7 + spring boot 1.5.10.RELEASE + mysql

    步骤

    一、创建项目

    1. 修改 pom.xml 文件
    <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>
      <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.10.RELEASE</version>
      </parent>
      <groupId>cn.alinwork</groupId>
      <artifactId>10_springboot_mybatis</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      
      <properties>
        <!-- 1.5.10.RELEASE 版本 spring boot 使用 jdk1.7 -->
        <java.version>1.7</java.version>
        <!-- thymeleaf 版本 -->
        <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
        
        <thymeleaf-layout-dialect.version>2.0.4</thymeleaf-layout-dialect.version>
      </properties>
      
      <dependencies>
        <!-- 
            web 启动器 ,thymeleaf 是 spring boot 推荐的视图层技术;
            spring-boot-starter-thymeleaf 下面已经包括了 spring-boot-starter-web,
            所以可以把 spring-boot-starter-web 的依赖去掉
        -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!-- mybatis 启动器 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>
        <!-- mysql 数据库驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- druid 数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.9</version>
        </dependency>
      </dependencies>
      
    </project>
    
    • demo 使用 jdk1.7 + spring boot 1.5.10.RELEASE 版本;
    • thymeleaf 是 spring boot 推荐的视图层技术;
    • druid 是阿里巴巴开发的号称为监控而生的数据库连接池;
    1. 创建数据库表
    CREATE TABLE `users` (
      `id` smallint NOT NULL AUTO_INCREMENT,
      `name` varchar(20) DEFAULT NULL,
      `age` smallint DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
    1. 在 application.properties 文件配置连接池
    spring.datasource.driverClassName=com.mysql.jdbc.Driver
    spring.datasource.url=jdbc:mysql://localhost:3306/testdb
    spring.datasource.username=free
    spring.datasource.password=1234
    #连接池类型
    spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
    #mybatis 扫描路径
    mybatis.type-aliases-package=cn.alinwork.pojo
    

    application.properties 文件 :
          Spring Boot 使用“习惯优于配置”(项目中存在大量的配置,此外还内置了一个习惯性的配置,让你无需手动进行配置)的理念让你的项目快速运行起来。所以,我们要想把 Spring Boot 玩的溜,就要懂得如何开启各个功能模块的默认配置,这就需要了解 Spring Boot 的配置文件 application.properties。
          Spring Boot 使用了一个全局的配置文件 application.properties,放在 src/main/resources 目录下或者类路径的/config下。Sping Boot 的全局配置文件的作用是对一些默认配置的配置值进行修改。

    二、代码编辑

    1. 创建实体类
    package cn.alinwork.pojo;
    
    public class User {
        private int id;
        private String name;
        private int age;
    
        public User() {}
        public User(int id, String name, int age) {
            super();
            this.id = id;
            this.name = name;
            this.age = age;
        }
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        @Override
        public String toString() {
            return "name: " + name + " ,age: " + age;
        }
    }
    
    
    1. 创建 Mapper 映射器
    package cn.alinwork.mapper;
    
    import java.util.List;
    import cn.alinwork.pojo.User;
    
    public interface UserMapper {
        //增加用户
        int insertUser(User user);
        //查询所有用户信息
        List<User> selectUserAll();
        //根据id查询用户信息
        User findUserById(Integer id);
        //更新用户信息
        int updateUser(User user);
        //删除用户
        int deleteUser(Integer id);
    }
    
    
    1. 编写 sql 文件
    <?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.alinwork.mapper.UserMapper">
        <!-- 增加用户 -->
        <insert id="insertUser" parameterType="user">
            insert into user(name,age) values(#{name},#{age})
        </insert>
        <!-- 查询所有用户信息 -->
        <select id="selectUserAll" resultType="user">
            select id, name , age from user
        </select>
        <!-- 根据id查询用户信息 -->
        <select id="findUserById" parameterType="java.lang.Integer" resultType="user">
            select id,name,age from user where id = #{id}
        </select>
        <!-- 更新用户信息 -->
        <update id="updateUser" parameterType="user">
            update user set name = #{name} , age = #{age} where id = #{id}
        </update>
        <!-- 删除用户 -->
        <delete id="deleteUser" parameterType="java.lang.Integer">
            delete from user where id = #{id}
        </delete>
    </mapper>
    
    • namespace 指定对应Mapper 映射器类
    • parameterType 为 cn.alinwork.pojo.User 类时,可以用 user 替代;
      因为在 application.properties 文件里作了配置
      mybatis.type-aliases-package=cn.alinwork.pojo
    1. 创建 service 类
    • 定义接口类
    package cn.alinwork.service;
    
    import java.util.List;
    import cn.alinwork.pojo.User;
    
    public interface UserService {
        int addUser(User user);
        List<User> findAllUser();
        User findUserById(Integer id);
        int updateUser(User user);
        int deleteUser(Integer id);
    }
    
    
    • 定义实现类
    package cn.alinwork.service.impl;
    
    import java.util.List;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    import cn.alinwork.mapper.UserMapper;
    import cn.alinwork.pojo.User;
    import cn.alinwork.service.UserService;
    
    @Service
    @Transactional
    public class UserServiceImpl implements UserService {
    
        @Autowired
        private UserMapper userMapper;
        @Override
        public int addUser(User user) {
            return this.userMapper.insertUser(user);
        }
        @Override
        public List<User> findAllUser() {
            return this.userMapper.selectUserAll();
        }
        @Override
        public User findUserById(Integer id) {
            return this.userMapper.findUserById(id);
        }
        @Override
        public int updateUser(User user) {
            return this.userMapper.updateUser(user);
        }
        @Override
        public int deleteUser(Integer id) {
            return this.userMapper.deleteUser(id);
        }
    }
    
    
    1. 创建 controller 类
    package cn.alinwork.controller;
    
    import java.util.List;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    import cn.alinwork.pojo.User;
    import cn.alinwork.service.UserService;
    
    @Controller
    @RequestMapping("/user")
    public class UserController {
    
        @Autowired
        private UserService userService;
    
        @RequestMapping("/")
        private String findUserAll(Model model){
            List<User> users = this.userService.findAllUser();
            model.addAttribute("users", users);
            return "queryAll";
        }
        
        @RequestMapping("/gotoAddUser")
        private String gotoAddUser(){
            return "addUser";
        }
        
        @RequestMapping("/addUser")
        private String addUser(User user){
            this.userService.addUser(user);
            return "ok";
        }
        
        @RequestMapping("/findUserById")
        private String findUserById(int id , Model model){
            User user = this.userService.findUserById(id);
            model.addAttribute("user", user);
            return "update";
        }
        
        @RequestMapping("/updateUser")
        private String updateUser(User user){
            this.userService.updateUser(user);
            return "ok";
        }
        
        @RequestMapping("/deleteUser")
        private String deleteUser(int id){
            this.userService.deleteUser(id);
            return "ok";
        }
    }
    
    1. 视图文件
    • queryAll.html
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8"></meta>
    <title>展示用户数据</title>
    </head>
    <body>
        <div>
            <table border="1px">
                <tr><th>用户ID</th><th>用户姓名</th><th>用户年龄</th><th>操作</th></tr>
                <tr th:each="user:${users}">
                    <td th:text="${user.id}"></td>
                    <td th:text="${user.name}"></td>
                    <td th:text="${user.age}"></td>
                    <td>
                        <a th:href="@{/user/findUserById(id=${user.id})}">修改</a>
                        <a th:href="@{/user/deleteUser(id=${user.id})}">删除</a>
                    </td>
                </tr>
            </table>
            <h1><a th:href="@{/user/gotoAddUser}">添加用户</a></h1>
        </div>
    </body>
    </html>
    
    • addUser.html
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8"></meta>
    <title>用户新增</title>
    </head>
    <body>
        <form th:action="@{/user/addUser}">
            用户姓名:<input type="text" name="name" /><br>
            用户年龄:<input type="text" name="age" /><br>
            <input type="submit" value="确定" />
        </form>
    </body>
    </html>
    
    • update.html
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8"></meta>
    <title>修改用户</title>
    </head>
    <body>
        <form th:action="@{/user/updateUser}">
            <input type="hidden" th:field="${user.id}">
            用户姓名:<input type="text" name="name" th:field="${user.name}"/><br>
            用户年龄:<input type="text" name="age" th:field="${user.age}"/><br>
            <input type="submit" value="确定" />
        </form>
    </body>
    </html>
    
    • ok.html
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8"></meta>
    <title>添加成功页</title>
    </head>
    <body>
        <h1>ok !!!</h1>
        <h1><a th:href="@{/user/}">去首页</a></h1>
    </body>
    </html>
    
    1. 编写启动类
    package cn.alinwork;
    
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    /**
     * SpringBoot 启动类
     */
    @SpringBootApplication
    @MapperScan("cn.alinwork.mapper")
    public class App {
        public static void main(String[] args) {
            SpringApplication.run(App.class, args);
        }
    }
    
    
    

    三、测试

    在浏览器输入 http://localhost:8080/user/ ,出现页面:

    ok,至此已成功完毕......

    相关文章

      网友评论

          本文标题:Spring Boot 入门篇:SpringBoot+Sprin

          本文链接:https://www.haomeiwen.com/subject/kmglsqtx.html