栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Springboot集成mybatis(mybatis-plus,通用mapper等)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Springboot集成mybatis(mybatis-plus,通用mapper等)

集成mybatis 或者 mybatis-plus

第一步:依赖的导入pom.xml

①一定会有数据库驱动的依赖
版本太低的话(如5.1.47),在yml里面的驱动会加载不出来的


                mysql
                mysql-connector-java
                8.0.13
            

②mybatis/通用mapper/mybatis-plus , 三选一


            org.mybatis
            mybatis
            3.5.4



            
                tk.mybatis
                mapper-spring-boot-starter
                2.1.5
            


 
 
	com.baomidou 
	mybatis-plus-boot-starter
	3.0.5 

对于springboot项目可以导入下面这个mybatis依赖

  
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            2.1.4
        

spring:
  datasource:
    username: root
    password: zykj5717
    url: jdbc:mysql://183.62.240.92:3306/zycx_test?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useSSL=true&serverTimezone=Asia/Shanghai
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis:
  mapper-locations: classpath:mapper/*.xml

如果不能关联过去需要配置yml

mybatis:
  mapper-locations: classpath:mapper/*.xml

其他常用的依赖

    
        log4j
        log4j
        1.2.17
    
    
        junit
        junit
        4.12
        test
    
application.yml的配置
# mysql 5 驱动不同 com.mysql.jdbc.Driver 
# mysql 8  驱动不同 com.mysql.cj.jdbc.Driver、 
# mysql 8 需要增加时区的配置serverTimezone=GMT%2B8 

spring.datasource.username=root
spring.datasource.password=123456 spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus? useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

遇到了时区相差8小时的问题:
?serverTimezone=GMT%2B8
serverTimezone=Asia/Shanghai

使用

对于mybatis

传统方式pojo-dao(连接mybatis,配置mapper.xml文件)-service-controller

对于通用mapper

对于mybatis-plus

1、SQL谁帮我们写的 ? MyBatis-Plus 都写好了
2、方法哪里来的? MyBatis-Plus 都写好了

①在启动类上添加注解扫描

@MapperScan("com.kuang.mapper")

②mapper接口

package com.kuang.mapper;
import com.baomidou.mybatisplus.core.mapper.baseMapper;
import com.kuang.pojo.User;
import org.springframework.stereotype.Repository; 
// 在对应的Mapper上面继承基本的类 baseMapper
@Repository  // 代表持久层 
public interface UserMapper extends baseMapper { 
// 所有的CRUD操作都已经编写完成了 
// 你不需要像以前的配置一大堆文件了!
}

③使用

@SpringBootTest 
class MybatisPlusApplicationTests { 
// 继承了baseMapper,所有的方法都来自己父类
// 我们也可以编写自己的扩展方法! 
@Autowired private UserMapper userMapper; 
@Test void contextLoads() { 
// 参数是一个 Wrapper ,条件构造器,这里我们先不用 null 
// 查询全部用户 
List users = userMapper.selectList(null); users.forEach(System.out::println);
} 
}

④ 扩展:
我们所有的sql现在是不可见的,我们希望知道它是怎么执行的,所以我们必须要看日志!
如何配置日志呢?

配置日志 mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/703980.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号