五、springboot 使用 Mybatis

1、Mybatis 简介

MyBatis 支持定制化 SQL、存储过程以及高级映射,避免了 JDBC 代码和手动设置参数以及结果集的获取,使用简单的 XML 或注解来配置和映射原生信息,在国内mybatis的使用率很高,前面提到的jpa在国外使用较高一些

2、添加依赖

pom.xml中添加mybatis-spring-boot-starter的依赖,添加 mysql 的依赖

<!-- mybatis包 -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
</dependency>

<!-- MYSQL包 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

3、配置数据源,连接数据库

application.properties 中添加如下配置,连接数据库以及mybatis的相关设置

spring.datasource.url=jdbc:mysql://localhost:3306/wzp?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false
spring.datasource.password=root
spring.datasource.username=root

mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.wzp.wzx.*
# 驼峰命名规范 如:数据库字段是  order_id 那么 实体字段就要写成 orderId
mybatis.configuration.map-underscore-to-camel-case=true

4、构建一张数据表,用于测试

DROP TABLE IF EXISTS `admin`;
CREATE TABLE `admin`  (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `uid` int(11) NULL DEFAULT NULL,
  `username` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT '用户名',
  `password` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT '密码',
  `age` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
  `sex` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
  `tel` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
  `email` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 58 CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;

5、构建实体类

package com.wzp.wzx.admin.entity;

import lombok.Getter;
import lombok.Setter;

import javax.persistence.Entity;
import java.io.Serializable;

@Entity
@Getter
@Setter
public class Admin implements Serializable {
    private static final long serialVersionUID = -1493660405397259028L;

    private Integer id;
    private Integer uid;
    private String username;
    private String password;
    private String age;
    private String sex;
    private String tel;
    private String email;

}

6、构建mapper层

package com.wzp.wzx.admin.mapper;

import com.wzp.wzx.admin.entity.Admin;
import org.apache.ibatis.annotations.*;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;

import java.util.HashMap;
import java.util.List;

@Mapper
public interface AdminMapper {

    /**
     * 增加数据
     * 基于mybatis3.x版本后提供的注解方式 同理它还有@Update、@Delete、@Insert等等一系列注解
     *
     * @param admin
     * @return
     */
    @CacheEvict(value = "admin", allEntries = true)
    @Insert("insert into Admin(uid,username,password,age,sex,tel,email) VALUES (#{uid},#{username},#{password},#{age},#{sex},#{tel},#{email})")
    Admin save(Admin admin);

    /**
     * 根据id删除
     *
     * @param id
     */
    @CacheEvict(value = "admin", allEntries = true)
    @Delete("delete from Admin where id=#{id}")
    int deleteById(int id);

    /**
     * 根据id进行信息修改
     *
     * @param admin
     * @return
     */
    @CacheEvict(value = "admin", allEntries = true)
    @Update("update Admin set uid=#{uid},username=#{username},password=#{password},age=#{age},sex=#{sex},tel=#{tel},email=#{email} where id=#{id}")
    Admin update(Admin admin);

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @Cacheable(value = "admin")
    @Select("select * from Admin where id = #{id}")
    Admin findById(Integer id);

    /**
     * 查找所有
     *
     * @return
     */
    @Cacheable(value = "admin")
    @Select("select * from Admin")
    List<Admin> findAll();


    /**
     * 早期写法,将SQL写在 XML 中  示例往后看
     *
     * @param
     * @param
     * @param
     * @return
     */
    /*int insert1(Admin admin);

    int insert2(Admin admin);

    int deleteById1(Integer id);

    int updateById1(Admin admin);

    int updateById2(Admin admin);

    Admin findById1(Integer id);

    List<User> findAllUser();*/

    @Cacheable(value = "admin")
    List<Admin>findAllBySome(HashMap map);


}

        xml 文件 sql 示例

<!-- 条件查询 -->
    <select id="findAllBySome" parameterType="hashmap" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from Admin
        where 1=1
        <if test="uid != null and uid != '' ">
            AND uid Like CONCAT(CONCAT('%',#{uid, jdbcType=INTEGER},'%'))
        </if>
        <if test="username != null and username != ''">
            AND username Like CONCAT(CONCAT('%',#{username, jdbcType=VARCHAR},'%'))
        </if>
        <if test="age != null and age != '' ">
            AND age Like CONCAT(CONCAT('%',#{age, jdbcType=VARCHAR},'%'))
        </if>
        <if test="sex != null and sex != '' ">
            AND sex Like CONCAT(CONCAT('%',#{sex, jdbcType=VARCHAR},'%'))
        </if>
        <if test="tel != null and tel != '' ">
            AND tel Like CONCAT(CONCAT('%',#{tel, jdbcType=VARCHAR},'%'))
        </if>
        <if test="email != null and email != '' ">
            AND email Like CONCAT(CONCAT('%',#{email, jdbcType=VARCHAR},'%'))
        </if>
    </select>

7、来个Controller层,测试走一波

package com.wzp.wzx.admin.controller;

import com.github.pagehelper.PageInfo;
import com.wzp.wzx.admin.entity.Admin;
import com.wzp.wzx.admin.mapper.AdminMapper;
import com.wzp.wzx.config.BaseController;
import com.wzp.wzx.config.MD5Util;
import com.wzp.wzx.config.Result;
import com.wzp.wzx.enums.ErrorCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


@RestController
@CrossOrigin
@RequestMapping("/admin")
@Api(description = "后台相关管理接口")
public class AdminController extends BaseController {

    @Autowired
    private AdminMapper AdminMapper;


    @PostMapping("/findAll")
    public Result findAll(@RequestBody Map<String, String> parameters) {
        if (!hasParameter(parameters, "pageNumber") || !hasParameter(parameters, "pageSize") || !hasParameter(parameters, "propertiesAndSort")) {
            return Result.error(ErrorCodeEnum.MISSING_REQUIRED_ARGUMENTS);
        }
        pageRequest(parameters);
        HashMap<String, Object> map = new HashMap();
        if (hasParameter(parameters, "uid")) {
            map.put("uid", Integer.valueOf(parameters.get("uid")));
        }
        if (hasParameter(parameters, "username")) {
            map.put("username", parameters.get("username"));
        }
        if (hasParameter(parameters, "age")) {
            map.put("age", parameters.get("age"));
        }
        if (hasParameter(parameters, "sex")) {
            map.put("sex", parameters.get("sex"));
        }
        if (hasParameter(parameters, "tel")) {
            map.put("tel", parameters.get("tel"));
        }
        if (hasParameter(parameters, "email")) {
            map.put("email", parameters.get("email"));
        }
        PageInfo<Admin> tb_user = new PageInfo<>(this.AdminMapper.findAllBySome(map));
        return Result.ok(tb_user);
    }


}

测试结果就不写了,就那么回事,有兴趣的可以自己测测,当然,这里面涉及到很多我自己封装的东西,这里就不贴出来了,占地方......

8、结语

按照惯例写个结语,嗯...看了很多大佬的教程,结合我自己的总结了一波,当然了,不足之处请多包涵,也请多指教...如有雷同,也请多包涵......

注:如有需要,可自行转载,但是要加上原创作者及原文章链接哦...

发布了25 篇原创文章 · 获赞 28 · 访问量 5443

猜你喜欢

转载自blog.csdn.net/wzp12321/article/details/100689324