Spring Boot学习笔记——Spring Boot与MyBatis的集成(项目示例)

1.准备数据库环境

# 创建数据库
CREATE DATABASE IF NOT EXISTS zifeiydb DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
use zifeiydb;
# 创建一个名为tb_user的表
CREATE TABLE tb_user (
    id int(32) PRIMARY KEY AUTO_INCREMENT,
    username varchar(32),
    address varchar(256)
);
# 插入3条数据
INSERT INTO tb_user VALUES (1, 'zifeiy', 'zifeiy home');
INSERT INTO tb_user VALUES (2, 'zifeiy2', 'zifeiy corp');
INSERT INTO tb_user VALUES (3, 'zifeiy3', 'zifeiy girlfriend home');

2.创建项目,添加依赖

创建一个依赖于Web模块的Spring Boot项目,在项目的pom.xml中添加如下依赖配置信息。

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.1.1</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.11</version>
</dependency>

依赖下载地址:

  1. mybatis spring boot starter
  2. mysql kconnector java 我这里是8.0.11版本的,因为我电脑上面用的也是mysql 8版本。

在上面的配置代码中,mybatis-spring-boot-starter是Spring Boot中的Mybatis启动器配置,添加此依赖后,Spring Boot会将MyBatis所需的JAR包自动添加到项目中。
MySQL的驱动信息配置主要用于添加MySQL数据库驱动JAR包。

__注意:__期间遇到一个问题是项目的红叉,因为通过Spring Initializer生成的项目的pom.xml的开头是这样的:

<?xml version="1.0" encoding="UTF-8"?>
<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">

3.编写配置文件

在项目根目录下新建一个application.properties文件,并编写如下信息:

# DB Configuration
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/zifeiydb
spring.datasource.username=root
spring.datasource.password=password
# logging
logging.level.com.zifeiy.demo=debug

其中,DB中的username和password对应的是我的MySQL用户名和密码,zifeiydb是我MySQL中使用的数据库的名称,logging中的com.zifeiy.demo是我项目中的package名,使用时要做适当修改。

4.创建实体类

User.java:

package com.zifeiy.demo.po;

public class User {
	private Integer id;
	private String username;
	private String address;
	
	public User(Integer id, String username, String address) {
		super();
		this.id = id;
		this.username = username;
		this.address = address;
	}
	
	// getters and setters
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
}

5编写Mapper

在项目的src/main/java中创建com.zifeiy.demo.mapper包,并在该包中创建接口文件UserMapper:
UserMapper.java:

package com.zifeiy.demo.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import com.zifeiy.demo.po.User;

@Mapper
public interface UserMapper {
	// 查询所有用户
	@Select("select * from tb_user")
	List<User> getAllUsers();
	
	// 删除用户
	@Delete("DELETE FROM tb_user WHERE id=#{id}")
	void delete(Integer id);
}

在上述代码中,@Mapper是MyBatis框架用于声明Mapper接口的注解,@Select是用于映射查询SQL语句的注解,@Delete是用于映射删除SQL语句的注解。

6.编写Service

(1)编写接口。在项目的src/main/java中创建包com.zifeiy.demo.service,并在该包中茶ungjian接口文件UserService:
UserService.java:

package com.zifeiy.demo.service;

import java.util.List;

import com.zifeiy.demo.po.User;

public interface UserService {
	// 查询所有
	List<User> getAllUsers();
	// 删除所有
	void deleteUser(Integer id);
}

(2)编写实现类。在项目的src/main/java中创建包com.zifeiy.demo.service.impl,并在该包中创建UserService接口的实现类UserServiceImpl:
UserServiceImpl.java:

package com.zifeiy.demo.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 com.zifeiy.demo.mapper.UserMapper;
import com.zifeiy.demo.po.User;
import com.zifeiy.demo.service.UserService;

@Service
@Transactional
public class UserServiceImpl implements UserService {
	// 注入用户Mapper
	@Autowired
	private UserMapper UserMapper;
	
	// 查询所有用户
	@Override
	public List<User> getAllUsers() {
		return this.UserMapper.getAllUsers();
	}
	
	// 删除用户
	@Override
	public void deleteUser(Integer id) {
		System.out.println("删除了id为 " + id + " 的用户");
		this.UserMapper.delete(id);
	}
	
}

7.编写Controller

在项目的src/main/java中创建包com.zifeiy.demo.controller,并在该包中创建用户控制器类UserCOntroller:
UserController.java:

package com.zifeiy.demo.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.zifeiy.demo.po.User;
import com.zifeiy.demo.service.UserService;

@RestController
@RequestMapping("/user")
public class UserController {
	// 注入用户Service
	@Autowired
	private UserService userService;
	
	// 查询所有用户
	@RequestMapping("/userList")
	public List<User> getAllUsers() {
		List<User> list = this.userService.getAllUsers();
		return list;
	}
	
	// 删除用户
	@RequestMapping("/delete/{id}")
	public void delete(@PathVariable Integer id) {
		this.userService.deleteUser(id);
	}
	
}

8.实现前端框架

将Easy UI框架的资源文件拷贝到src/main/resources下的static文件夹中,,并在static文件夹中创建页面文件user.html:
user.html:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户信息 zifeiy</title>
<link rel="stylesheet" type="text/css" href="ui/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="ui/themes/icon.css">
<script type="text/javascript" src="ui/jquery.min.js"></script>
<script type="text/javascript" src="ui/jquery.easyui.min.js"></script>
<script type="text/javascript" src="ui/locale/easyui-lang-zh_CN.js"></script>
<script type="text/javascript">
	$(function() {
		$('#grid').datagrid({
			url: 'user/userList',
			fit: true,
			columns: [[
				{field: 'id', title: '编号', width: 50},
				{field: 'username', title: '姓名', width: 200},
				{field: 'address', title: '地址', width: 200},
				{field: 'del', title: '删除', width: 100}
			]]
		});
	});
</script>
</head>
<body>
<table id="grid"></table>
</body>
</html>

Jquery EasyUI下载地址:http://www.jeasyui.com/download/index.php

9.启动项目

启动Spring Boot项目,在浏览器地址栏中输入访问地址:http://localhost:8080/user.html后,浏览器现实效果如图:

启动方法:运行@SpringBootApplication注解对应的类就可以了。

posted @ 2018-05-16 22:17  zifeiy  阅读(285)  评论(0编辑  收藏  举报