天天看點

JavaWeb架構梳理(九)——SpringBoot配置Mybatis

文章目錄

    • 注解配置
        • application.properties
        • 配置pom
        • 實體類Category
        • CategoryMapper
        • CategoryController
        • listCategory.jsp
        • 效果
    • xml方式
        • CategoryMapper
        • Category.xml
        • application.properties
        • 項目結構
    • 實作CRUD
        • 增加對PageHelper的jar
        • 配置PageHelper
        • CategoryMapper
        • CategoryController
        • listCategory.jsp
        • 效果

來源于how2j

github項目入口

注解配置

application.properties

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

配置pom

mysql mybatis

<!-- 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>
	<version>5.1.21</version>
</dependency>
           

實體類Category

package com.how2java.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;
    }
      
}
           

CategoryMapper

  • 增加一個包:com.how2java.springboot.mapper,然後建立接口CategoryMapper。
  • 使用注解@Mapper 表示這是一個Mybatis Mapper接口。
  • 使用@Select注解表示調用findAll方法會去執行對應的sql語句。對比配置檔案Category.xml,其實就是把SQL語句從XML挪到了注解上來
package com.how2java.springboot.mapper;
 
import java.util.List;
 
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
 
import com.how2java.springboot.pojo.Category;
 
@Mapper
public interface CategoryMapper {
 
    @Select("select * from category_ ")
    List<Category> findAll();
 
}
           

CategoryController

增加一個包:com.how2java.springboot.web,然後建立CategoryController 類。

  1. 接受listCategory映射
  2. 然後擷取所有的分類資料
  3. 接着放入Model中
  4. 跳轉到listCategory.jsp中
package com.how2java.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 com.how2java.springboot.mapper.CategoryMapper;
import com.how2java.springboot.pojo.Category;
   
@Controller
public class CategoryController {
    @Autowired CategoryMapper categoryMapper;
      
    @RequestMapping("/listCategory")
    public String listCategory(Model m) throws Exception {
        List<Category> cs=categoryMapper.findAll();
          
        m.addAttribute("cs", cs);
          
        return "listCategory";
    }
      
}
           

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"%>
   
<table align='center' border='1' cellspacing='0'>
    <tr>
        <td>id</td>
        <td>name</td>
    </tr>
    <c:forEach items="${cs}" var="c" varStatus="st">
        <tr>
            <td>${c.id}</td>
            <td>${c.name}</td>
                
        </tr>
    </c:forEach>
</table>
           

效果

JavaWeb架構梳理(九)——SpringBoot配置Mybatis

xml方式

CategoryMapper

去掉sql注解

package com.how2java.springboot.mapper;
 
import java.util.List;
 
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
 
import com.how2java.springboot.pojo.Category;
 
@Mapper
public interface CategoryMapper {
 
    List<Category> findAll();
 
}
           

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="com.how2java.springboot.mapper.CategoryMapper">
        <select id="findAll" resultType="Category">
            select * from category_
        </select>   
    </mapper>
           

application.properties

指明從哪裡去找xml配置檔案,同時指定别名

spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
 
mybatis.mapper-locations=classpath:com/how2java/springboot/mapper/*.xml
mybatis.type-aliases-package=com.how2java.springboot.pojo

           

項目結構

JavaWeb架構梳理(九)——SpringBoot配置Mybatis

實作CRUD

增加對PageHelper的jar

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

配置PageHelper

  • 注解@Configuration 表示PageHelperConfig 這個類是用來做配置的。
  • 注解@Bean 表示啟動PageHelper這個攔截器。
  • 新增加一個包 com.how2java.springboot.config, 然後添加一個類PageHelperConfig ,其中進行PageHelper相關配置。
  • offsetAsPageNum:設定為true時,會将RowBounds第一個參數offset當成pageNum頁碼使用.

    p.setProperty("offsetAsPageNum", "true");

  • rowBoundsWithCount:設定為true時,使用RowBounds分頁會進行count查詢.

    p.setProperty("rowBoundsWithCount", "true");

  • reasonable:啟用合理化時,如果pageNum<1會查詢第一頁,如果pageNum>pages會查詢最後一頁。

    p.setProperty("reasonable", "true");

  • 代碼:
package com.how2java.springboot.config;
 
import java.util.Properties;
 
import org.springframework.context.annotation.Bean;
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");
        p.setProperty("rowBoundsWithCount", "true");
        p.setProperty("reasonable", "true");
        pageHelper.setProperties(p);
        return pageHelper;
    }
}
           

CategoryMapper

package com.how2java.springboot.mapper;
 
import java.util.List;
 
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
 
import com.how2java.springboot.pojo.Category;
 
@Mapper
public interface CategoryMapper {
 
    @Select("select * from category_ ")
    List<Category> findAll();
     
    @Insert(" insert into category_ ( name ) values (#{name}) ")
    public int save(Category category); 
     
    @Delete(" delete from category_ where id= #{id} ")
    public void delete(int id);
         
    @Select("select * from category_ where id= #{id} ")
    public Category get(int id);
       
    @Update("update category_ set name=#{name} where id=#{id} ")
    public int update(Category category); 
 
}
           

CategoryController

修改查詢映射

@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";
}
           
  • 在參數裡接受目前是第幾頁 start ,以及每頁顯示多少條資料 size。 預設值分别是0和5。

    @RequestParam(value = "start", defaultValue = "0") int start,@RequestParam(value = "size", defaultValue = "5"

  • 根據start,size進行分頁,并且設定id 倒排序

    PageHelper.startPage(start,size,"id desc")

    ;
  • 因為PageHelper的作用,這裡就會傳回目前分頁的集合了

    List<Category> cs=categoryMapper.findAll()

    ;
  • 根據傳回的集合,建立PageInfo對象

    PageInfo<Category> page = new PageInfo<>(cs)

    ;
  • 把PageInfo對象扔進model,以供後續顯示

    m.addAttribute("page", page)

    ;
  • 跳轉到listCategory.jsp

    return "listCategory"

    ;
  • 代碼:
package com.how2java.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 com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.how2java.springboot.mapper.CategoryMapper;
import com.how2java.springboot.pojo.Category;
   
@Controller
public class CategoryController {
    @Autowired CategoryMapper categoryMapper;
      
    @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";
    }
     
    @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";
    }
     
}
           

listCategory.jsp

通過page.getList周遊目前頁面的Category對象。

在分頁的時候通過page.pageNum擷取目前頁面,page.pages擷取總頁面數。

注:page.getList會傳回一個泛型是Category的集合。

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
  
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    
<div align="center">
  
</div>
  
<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>
           

editCategory.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8" isELIgnored="false"%>
  
<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>
           

效果

JavaWeb架構梳理(九)——SpringBoot配置Mybatis

繼續閱讀