SpringBoot權限管理開發實戰2-集成MyBatis

1.添加依賴

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

關於依賴的版本,可以到項目官網查看,mybatis-spring-boot-starter的項目地址是https://github.com/mybatis/spring-boot-starter,readme裏可以看到版本匹配關係,tags裏可以看到版本號

2.添加代碼生成插件,使用的插件是MyBatis官方提供的MyBatis Generator

<plugin>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-maven-plugin</artifactId>
    <version>1.3.7</version>
    <configuration>
        <configurationFile>
            src/main/resources/mybatis/generatorConfig.xml
        </configurationFile>
        <overwrite>true</overwrite>
        <verbose>true</verbose>
    </configuration>
    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>
    </dependencies>
</plugin>

3.添加config包,在config包下創建Mybatis配置類

package cn.gintone.guard.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@Configuration
@MapperScan("cn.gintone.guard.**.dao")
public class MybatisConfig {
    @Autowired
    private DataSource dataSource;

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception{
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setTypeAliasesPackage("cn.gintone.guard.**.model");//掃描Model
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sessionFactoryBean.setMapperLocations(resolver.getResources("classpath*:**/sqlmap/*.xml"));//掃描映射文件
        return sessionFactoryBean.getObject();
    }
}

遇到了@MapperScan註解不識別的問題,修改mybatis-spring-boot-starter的版本號爲2.0.0,問題解決,再改回2.1.1還是可以用

4.修改application.yml,添加數據源配置

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/guard?useUnicode=true&zeroDateTimeBehavior=convertToNull&autoReconnect=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
    username: root
    password: 123456

5.創建數據表

DROP TABLE IF EXISTS `sys_user`;
CREATE TABLE `sys_user` (
  `id` bigint(20) NOT NULL COMMENT '編號',
  `name` varchar(50) NOT NULL COMMENT '用戶名',
  `nick_name` varchar(150) DEFAULT NULL COMMENT '暱稱',
  `avatar` varchar(150) DEFAULT NULL COMMENT '頭像',
  `password` varchar(100) DEFAULT NULL COMMENT '密碼',
  `salt` varchar(40) DEFAULT NULL COMMENT '加密鹽',
  `email` varchar(100) DEFAULT NULL COMMENT '郵箱',
  `mobile` varchar(100) DEFAULT NULL COMMENT '手機號',
  `status` tinyint(4) DEFAULT NULL COMMENT '狀態  0:禁用   1:正常',
  `dept_id` bigint(20) DEFAULT NULL COMMENT '機構ID',
  `create_by` varchar(50) DEFAULT NULL COMMENT '創建人',
  `create_time` datetime DEFAULT NULL COMMENT '創建時間',
  `last_update_by` varchar(50) DEFAULT NULL COMMENT '更新人',
  `last_update_time` datetime DEFAULT NULL COMMENT '更新時間',
  `del_flag` tinyint(4) DEFAULT '0' COMMENT '是否刪除  -1:已刪除  0:正常',
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`),
  UNIQUE KEY `nick_name_UNIQUE` (`nick_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用戶管理';

INSERT INTO `sys_user` VALUES ('1', 'admin', '超管', null, 'bd1718f058d8a02468134432b8656a86', 'YzcmCZNvbXocrsz9dm8e', '[email protected]', '13612345678', '1', '4', 'admin', '2020-09-19 11:11:11', 'admin', '2020-09-19 11:11:11', '0');

6.生成MyBatis模塊,包括Model,DAO,XML映射文件,手動編寫比較麻煩,使用上面配置的插件自動生成

在idea中找到生成命令,雙擊即可

7.編寫服務接口

package cn.gintone.guard.service.impl;

import cn.gintone.guard.dao.SysUserMapper;
import cn.gintone.guard.model.SysUser;
import cn.gintone.guard.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Override
    public List<SysUser> selectAll() {
        return sysUserMapper.selectAll();
    }
}

8.編寫控制器

package cn.gintone.guard.controller;

import cn.gintone.guard.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("user")
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;
    @GetMapping("/all")
    public Object selectAll(){
        return sysUserService.selectAll();
    }
}

9.運行測試

完整前後臺代碼託管在gitee上,地址 https://gitee.com/gintone/Guard

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章