SpringBoot结合Mybatis

2019-01-11 19:46:00     
这里使用Mybatis来做一个完整的CRUD和分页。 其中分页使用Mybatis 里的PageHelper插件

建立表结构

CREATE TABLE `category` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(32) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;

pom.xml

各种jar包依赖

<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>top.bounds</groupId>
	<artifactId>springboot</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>springboot</name>
	<description>springboot</description>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.9.RELEASE</version>
	</parent>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<optional>true</optional> <!-- 这个需要为 true 热部署才有效 -->
		</dependency>
		<!-- servlet依赖. -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
		</dependency>
		<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>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
		<!-- mysql -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			</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>
		<!-- springboot test -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </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>

Application.java

创建 Application.java(包名:top.bounds.springboot),其注解 @SpringBootApplication 表示这是一个SpringBoot应用,运行其主方法就会启动tomcat,默认端口是8080

package top.bounds.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
}

Category.java

创建catagory.java(包名:top.bounds.springboot.pojo)实体类,对应sql表

package top.bounds.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.java

创建CategoryMapper.java(包名:top.bounds.springboot.mapper),增加CRUD方法的支持。 其实就是调用不同的SQL语句。

package top.bounds.springboot.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;

import top.bounds.springboot.pojo.Category;

@Mapper
public interface CategoryMapper {
	// 查询所有
	List<Category> findAll();

	// 插入
	public int save(Category category);

	// 删除
	public void delete(int id);

	// 修改
	public void update(Category category);

	// 查找一条
	public Category findById(int id);
}

Category.xml

创建Category.xml(包名:top.bounds.springboot.mapper)对应的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="top.bounds.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>
	<!-- 修改 -->
	<update id="update" parameterType="Category">
		update category set
		name=#{name} where id=#{id}
	</update>
	<!-- 查询一条 -->
	<select id="findById" resultType="Category" parameterType="_int">
		select * from category where id=#{id}
	</select>
</mapper>

application.properties

SpringBoot的配置文件(路径:src/main/resources),加入springmvc、mysql、mybatis的相关配置

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

TestSpringBoot.java

创建TestSpringBoot.java(包名:top.bounds.springboot.test)测试类

package top.bounds.springboot.test;

import java.util.List;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import top.bounds.springboot.Application;
import top.bounds.springboot.mapper.CategoryMapper;
import top.bounds.springboot.pojo.Category;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class TestSpringBoot {
	@Resource
	CategoryMapper categoryMapper;

	@Test
	public void testOne() {
		List<Category> list = categoryMapper.findAll();
		for (Category c : list) {
			System.out.println(c.getId() + ",,," + c.getName());
		}
	}
}

到这一步就可以进行测试了。使用JUnit进行测试,可以查看到控制台打印的数据

PageHelperConfig.java

创建PageHelperConfig.java(包名:top.bounds.springboot.config)分页类

package top.bounds.springboot.config;

import java.util.Properties;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
import com.github.pagehelper.PageHelper;
 
/**
 * @Configuration 表示PageHelperConfig 这个类是用来做配置的
 * @Bean 表示启动PageHelper这个拦截器
 * @author bounds
 */
@Configuration
public class PageHelperConfig {
 
    @Bean
    public PageHelper pageHelper() {
        PageHelper pageHelper = new PageHelper();
        Properties p = new Properties();
        //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");
        pageHelper.setProperties(p);
        return pageHelper;
    }
}

BootController.java

创建BootController.java(包名:top.bounds.springboot.controller)控制层类,与前端交互

package top.bounds.springboot.controller;

import java.util.List;

import javax.annotation.Resource;

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 top.bounds.springboot.mapper.CategoryMapper;
import top.bounds.springboot.pojo.Category;

@Controller
public class BootController {
	@Resource
	CategoryMapper categoryMapper;

	/**
	 * 在参数里接受当前是第几页 start ,以及每页显示多少条数据 size。 默认值分别是0和5。
	 * 
	 * @param m
	 * @param start
	 * @param size
	 * @return
	 */
	@RequestMapping("/listCategory")
	public String listCategory(Model m, @RequestParam(value = "start", defaultValue = "0") int start,
			@RequestParam(value = "size", defaultValue = "1") int size) {
		// 根据start,size进行分页,并且设置id 倒排序
		PageHelper.startPage(start, size, "id desc");
		// 因为PageHelper的作用,这里就会返回当前分页的集合了
		List<Category> list = categoryMapper.findAll();
		// 根据返回的集合,创建PageInfo对象
		PageInfo<Category> page = new PageInfo<>(list);
		// 把PageInfo对象扔进model,以供后续显示
		m.addAttribute("page", page);
		// 跳转到listCategory.jsp
		return "listCategory";
	}

	/**
	 * 添加
	 * 
	 * @param category
	 * @return
	 */
	@RequestMapping("/addCategory")
	public String addCategory(Category category) {
		categoryMapper.save(category);
		return "redirect:listCategory";
	}

	/**
	 * 根据id删除
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/deleteCategory")
	public String deleteCategory(int id) {
		categoryMapper.delete(id);
		return "redirect:listCategory";
	}

	/**
	 * 按id查找
	 * 
	 * @param id
	 * @param m
	 * @return
	 */
	@RequestMapping("/findByIdCategory")
	public String findByIdCategory(int id, Model m) {
		Category category = categoryMapper.findById(id);
		m.addAttribute("category", category);
		return "modifyCategory";
	}

	/**
	 * 更新
	 * 
	 * @param category
	 * @return
	 */
	@RequestMapping("/updateCategory")
	public String updateCategory(Category category) {
		categoryMapper.update(category);
		return "redirect:listCategory";
	}

}

listCategory.jsp

用于展示查询到的所有数据(路径:src/main/webapp/WEB-INF/jsp)

<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="findByIdCategory?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>

modifyCategory.jsp

用于修改数据的界面(路径:src/main/webapp/WEB-INF/jsp)

<div style="margin: 0px auto; width: 500px">
	<form action="updateCategory" method="post">
		name: <input name="name" value="${category.name}"> <br> <input
			name="id" type="hidden" value="${category.id}">
		<button type="submit">提交</button>
	</form>
</div>

运行

运行Application.java然后访问http://127.0.0.1:8080/listCategory 即可看到效果

ps:本篇博客源码下载链接:https://pan.baidu.com/s/1FWz93VQWArO9FwkZSzYCYA 密码:227k
SpringBoot入门

在学习SSM(H)的过程中,需要做大量的配置工作,其实很多配置行为本身只是手段,并不是目的。 基于这个考虑,把该简化的简化,该省略的省略,开发人员只用关心提供业务功能就行了,这就是 SpringBoot。 换言之,SpringBoot可以简单地看成简化了的、按照约定开发的SSM(H)。 开发速度大大提升。

SpringBoot结合Thymeleaf

Spring boot不建议使用jsp开发web,本例子展示如何使用spring boot和Thymeleaf开发web项目。通过@URL 外部引用css 文件和 js 文件,Thymeleaf 的基本表达式,以及include的包含关系等

 发表评论