SpringBoot study notes (six, Mybatis)

Mybatis the framework of current popular style framework, SpringBoot Mybatis integration and integration JPA is actually relatively similar, differentiated only part of the data manipulation.

1, the introduction of the respective dependent

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>

Complete 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

In addition to the data source associated configuration, and related Mybatis also indicates where to find the xml configuration file, specify an alias

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, data

Before too lazy to build, or use

create database springbootjpa;

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

Respective entity class

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

Create a new package edu.hpu.springboot.config, a new class PageHelperConfig the package, this class is doing, tubes tab.
Notes @Configuration represents PageHelperConfig This class is used for configuration.
Notes @Bean start PageHelper represent the interceptor.

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 a new packet, the new packet interface 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

New Category.xml in edu.hpu.springboot.mapper

<?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>

The entire project structure List (ignore the red cross, does not affect)
Here Insert Picture Descriptionrun about
Here Insert Picture DescriptionHere Insert Picture Descriptionon Mybatis, also can be used as annotations, is not xml configuration, add annotations on the interface corresponding statement, such as

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

参考:
【1】、https://blog.csdn.net/forezp/article/details/70768477
【2】、http://how2j.cn/k/springboot/springboot-mybatis-crud-pagination/1651.html#nowhere

Guess you like

Origin blog.csdn.net/sinat_40770656/article/details/89683800