天天看點

SpringBoot學習筆記(六、Mybatis)

Mybatis這個架構式當下比較流行的架構,SpringBoot整合Mybatis其實和整合JPA是比較相似的,有差別的隻是資料操作的部分。

1、引入相應依賴

mybatis-

spring-boot

-starter

<dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
         </dependency>      

pagehelper

<dependency>
           <groupId>com.github.pagehelper</groupId>
           <artifactId>pagehelper</artifactId>
           <version>4.1.6</version>
         </dependency>      

完整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>
  <groupId>edu.hpu</groupId>
  <artifactId>SpringBoot</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringBoot</name>
  <!-- Spring Boot 啟動父依賴 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.3.RELEASE</version>
    </parent>
    <dependencies>
        <!-- Spring Boot web依賴 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- Junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <!-- 添加servlet依賴 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>
        
        <!--添加 jstl依賴 -->
        <dependency>
           <groupId>javax.servlet</groupId>
           <artifactId>jstl</artifactId>
        </dependency>
        
        <!-- tomcat的支援 -->
        <dependency>
           <groupId>org.apache.tomcat.embed</groupId>
           <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
        
        <!-- 熱部署依賴 -->
        <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional> <!-- 這個需要為 true 熱部署才有效 -->
        </dependency>
        
        <!-- 添加對mysql的支援 -->
        <dependency>
           <groupId>mysql</groupId>
           <artifactId>mysql-connector-java</artifactId>
           <version>5.1.21</version>
        </dependency>
        
         <!--mybatis支援  -->
         <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
         </dependency>
         
         <!-- pagehelper -->
         <dependency>
           <groupId>com.github.pagehelper</groupId>
           <artifactId>pagehelper</artifactId>
           <version>4.1.6</version>
         </dependency>
    </dependencies>
    
    <properties>
      <java.version>1.8</java.version>
    </properties>
    
    <build>
       <plugins>
           <plugin>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-maven-plugin</artifactId>
           </plugin>
       </plugins>
    </build>
</project>      

2、application.properties

除了資料源相關的配置,和Mybatis相關的還要指明從哪裡去找xml配置檔案,同時指定别名

spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
spring.datasource.url=jdbc:mysql://localhost:3306/springbootjpa?characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=xing0515
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

mybatis.mapper-locations=classpath:edu/hpu/springboot/mapper/*.xml
mybatis.type-aliases-package=edu.hpu.springboot.pojo      

3、資料

懶得再建了,還是用之前的

create database springbootjpa;
      
use springbootjpa; 
CREATE TABLE category_ ( 
 id int(11) NOT NULL AUTO_INCREMENT,
 name varchar(30), PRIMARY KEY (id) ) DEFAULT CHARSET=UTF8;      

相應的實體類

package edu.hpu.springboot.pojo;

public class Category {
   private int id;
   private String name;

    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;
    }
   
}      

4、PageHelperConfig

建立一個包edu.hpu.springboot.config,包下建立一個類 PageHelperConfig,這個類是幹什麼的,管分頁的。

注解@Configuration 表示PageHelperConfig 這個類是用來做配置的。

注解@Bean 表示啟動PageHelper這個攔截器。

import org.springframework.context.annotation.Configuration;

import com.github.pagehelper.PageHelper;

@Configuration
public class PageHelperConfig {
    @Bean
    public PageHelper pageHelper() {
        PageHelper pageHelper = new PageHelper();
        Properties p = new Properties();
        p.setProperty("offsetAsPageNum", "true");  //将RowBounds第一個參數offset當成pageNum頁碼使用.
        p.setProperty("rowBoundsWithCount", "true");  //使用RowBounds分頁會進行count查詢
        p.setProperty("reasonable", "true");                       //啟用合理化時,如果pageNum<1會查詢第一頁,如果pageNum>pages會查詢最後一頁
        pageHelper.setProperties(p);
        return pageHelper;
    }

}      

5、CategoryMapper

建立一個edu.hpu.springboot.mapper包,包下建立一個接口CategoryMapper

package edu.hpu.springboot.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;


import edu.hpu.springboot.pojo.Category;
@Mapper
public interface CategoryMapper {
    List<Category> findAll();
    public int save(Category category);
    public void delete(int id);
    public Category get(int id);
    public int update(Category category);
}      

6、Category.xml

在edu.hpu.springboot.mapper下建立Category.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="edu.hpu.springboot.mapper.CategoryMapper">
        <select id="findAll" resultType="Category">
            select * from category_
        </select>   
        
        <insert id="save" parameterType="Category">
          insert into category_ ( name ) values (#{name})
        </insert>
        
        <delete id="delete" parameterType="int">
           delete from category_ where id= #{id}
        </delete>
        
        <select id="get" parameterType="int" resultType="Category">
          select * from category_ where id= #{id}
        </select>
        
        <update id="update" parameterType="Category">
           update category_ set name=#{name} where id=#{id}
        </update>
    </mapper>      

7、CategoryController

package edu.hpu.springboot.web;

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 org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import edu.hpu.springboot.mapper.CategoryMapper;
import edu.hpu.springboot.pojo.Category;

@Controller
public class CategoryController {
   @Autowired
   CategoryMapper categoryMapper;
   
   @RequestMapping("/listCategory")
   public String listCategory(Model m,@RequestParam(value = "start", defaultValue = "0") int start,@RequestParam(value = "size", defaultValue = "5") int size) throws Exception {
       PageHelper.startPage(start,size,"id desc");
       List<Category> cs=categoryMapper.findAll();
       PageInfo<Category> page = new PageInfo<>(cs);
       m.addAttribute("page", page);         
       return "listCategory";
   }
   
   @RequestMapping("/addCategory")
   public String listCategory(Category c) throws Exception {
    categoryMapper.save(c);
    return "redirect:listCategory";
   }
   @RequestMapping("/deleteCategory")
   public String deleteCategory(Category c) throws Exception {
    categoryMapper.delete(c.getId());
    return "redirect:listCategory";
   }
   @RequestMapping("/updateCategory")
   public String updateCategory(Category c) throws Exception {
    categoryMapper.update(c);
    return "redirect:listCategory";
   }
   @RequestMapping("/editCategory")
   public String listCategory(int id,Model m) throws Exception {
    Category c= categoryMapper.get(id);
    m.addAttribute("c", c);
    return "editCategory";
   }
}      

8、listCategory.jsp與editCategory.jsp

listCategory.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>   
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>檢視分類</title>
</head>
<body>
    <div style="width: 500px; margin: 20px auto; text-align: center">
        <table align='center' border='1' cellspacing='0'>
            <tr>
                <td>id</td>
                <td>name</td>
                <td>編輯</td>
                <td>删除</td>
            </tr>
            <c:forEach items="${page.list}" var="c" varStatus="st">
                <tr>
                    <td>${c.id}</td>
                    <td>${c.name}</td>
                    <td><a href="editCategory?id=${c.id}">編輯</a></td>
                    <td><a href="deleteCategory?id=${c.id}">删除</a></td>
                </tr>
            </c:forEach>

        </table>
        <br>
        <div>
            <a href="?start=1">[首 頁]</a> <a href="?start=${page.pageNum-1}">[上一頁]</a>
            <a href="?start=${page.pageNum+1}">[下一頁]</a> <a
                href="?start=${page.pages}">[末 頁]</a>
        </div>
        <br>
        <form action="addCategory" method="post">

            name: <input name="name"> <br>
            <button type="submit">送出</button>

        </form>
    </div>
    </html>      

editCategory.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>修改</title>
</head>
<body>
    <div style="margin: 0px auto; width: 500px">

        <form action="updateCategory" method="post">

            name: <input name="name" value="${c.name}"> <br> <input
                name="id" type="hidden" value="${c.id}">
            <button type="submit">送出</button>

        </form>
    </div>
</body>
</html>      

整個項目結構一覽(忽略掉那個紅叉,不影響)

SpringBoot學習筆記(六、Mybatis)

跑一下

SpringBoot學習筆記(六、Mybatis)
SpringBoot學習筆記(六、Mybatis)

關于Mybatis,還可以使用注解的方式,就是不用xml配置,在接口相應語句上添加注解,比如

@Select("select * from category_ ")
    List<Category> findAll();