springboot整合mybatis

 

1.先导入相关依赖:

<!-- mysql:MyBatis相关依赖 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-maven-plugin</artifactId>
            <version>1.4.0</version>
            <type>maven-plugin</type>
        </dependency>
        <!-- mysql:mysql驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        
        <!-- mysql:阿里巴巴数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.12</version>
        </dependency>

 

2.application.yml 配置:

spring: 
  application: 
    name: service-order
  redis:
    database: 0
    host: 127.0.0.1
    port: 6379
    timeout: 2000
    password:
    #数据库连接配置
  datasource: 
         #配置当前使用的数据源的操作类型
    type: com.alibaba.druid.pool.DruidDataSource                          
         #配置MySQL的驱动程序类
    driver-class-name: com.mysql.cj.jdbc.Driver                             
         #数据库连接地址
    url: jdbc:mysql://localhost:3306/ac-new?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
         #数据库连接用户名
    username: root                                                        
         #数据库连接密码
    password: root
         #进行数据库连接池的配置
    dbcp2:          
             #初始化提供的连接数                                                      
      initial-size: 5    
             #数据库连接池的最小维持连接数                                                 
      min-idle: 5          
             #最大的连接数                                               
      max-total: 5 
             #等待连接获取的最大超时时间                                                       
      max-wait-millis: 200                                                
      validation-query: SELECT 1
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
#自定义哨兵
sentinel:
  address:
    - 127.0.0.1:26379
    - 127.0.0.1:26479
    - 127.0.0.1:26579
  masterName: mymaster

#注册中心
eureka: 
  
  client:
    enabled: true
        #设置服务注册中心的URL
    service-url:
      defaultZone: http://localhost:7900/eureka/

#mybatis配置
mybatis:
  mapper-locations:
  - classpath:mapper/*.xml

 

 

3.编写模板 generatorConfigMySql.xml :

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration>
    <context id="MySqlContext" targetRuntime="MyBatis3Simple" defaultModelType="flat">
        <property name="beginingDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>
        <commentGenerator>
            <property name="supressDate" value="true"/>
            <property name="addRemarkComments" value="true"/>
        </commentGenerator>

        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/ac-new?serverTimezone=UTC&amp;useUnicode=true&amp;zeroDateTimeBehavior=convertToNull&amp;autoReconnect=true&amp;characterEncoding=utf8" userId="root"
                        password="root" >
        </jdbcConnection>
        <javaModelGenerator targetPackage="com....." targetProject="service\src\main\java\">
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <sqlMapGenerator targetPackage="mapper" targetProject="service\src\main\resources/"/>
        <javaClientGenerator type="XMLMAPPER" targetPackage="com...." targetProject="service\src\main\java\"/>
        <table tableName="SAVE"  domainObjectName="SaveInfo"/>
    </context>
</generatorConfiguration>

需要根据自身更改(参数说明一一对应): connectionURL: 数据库地址,端口号,数据库名称(localhost:3306/ac-new) userId: 数据库用户名 (root) password: 数据库密码 (root) targetPackage: 生成文件存放路径从java下的com文件夹开始(com.....) targetProject:从工程名到java目录,service是工程名(service\src\main\java\) targetProject:生成的XML存放路径,service是工程名(service\src\main\resources/) tableName: 数据库表名(SAVE) domainObjectName: 生成文件名(SaveInfo)

 

4.java 运行main函数生成文件:

package com....;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class GeneratorToSqlFile {

    public static void main(String[] args) throws Exception{
    
        List<String> warnings = new ArrayList<>();
        boolean overwrite = true;
        InputStream is = GeneratorToSqlFile.class.getResourceAsStream("/generatorConfigMySql.xml");
        if(is == null){
            System.out.println("null");
        }
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(is);
        is.close();
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);
        for(String warning : warnings){
            System.out.println(warning);
        }
        
    }
}


运行改方法共生成:

  1.带有get,set方法的 SaveInfo.java实体类 ,
  2.带有@Mapper注解的 SaveInfoMapper.java接口类 ,
  3.带有简单Sql语句的 SaveInfoMapper.xml配置类 三个文件
  (生成的xml,最好检查一下每个节点对应的路径

 

5.测试:
对数据库做简单的查询和写入

package com....controller;

import com.....SaveInfoMapper;
import com.....SaveInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;

@Controller
public class GetInfoByIdController {

    @Autowired
    private SaveInfoMapper saveInfoMapper;

    @GetMapping("/selSql")
    public void selSql(HttpServletRequest request,HttpServletResponse response) throws IOException {

         SaveInfo info = saveInfoMapper.selectInfoByid("001");
         String id = info.getId();
         String applyno = info.getApplyno();
         String address = info.getAddress();
         System.out.println(id);
         System.out.println(applyno);
         System.out.println(address);
         response.getWriter().print("$$$$$$");
    }

    @GetMapping("/InSql")
    public void InSql(HttpServletRequest request,HttpServletResponse response) throws IOException {
        Timestamp saveTime=new Timestamp(new Date().getTime());
        SaveInfo info = new SaveInfo();
        info.setId("002");
        info.setApplyno("004098020000002");
        info.setUserName("测试2");
        info.setUserNumber("002");
        info.setAddress("静安区");
        info.setSaveTime(saveTime);
        info.setType("Yes");
        info.setCount("count");
        int mu = saveInfoMapper.insert(info);
        response.getWriter().print(mu+"");
    }
}


简单查询 :
1.SaveInfoMapper里加个方法:SaveInfo selectInfoByid(String id);
2.SaveInfoMapper.xml里加个select节点:
<select id="selectInfoByid" parameterType="java.lang.String" resultMap="BaseResultMap">
select ID, APPLYNO, USER_NAME, USER_NUMBER, ADDRESS, SAVE_TIME, TYPE, COUNT, SAVE_BOLB,
SAVE_CLOB
from save
where id = #{id,jdbcType=VARCHAR}
</select>



结果:

控制台

 

页面 

 

 数据库

 

posted @ 2020-12-03 11:31  Li&Fan  阅读(144)  评论(0编辑  收藏  举报