zoukankan      html  css  js  c++  java
  • SpringBoot学习笔记(6)Mybatis整合

    简介

    这篇文章主要介绍SpringBoot集成Mybatis,数据库连接池使用alibaba的druid。SpringBoot微服框架虽然可以支持集成mybaits后不使用xml文件来写sql,但是习惯了xml配置sql的也可以用xml来实现。实现上具体用什么方式并不重要,主要是搭建一遍,对框架的运转就比较清晰。本博客还是用xml的方式来实现Mybatis的sql编写,不用注解方式。

    pom文件配置

    <?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.2.0.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.meng</groupId>
        <artifactId>demo</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>db_demo</name>
        <description>Demo project for Spring Boot</description>
    
        <properties>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-jdbc</artifactId>
            </dependency>
            <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>
                <scope>runtime</scope>
            </dependency>
            <!--自定义连接池-->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.1.10</version>
            </dependency>
    
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.17</version>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
                <exclusions>
                    <exclusion>
                        <groupId>org.junit.vintage</groupId>
                        <artifactId>junit-vintage-engine</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    </project>
    

    SpringBoot配置文件

    spring:
      datasource:
        username: root
        password: 123456
        url: jdbc:mysql://192.168.0.157:3306/db1
        driver-class-name: com.mysql.cj.jdbc.Driver
        type: com.alibaba.druid.pool.DruidDataSource
    
        #   数据源其他配置
        #初始化大小,最小,最大
        initialSize: 5
        minIdle: 5
        maxActive: 20
        # 配置获取连接等待超时的时间
        maxWait: 60000
        # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
        timeBetweenEvictionRunsMillis: 60000
        # 配置一个连接在池中最小生存的时间,单位是毫秒
        minEvictableIdleTimeMillis: 300000
        validationQuery: SELECT 1 FROM DUAL
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
        #   配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
        filters: stat,wall,log4j
        maxPoolPreparedStatementPerConnectionSize: 20
        useGlobalDataSourceStat: true
        connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
    mybatis:
      config-location: classpath:mybatis/mybatis-config.xml
      mapper-locations: classpath:mybatis/mapper/*.xml

     

    然后开始创建实体类实现流程

    创建包:entity、mapper、controller。resource下创建mapping文件夹,用于写sql语句,也可以直接写在mapper的java文件中,下面直接贴代码

    Application

    @MapperScan("com.meng.demo.mapper") //扫描路径下面的接口
    @SpringBootApplication
    public class DbDemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(DbDemoApplication.class, args);
        }
    
    }

    javaBean对象

    public class EmployeePO {
        private Integer id;
        private String lastName;
        private String email;
        private Integer gender;
        private Integer d_id;

    Mapper

    public interface EmployeeMapper {
    
        public EmployeePO getById(Integer id);   //根据id查询
    
        public void insert(EmployeePO employeePO); //新增
    }

    Controller

    @RestController
    public class DemoController {
    
        @Autowired
        EmployeeMapper employeeMapper;
    
        @GetMapping("/emp/{id}")
        public EmployeePO getEmp(@PathVariable("id") Integer id){
            return employeeMapper.getById(id);
        }
    
        @GetMapping("/emp")
        public EmployeePO inset(EmployeePO employeePO){
            employeeMapper.insert(employeePO);
            return employeePO;
        }
    
    }
    

      

    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.meng.demo.mapper.EmployeeMapper">
    
        <select id="getById" resultType="com.meng.demo.entity.EmployeePO">
    		SELECT
    			a.*
    		FROM employee a
    		WHERE a.id = #{id}
    	</select>
    
    
        <insert id="insert" keyProperty="id" useGeneratedKeys="true">
    		insert into employee(lastName,email,gender,d_id)
    		values (#{lastName},#{email},#{gender},#{d_id})
    	</insert>
    
    </mapper>

    mybatis-config.xml配置文件

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <settings>
            <setting name="mapUnderscoreToCamelCase" value="true"/> <!-- 驼峰命名 -->
        </settings>
    </configuration>
    

    最终的架构

     最后测试启动

    在浏览器中输入:http://localhost:8080/emp?lastName=%E6%B5%8B%E8%AF%9505&email=55555@qq.com&gender=10&d_id=1   插入一条数据

     在浏览器中输入:http://localhost:8080/emp/5   查询一条数据

  • 相关阅读:
    MySql 分页存储过程
    Wireshark图解教程
    Android全局变量使用
    Memcache存储大数据的问题
    论这场云盘大战,以及各网盘的优劣
    [MySQL CPU]线上飙升800%,load达到12的解决过程
    一步一步写算法(之排序二叉树)
    platform_device与platform_driver
    SPOJ 130
    Java实现 蓝桥杯VIP 算法训练 奇偶判断
  • 原文地址:https://www.cnblogs.com/mengY/p/11733713.html
Copyright © 2011-2022 走看看