SpringBoot框架入门(二)
一、Mybatis整合
1.环境整合配置
(1)新建项目spring_mybatis
(2)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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.zgf</groupId>
<artifactId>springboot_mybatis</artifactId>
<version>1.0-SNAPSHOT</version>
<name>springboot_mybatis</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- mybatis 集成 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
<!-- springboot 分⻚插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.13</version>
</dependency>
<!-- mysql 驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- c3p0 数据源 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
(3)application.yml 整合配置
server:
# 设置项⽬启动的端⼝号
port: 8080
# 设置项⽬的访问路径(上下⽂路径)
servlet:
context-path: /springboot_mybatis
## 数据源配置
spring:
datasource:
type: com.mchange.v2.c3p0.ComboPooledDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
username: root
password: root
## mybatis 配置
mybatis:
mapper-locations: classpath:/mappers/ *.xml
type-aliases-package: com.xxxx.springboot.po
configuration:
## 下划线转驼峰配置
map-underscore-to-camel-case: true
## pageHelper
pagehelper:
helper-dialect: mysql
## 显示dao 执⾏sql语句
logging:
level:
com:
zgf:
springboot:
dao: debug
(4)源代码添加
JavaBean 对象定义
package com.zgf.springboot.po;
public class User {
private Integer id;
private String userName;
private String userPwd;
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 getUserPwd() {
return userPwd;
}
public void setUserPwd(String userPwd) {
this.userPwd = userPwd;
}
}
Dao层接口方法定义
package com.zgf.springboot.dao;
import com.zgf.springboot.po.User;
public interface UserMapper {
//用过用户名查询用户对象
User queryUserByUserName(String username);
}
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="com.zgf.springboot.dao.UserMapper">
<select id="queryUserByUserName" parameterType="String" resultType="com.zgf.springboot.po.User">
select
id,user_name,user_pwd
from
user
where
user_name = #{userName}
</select>
</mapper>
添加 service 、controller 对应代码
package com.zgf.springboot.service;
import com.zgf.springboot.dao.UserMapper;
import com.zgf.springboot.po.User;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service //交给IOC处理
public class UserService {
@Resource
public UserMapper userMapper;
public User queryUserByUserName(String userName) {
return userMapper.queryUserByUserName(userName);
}
}
package com.zgf.springboot.controller;
import com.zgf.springboot.po.User;
import com.zgf.springboot.service.UserService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
public class UserController {
@Resource
private UserService userService;
@GetMapping("/user/{userName}")
public User queryUserByUserName(@PathVariable String userName){
return userService.queryUserByUserName(userName);
}
}
添加应⽤启动⼊⼝
package com.zgf.springboot;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.zgf.springboot.dao")
public class Starter {
public static void main(String[] args) {
SpringApplication.run(Starter.class);
}
}
二、 SpringBoot 数据访问操作
1.查询操作
(1)定义接口
public interface UserMapper {
//通过用户ID查询用户对象
User queryUserById(Integer id);
}
(2)映射文件配置
<?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.zgf.springboot.dao.UserMapper">
<!-- 通过用户id查询用户对象-->
<select id="queryUserById" parameterType="int" resultType="com.zgf.springboot.po.User">
select
*
from
user
where
id = #{id,jdbcType = INTEGER}
</select>
</mapper>
(3) UserService
package com.zgf.springboot.service;
import com.zgf.springboot.dao.UserMapper;
import com.zgf.springboot.po.User;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service //交给IOC处理
public class UserService {
@Resource
public UserMapper userMapper;
/**
* 根据id查询对象
* @param id
* @return
*/
public User queryUserById(Integer id){
return userMapper.queryUserById(id);
}
}
(4) UserController
package com.zgf.springboot.controller;
@RestController
public class UserController {
@Resource
private UserService userService;
/**
* 通过用户Id查询对象
* @param userId
* @return
*/
@GetMapping("/user/${userId}")
public User queryUserById(@PathVariable Integer userId){
return userService.queryUserById(userId);
}
}
2.添加操作
(1)接口方法定义
public interface UserMapper {
// 添加⽤户
public int save(User user);
}
(2)映射文件配置
<!--添加用户-->
<insert id="save" parameterType="com.zgf.springboot.po.User">
insert into
user
(user_name,user_pwd)
values
(#{userName},#{userPwd})
</insert>
(3)添加 commons-lang3 依赖
<!-- commons-lang3 依赖-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
(4) AssertUtil工具类
package com.zgf.springboot.utils;
import com.zgf.springboot.exceptions.ParamsException;
public class AssertUtil {
/**
* 判断结果是否为true
* 如果结果为true,抛出异常
* @param flag
* @param msg
*/
public static void isTrue(Boolean flag, String msg){
if(flag){
throw new ParamsException(msg);
}
}
}
(5)ParamsException 自定义异常
package com.zgf.springboot.exceptions;
public class ParamsException extends RuntimeException{
private Integer code = 300;
private String msg = "参数异常!";
public ParamsException(){
super("参数异常!");
}
public ParamsException(String msg) {
super(msg);
this.msg = msg;
}
public ParamsException(Integer code) {
super("参数异常!");
this.code = code;
}
public ParamsException(Integer code, String msg) {
super(msg);
this.code = code;
this.msg = msg;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
(6)UserService
package com.zgf.springboot.service;
@Service //交给IOC处理
public class UserService {
@Resource
public UserMapper userMapper;
/**
* 根据用户名查询对象
* @param userName
* @return
*/
public User queryUserByUserName(String userName) {
return userMapper.queryUserByUserName(userName);
}
/**
* 根据id查询对象
* @param id
* @return
*/
public User queryUserById(Integer id){
return userMapper.queryUserById(id);
}
/**
* 添加用户
* @param user
*/
public void saveUser(User user){
AssertUtil.isTrue(StringUtils.isBlank(user.getUserName()),"用户名不能为空");
AssertUtil.isTrue(StringUtils.isBlank(user.getUserPwd()),"密码不能为空");
//用过用户名查询用户对象是否存在
User temp = userMapper.queryUserByUserName((user.getUserName()));
AssertUtil.isTrue(null != temp ,"该用户已存在");
AssertUtil.isTrue(userMapper.save(user) < 1,"添加用户失败");
}
}
(7)ResultInfo
package com.zgf.springboot.po.vo;
public class ResultInfo {
private Integer code = 200 ;
private String msg = "操作成功";
private Object result;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getResult() {
return result;
}
public void setResult(Object result) {
this.result = result;
}
}
(8)UserController
package com.zgf.springboot.controller;
@RestController
public class UserController {
@Resource
private UserService userService;
/**
* 添加
* @param user
* @return
*/
@PutMapping("/user")
public ResultInfo saveUser(User user){
ResultInfo resultInfo = new ResultInfo();
try {
userService.saveUser(user);
}catch (ParamsException e){
resultInfo.setCode(e.getCode());
resultInfo.setMsg(e.getMsg());
e.printStackTrace();
}catch (Exception e){
resultInfo.setCode(300);
resultInfo.setMsg("添加失败");
e.printStackTrace();
}
return resultInfo;
}
}
3.修改操作
(1)接口方法定义
public interface UserMapper {
// 修改⽤户
public int update(User user);
}
(2)映射文件配置
<update id="update" parameterType="com.xxxx.springboot.po.User">
update
tb_user
set
user_name =#{userName},user_pwd=#{userPwd}
where
id = #{id}
</update>
(3)UserService
package com.zgf.springboot.service;
@Service //交给IOC处理
public class UserService {
@Resource
public UserMapper userMapper;
/**
* 修改⽤户
* @param user
*/
public void updateUser(User user) {
AssertUtil.isTrue(StringUtils.isBlank(user.getUserName()), "⽤户名不能为空!");
AssertUtil.isTrue(StringUtils.isBlank(user.getUserPwd()),"⽤户密码不能为空!");
User temp = userMapper.queryUserByUserName(user.getUserName());
AssertUtil.isTrue(null != temp && !(temp.getId().equals(user.getId())), "该用户已存在!");
AssertUtil.isTrue(userMapper.update(user) < 1,"⽤户记录添加失败!");
}
}
(4)UserController
package com.zgf.springboot.controller;
@RestController
public class UserController {
@Resource
private UserService userService;
@GetMapping("/user/{userName}")
public User queryUserByUserName(@PathVariable String userName){
return userService.queryUserByUserName(userName);
}
/**
* 修改⽤户
* @param user
* @return
*/
@PostMapping("user")
public ResultInfo updateUser(@RequestBody User user){
ResultInfo resultInfo = new ResultInfo();
try {
userService.updateUser(user);
} catch (ParamsException e) {
e.printStackTrace();
resultInfo.setCode(e.getCode());
resultInfo.setMsg(e.getMsg());
}catch (Exception e) {
e.printStackTrace();
resultInfo.setCode(300);
resultInfo.setMsg("记录更新失败!");
}
return resultInfo;
}
}
4.删除操作
(1)接口方法定义
public interface UserMapper {
// 删除⽤户
public int deleteUserById(Integer id);
}
(2) 映射文件配置
<?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.zgf.springboot.dao.UserMapper">
<!--删除用户-->
<delete id="deleteUserById" parameterType="int">
delete from
user
where
id=#{id}
</delete>
</mapper>
(3) UserService
@Service //交给IOC处理
public class UserService {
@Resource
public UserMapper userMapper;
/**
* 删除⽤户
* @param id
*/
public void deleteUser(Integer id){
AssertUtil.isTrue(null == id || null == userMapper.queryById(id),"待删除记录不存在!");
AssertUtil.isTrue(userMapper.deleteUserById(id)<1,"⽤户删除失败!");
}
}
(4)UserController
@RestController
public class UserController {
@Resource
private UserService userService;
@GetMapping("/user/{userName}")
public User queryUserByUserName(@PathVariable String userName){
return userService.queryUserByUserName(userName);
}
/**
* 删除⽤户
* @param userId
* @return
*/
@DeleteMapping("user/{userId}")
public ResultInfo deleteUser(@PathVariable Integer userId){
ResultInfo resultInfo = new ResultInfo();
try {
userService.deleteUser(userId);
} catch (ParamsException e) {
e.printStackTrace();
resultInfo.setCode(e.getCode());
resultInfo.setMsg(e.getMsg());
}catch (Exception e) {
e.printStackTrace();
resultInfo.setCode(300);
resultInfo.setMsg("记录删除失败!");
}
return resultInfo;
}
}
5.分页条件查询操作
(1)UserQuery
package com.zgf.springboot.query;
public class UserQuery {
private Integer pageNum = 1; // 当前⻚
private Integer pageSize = 10; // 每⻚显示的数量
private String userName; // 查询条件:⽤户名
public Integer getPageNum() {
return pageNum;
}
public void setPageNum(Integer pageNum) {
this.pageNum = pageNum;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
(2) 接口方法定义
public interface UserMapper {
// 通过条件,分⻚查询⽤户列表
public List<User> selectByParams(UserQuery userQuery);
}
(3)映射文件配置
<?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.zgf.springboot.dao.UserMapper">
<!--分页查询-->
<select id="selectByParams" parameterType="com.zgf.springboot.query.UserQuery"
resultType="com.zgf.springboot.po.User">
select
*
from
user
<where>
<if test="null != userName and userName !=''">
and user_name like concat('%',#{userName},'%')
</if>
</where>
</select>
</mapper>
(4)UserService
package com.zgf.springboot.service;
@Service //交给IOC处理
public class UserService {
@Resource
public UserMapper userMapper;
/**
* 通过指定参数,分⻚查询⽤户列表
* @param userQuery
* @return
*/
public PageInfo<User> queryUserByParams(UserQuery userQuery){
PageHelper.startPage(userQuery.getPageNum(),userQuery.getPageSize());
return new PageInfo<User>(userMapper.selectByParams(userQuery));
}
}
(5)UserController
package com.zgf.springboot.controller;
@RestController
public class UserController {
@Resource
private UserService userService;
/**
* 通过指定参数,分⻚查询⽤户列表
* @param userQuery
* @return
*/
@GetMapping("user/list")
public PageInfo<User> list(UserQuery userQuery){
return userService.queryUserByParams(userQuery);
}
}
6.PostMan 工具下载与使用
PostMan 工具下载官网: https://www.postman.com/downloads/
测试:
(1)查询功能(2)添加功能
(3)修改功能
(4)删除功能
(5)分页查询