SpringBoot-Mybaitis

x33g5p2x  于2021-09-25 转载在 Spring  
字(9.6k)|赞(0)|评价(0)|浏览(283)

SpringBoot-Mybaitis

结构图

添加需要的Maven

我们使用目前市面上最快的连接池 也是Springboot默认的连接池HikariCP

<!--spring-boot -->
  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.6.RELEASE</version>
</parent>

<dependencies>
 <!--web相关依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--数据库驱动 告诉Springboot 我们使用什么数据库-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

        <!--jdbc的启动器,默认使用HikariCP连接池-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <version>2.3.0.RELEASE</version>
        </dependency>

	  <!--mybati 和Spring boot 自动整合依赖 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>

        <!--测试的起步依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>2.1.1.RELEASE</version>
            <scope>test</scope>
        </dependency>


    </dependencies>

然后就需要添加配置信息了 在yml配置文件中添加

配置端口号为80 如果不想配置这一步可以省略 默认为8080

server:
 port: 80

添加数据库配置信息

如果使用的是application.properties配置文件的话

spring.datasource.driverClassName=com.mysql.jdbc.Driver

spring.datasource.url: jdbc:mysql://localhost:3306/order?useUnicode=true&characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false

spring.datasource.username=root

spring.datasource.password=root

spring.datasource.hikari.idle-timeout=60000

spring.datasource.hikari.maximum-pool-size=30

spring.datasource.hikari.minimum-idle=10

如果使用的是application.yml 配置文件的话

spring:
  datasource:
    driverClassName: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/order?useUnicode=true&characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false&serverTimezone=UTC
    username: root
    password: root
    hikari.idle-timeout: 60000
    hikari.maximum-pool-size: 30
    hikari.minimum-idle: 10

添加Mybatis-Mapper配置

如果使用的是application.properties配置的话

#spring集成Mybatis环境

#实体类别名扫描包
mybatis.type-aliases-package=com.baidu.entity

# 加载Mybatis映射文件 classpath:mybaitis/**Mapper.xml 
# 代表是  resources下mybaitis包里(包括子层)所有是xxMapper.xml结尾的xml配置文件
# 

mybatis.mapper-locations=classpath:mybaitis/**Mapper.xml

# 开启将带有下划线的表字段 映射为驼峰格式的实体类属性
mybatis.configuration.map-underscore-to-camel-case=true

如果使用的是application.yml 配置文件的话

#spring集成Mybatis环境
#实体类别名扫描包 如果使用接口的话这个可以省略
# 加载Mybatis映射文件 classpath:mapper/*Mapper.xml 代表是 resources 下mapper包里所有是 ..Mapper.xml结尾的xml配置文件 如果使用接口的话这个可以省略

mybatis:
  type-aliases-package: com.baidu.entity
  mapper-locations: classpath:mybaitis/*Mapper.xml
  configuration:
  		map-underscore-to-camel-case: true

如果是多层目录可用这样(一般大点的项目下面这配置就够了)

mybatis:
  #实体类别名扫描包
  type-aliases-package: com.ddd.domain.**.entity
  # 加载Mybatis映射文件
  mapper-locations: classpath:mybaitis/**/*Mapper.xml
  configuration:
    # 开启将带有下划线的表字段 映射为驼峰格式的实体类属性
    map-underscore-to-camel-case: true

整合mybatis

准备阶段

Maven 上面都已经添加了

创建一个数据库voidme在数据库中创建一个表t_user的表 ,添加一些信息

创建一个User实体类

package com.baidu.entity;

public class User {
    private Integer id;
    private String userId;
    private String name;
    private String pass;
    private String age;
    private String sex;
    private String address;
    private String phone;

  // ..... Get SET tostring
}

编写Mapper

应为是学习所以xml和注解的方式都演示

注解的方式:

package com.baidu.dao;

import com.baidu.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface UserDao {
    @Select("SELECT * FROM t_user")
    List<User> queryAll(); //查询user表的全部数据
}

注意必须添加 @Mapper 否则就会发生找不到 Mapper的情况

xml的方式:

<?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.baidu.dao.UserDao">
    <!--查询全部数据条数-->
    <select id="userCount" resultType="Integer">
        SELECT COUNT(*) FROM t_user
    </select>

</mapper>

Service层

有很多人都喜欢使用 @Autowired自动装着 但是我比较喜欢是 指定装着 @Resource

这样能知道自己每一步到底干了啥

接口

package com.baidu.service;

import com.baidu.entity.User;

import java.util.List;

public interface UserService {

    List<User> queryAll(); //查询user表的全部数据
    Integer userCount(); //查询user表的全部语句的个数
}

实现类

package com.baidu.service.impl;

import com.baidu.dao.UserDao;
import com.baidu.entity.User;
import com.baidu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl  implements UserService {
    @Autowired
    private UserDao userDao;
    @Override
    public List<User> queryAll() {
        return userDao.queryAll();
    }

    @Override
    public Integer userCount() {
        return userDao.userCount();
    }

}

Controller层

package com.baidu.controller;

import com.baidu.entity.User;
import com.baidu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    //http://localhost:10101/user/queryAll
    @GetMapping("/queryAll")
    public ResponseEntity<List<User>>  queryAll(){
       return ResponseEntity.ok(userService.queryAll());
    }

    //http://localhost:10101/user/userCount
    @GetMapping("/userCount")
    public ResponseEntity<Integer>  userCount(){
        return ResponseEntity.ok(userService.userCount());
    }
}

引导类

package com.baidu;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class HelloAppllication {

    public static void main(String[] args) {
        SpringApplication.run(HelloAppllication.class,args);
    }
}

测试引导类

用来测试代码有没有问题的

package com.itheima.test;

import cn.boke.applliaction.TestAplliaction;
import cn.boke.entity.User;
import cn.boke.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestAplliaction.class)
public class MapperTest {
    @Resource(name = "UserServiceImpl")
    private UserService userService;

    @Test
    public void test() {
        List<User> users = userService.queryAll();
        System.out.println(users);
    }

}

测试

如果以上都配置了那么

就可以运行测试引导类了

这个没问题了 那么我们测试下Controller

运行引导类

运行成功后 我设置的是80端口

然后输入 http://localhost/queryUser

PageHeleper分页插件

<dependency>
 <groupId>com.github.pagehelper</groupId>
 <artifactId>pagehelper</artifactId>
 <version>5.1.2</version>
</dependency>
<dependency>
 <groupId>com.github.pagehelper</groupId>
 <artifactId>pagehelper-spring-boot-autoconfigure</artifactId>
 <version>1.2.3</version>
</dependency>
<dependency>
 <groupId>com.github.pagehelper</groupId>
 <artifactId>pagehelper-spring-boot-starter</artifactId>
 <version>1.2.3</version>
</dependency>

方式一:我们在application.yml(spring 需要读取的yml)中加入

pagehelper:
 helperDialect: mysql
 reasonable: true
 supportMethodsArguments: true
 params: count=countSql

方式二:在注解涵盖package下面新建PageHeleperConfig

@Configuration
public class PageHelperConfig {
 
 
 @Bean
 public PageHelper getPageHelper(){
 PageHelper pageHelper=new PageHelper();
 Properties properties=new Properties();
 properties.setProperty("helperDialect","mysql");
 properties.setProperty("reasonable","true");
 properties.setProperty("supportMethodsArguments","true");
 properties.setProperty("params","count=countSql");
 pageHelper.setProperties(properties);
 return pageHelper;
 }
 
}

然后你就可以使用pagehelper插件了

使用步骤:

controller

@Override
public PageInfo<Student> findAllUserByPageS(int pageNum, int pageSize) {
    // TODO Auto-generated method stub
    PageHelper.startPage(pageNum, pageSize);
    List<Student> lists = studentMapper.queryUserInfo();
    PageInfo<Student> pageInfo = new PageInfo<Student>(lists);
    return pageInfo;
 
}

Controller

@GetMapping("/testPageHelper1")
public PageInfo<Student> testPageHelper1(){
    PageInfo<Student> queryResult = studentService.findAllUserByPageS(1, 5);
    return queryResult;
}

返回信息大概格式

{
    "pageNum":1,    //当前页码
    "pageSize":50,	//每页个数
    "size":1,		//当前页个数
    "startRow":1,	//由第几条开始
    "endRow":1,		//到第几条结束
    "total":1,		//总条数
    "pages":1,		//总页数
    "list":[{"dateTime":"2020-03-21","operationType":1}],//查出出来的数据集合
    "prePage":0,				//上一页
    "nextPage":0,				//下一页
    "isFirstPage":true,			//是否为首页
    "isLastPage":true,			//是否为尾页
    "hasPreviousPage":false,	//是否有上一页
    "hasNextPage":false,		//是否有下一页
    "navigatePages":8,			//每页显示的页码个数
    "navigatepageNums":[1],		//首页
    "navigateFirstPage":1,		//尾页
    "navigateLastPage":1,		//页码数
    "firstPage":1,				
    "lastPage":1				
}

遇到的问题

警告问题: Establishing SSL connection without server’s identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be establishexxx…

意思就是现在mysql 必须使用SSL方式连接, 但是我们没有SSL连接 所以我们需要给他关闭了,不然老是提醒烦人

解决办法: 在数据库连接上添加 &useSSL=false
点赞 -收藏-关注-便于以后复习和收到最新内容有其他问题在评论区讨论-或者私信我-收到会在第一时间回复如有侵权,请私信联系我感谢,配合,希望我的努力对你有帮助^_^

相关文章