IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> SpringBoot框架入门(二) -> 正文阅读

[Java知识库]SpringBoot框架入门(二)

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)分页查询
在这里插入图片描述

  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2022-01-28 11:45:25  更:2022-01-28 11:45:29 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/24 10:00:04-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码