Spring Boot 入門篇:SpringBoot+SpringMVC+MyBatis 實戰(zhàn)

概述

通過使用整合 SpringBoot + SpringMVC + MyBatis ,實現(xiàn)對users表進行CRUD操作

工具

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

步驟

一臣嚣、創(chuàng)建項目

  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 數(shù)據(jù)庫驅動 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <!-- druid 數(shù)據(jù)庫連接池 -->
    <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 是阿里巴巴開發(fā)的號稱為監(jiān)控而生的數(shù)據(jù)庫連接池沟娱;
  1. 創(chuàng)建數(shù)據(jù)庫表
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 使用“習慣優(yōu)于配置”(項目中存在大量的配置,此外還內置了一個習慣性的配置腕柜,讓你無需手動進行配置)的理念讓你的項目快速運行起來济似。所以矫废,我們要想把 Spring Boot 玩的溜,就要懂得如何開啟各個功能模塊的默認配置砰蠢,這就需要了解 Spring Boot 的配置文件 application.properties蓖扑。
??????Spring Boot 使用了一個全局的配置文件 application.properties,放在 src/main/resources 目錄下或者類路徑的/config下台舱。Sping Boot 的全局配置文件的作用是對一些默認配置的配置值進行修改赵誓。


二、代碼編輯

  1. 創(chuàng)建實體類
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. 創(chuàng)建 Mapper 映射器
package cn.alinwork.mapper;

import java.util.List;
import cn.alinwork.pojo.User;

public interface UserMapper {
    //增加用戶
    int insertUser(User user);
    //查詢所有用戶信息
    List<User> selectUserAll();
    //根據(jù)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>
    <!-- 根據(jù)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. 創(chuàng)建 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);
}

  • 定義實現(xiàn)類
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. 創(chuàng)建 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>展示用戶數(shù)據(jù)</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/ 碰声,出現(xiàn)頁面:

ok诡蜓,至此已成功完畢......

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市胰挑,隨后出現(xiàn)的幾起案子蔓罚,更是在濱河造成了極大的恐慌,老刑警劉巖瞻颂,帶你破解...
    沈念sama閱讀 222,104評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件豺谈,死亡現(xiàn)場離奇詭異,居然都是意外死亡贡这,警方通過查閱死者的電腦和手機茬末,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,816評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來盖矫,“玉大人丽惭,你說我怎么就攤上這事倍靡⌒攀猓” “怎么了?”我有些...
    開封第一講書人閱讀 168,697評論 0 360
  • 文/不壞的土叔 我叫張陵轩拨,是天一觀的道長湃望。 經常有香客問我换衬,道長,這世上最難降的妖魔是什么证芭? 我笑而不...
    開封第一講書人閱讀 59,836評論 1 298
  • 正文 為了忘掉前任瞳浦,我火速辦了婚禮,結果婚禮上檩帐,老公的妹妹穿的比我還像新娘术幔。我一直安慰自己,他們只是感情好湃密,可當我...
    茶點故事閱讀 68,851評論 6 397
  • 文/花漫 我一把揭開白布诅挑。 她就那樣靜靜地躺著四敞,像睡著了一般。 火紅的嫁衣襯著肌膚如雪拔妥。 梳的紋絲不亂的頭發(fā)上忿危,一...
    開封第一講書人閱讀 52,441評論 1 310
  • 那天,我揣著相機與錄音没龙,去河邊找鬼铺厨。 笑死,一個胖子當著我的面吹牛硬纤,可吹牛的內容都是我干的解滓。 我是一名探鬼主播,決...
    沈念sama閱讀 40,992評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼筝家,長吁一口氣:“原來是場噩夢啊……” “哼洼裤!你這毒婦竟也來了?” 一聲冷哼從身側響起溪王,我...
    開封第一講書人閱讀 39,899評論 0 276
  • 序言:老撾萬榮一對情侶失蹤腮鞍,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后莹菱,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體移国,經...
    沈念sama閱讀 46,457評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 38,529評論 3 341
  • 正文 我和宋清朗相戀三年道伟,在試婚紗的時候發(fā)現(xiàn)自己被綠了迹缀。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,664評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡皱卓,死狀恐怖裹芝,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情娜汁,我是刑警寧澤,帶...
    沈念sama閱讀 36,346評論 5 350
  • 正文 年R本政府宣布兄朋,位于F島的核電站掐禁,受9級特大地震影響,放射性物質發(fā)生泄漏颅和。R本人自食惡果不足惜傅事,卻給世界環(huán)境...
    茶點故事閱讀 42,025評論 3 334
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望峡扩。 院中可真熱鬧蹭越,春花似錦、人聲如沸教届。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,511評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至买置,卻和暖如春粪糙,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背忿项。 一陣腳步聲響...
    開封第一講書人閱讀 33,611評論 1 272
  • 我被黑心中介騙來泰國打工蓉冈, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人轩触。 一個月前我還...
    沈念sama閱讀 49,081評論 3 377
  • 正文 我出身青樓寞酿,卻偏偏與公主長得像,于是被迫代替她去往敵國和親脱柱。 傳聞我的和親對象是個殘疾皇子伐弹,可洞房花燭夜當晚...
    茶點故事閱讀 45,675評論 2 359

推薦閱讀更多精彩內容