springboot 整合 Mybatis (纯配置文件)

使用Maven配置 Eclipse环境 MySql数据库

  • 最近刚开始学习Spring框架
  • 然后也是第一次使用MyBatis和SpringBoot的整合
  • 从网上找了很多种方法 一直都搞不出来 最后终于成功了 所以写一下博客记录一下
  • 下面的代码里面我只写了SelectByPrimayKey的方法 其余的方法大同小异也就没有写了
  • 毕竟只是为了试验这两个框架的整合使用 如果需要的话可以自己动动手加上的
  • 然后有很多代码是从别的博客里面照搬的 不过东拼西凑的也没注意原作者到底是谁 所以也没写作者的名字
  • 如果有侵权请指正 我会马上删除或者写上出处

1.首先配置pom.xml

<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.tony</groupId>
    <artifactId>SecondMyBatisWithSB</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.2.3.RELEASE</version>
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <!-- commons -->
        <commons-io.version></commons-io.version>
        <commons-lang3.version>3.4</commons-lang3.version>
        <!-- springMvc -->
        <spring-jdbc.version>4.1.6.RELEASE</spring-jdbc.version>
        <spring-tx.version>4.1.6.RELEASE</spring-tx.version>
        <spring-web.version>4.1.6.RELEASE</spring-web.version>
        <spring-webmvc>4.1.6.RELEASE</spring-webmvc>
        <spring-data-japa.version>1.8.0.RELEASE</spring-data-japa.version>
        <spring-test.version>4.1.6.RELEASE</spring-test.version>
        <aspectjweaver.version>1.8.5</aspectjweaver.version>
        <webmvc.version>2.2.2.RELEASE</webmvc.version>
        <!-- myBatis -->
        <mybatis.version>3.2.8</mybatis.version>
        <mybatis-generator-core.version>1.3.2</mybatis-generator-core.version>
        <mybatis-spring.version>1.2.2</mybatis-spring.version>
        <mysql-connector-java.version>5.1.34</mysql-connector-java.version>
        <!-- mybatis pagehelper -->
        <pagehelper.version>3.6.3</pagehelper.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>${commons-lang3.version}</version>
        </dependency>
        <!-- datasource heroku -->
        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP-java6</artifactId>
            <exclusions>
                <exclusion>
                    <artifactId>tools</artifactId>
                    <groupId>com.sun</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- aspectJ -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
        </dependency>
        <!-- Spring boot -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- myBatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>${mybatis-spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>${mybatis-generator-core.version}</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- mybatis pagehelper -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>${pagehelper.version}</version>
        </dependency>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-rest-webmvc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-commons</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.hateoas</groupId>
            <artifactId>spring-hateoas</artifactId>
        </dependency>
        <!-- javax -->
        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
        </dependency>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>javax.servlet.jsp.jstl</artifactId>
            <version>1.2.2</version>
        </dependency>
    </dependencies>
    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.mybatis.generator</groupId>
                    <artifactId>mybatis-generator-maven-plugin</artifactId>
                    <version>1.3.2</version>
                    <configuration>
                        <configurationFile>src/main/resources/mybatis-generator-config.xml</configurationFile>
                        <verbose>true</verbose>
                        <overwrite>true</overwrite>
                    </configuration>
                    <executions>
                        <execution>
                            <id>Generate MyBatis Artifacts</id>
                            <goals>
                                <goal>generate</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <source>1.7</source>
                        <target>1.7</target>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>

</project>
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183

2.配置application.yml 放置在resources文件夹下即可

# Server settings
server:
    port:8080
    address:localhost

# DATASOURCE
jdbc:
    dataSourceClassName: com.mysql.jdbc.jdbc2.optional.MysqlDataSource
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&amp;charaterEncoding=utf-8
    databaseName: test
    serverName: 127.0.0.1
    username: root
    password: root
    cachePrepStmts: true
    prepStmtsSize: 250
    prepStmtsCacheSqlLimit: 2048
    userServerPrepStmts: true

# SPRING PROFILES
spring:       
    # HTTP ENCODING
    http:
        encoding.charset: UTF-8
        encoding.enable: true
        encoding.force: true

# MyBatis
mybatis:
    typeAliasesPackage: com.tony.entity
    mapperLocations: classpath:/com/tony/mapper/*.xml
    configLocation: classpath:/mybatis-config.xml

# LOGGING
logging:
    level:
       com.ibatis:DEBUG
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

3.配置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>
    <properties>
        <property name="dialect" value="mysql" />
    </properties>
    <settings>
        <!-- 这个配置使全局的映射器启用或禁用缓存。系统默认值是true,设置只是为了展示出来 -->
        <setting name="cacheEnabled" value="true" />
        <!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载。 系统默认值是true,设置只是为了展示出来 -->
        <setting name="lazyLoadingEnabled" value="true" />
        <!-- 允许或不允许多种结果集从一个单独的语句中返回(需要适合的驱动)。 系统默认值是true,设置只是为了展示出来 -->
        <setting name="multipleResultSetsEnabled" value="true" />
        <!--使用列标签代替列名。不同的驱动在这方便表现不同。参考驱动文档或充分测试两种方法来决定所使用的驱动。 系统默认值是true,设置只是为了展示出来 -->
        <setting name="useColumnLabel" value="true" />
        <!--允许 JDBC 支持生成的键。需要适合的驱动。如果设置为 true 则这个设置强制生成的键被使用,尽管一些驱动拒绝兼容但仍然有效(比如 
            Derby)。 系统默认值是false,设置只是为了展示出来 -->
        <setting name="useGeneratedKeys" value="false" />
        <!--配置默认的执行器。SIMPLE 执行器没有什么特别之处。REUSE 执行器重用预处理语句。BATCH 执行器重用语句和批量更新 系统默认值是SIMPLE,设置只是为了展示出来 -->
        <setting name="defaultExecutorType" value="SIMPLE" />
        <!--设置超时时间,它决定驱动等待一个数据库响应的时间。 系统默认值是null,设置只是为了展示出来 -->
        <setting name="defaultStatementTimeout" value="25000" />
    </settings>
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageHelper">
            <property name="dialect" value="mysql" />
            <property name="offsetAsPageNum" value="true" />
            <property name="rowBoundsWithCount" value="true" />
            <property name="pageSizeZero" value="true" />
            <property name="reasonable" value="true" />
        </plugin>
    </plugins>
</configuration>
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

4.配置mybatis-generator.properties

  • 这个是用来配置自动生成mapper.xml\dao\entity用的配置文件
#=============================#
#======database setting=======#
#=============================#

# mysql database setting
jdbc.type=mysql
jdbc.driverClassName:com.mysql.jdbc.Driver
jdbc.url:jdbc:mysql://127.0.0.1:3306/xxx?useUnicode=true&amp;characterEncoding=utf-8&allowMultiQueries=true
jdbc.username=root
jdbc.password=fixture

# pool settings
jdbc.pool.minIdle=8
jdbc.pool.maxActive=100

# mybatis generator setting
generator.classPath=C:/Users/TonyJiang/.m2/repository/mysql/mysql-connector-java/5.1.38/mysql-connector-java-5.1.38.jar
generator.mapperConfigFilename=mapper-config.xml
generator.targetProject=SecondMyBatisWithSB
generator.domainPackage=com.tony.entity
generator.mapperPackage=com.tony.mapper
generator.daoPackage=com.tony.dao

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

5.配置mybatis-generator-config.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>
    <!-- 引入配置文件 -->
    <properties resource="mybatis-generator.properties" />
    <!-- 指定数据连接驱动jar地址 -->
    <classPathEntry location="${generator.classPath}" />
    <!-- 一个数据库一个context -->
    <context id="BuildingTables" targetRuntime="Mybatis3">
        <!-- defaultModelType="hierarchical" -->
        <property name="javaFileEncoding" value="UTF-8" />
        <property name="suppressTypeWarnings" value="true" />

        <plugin type="org.mybatis.generator.plugins.SerializablePlugin" />
        <plugin type="org.mybatis.generator.plugins.CaseInsensitiveLikePlugin" />
        <plugin type="org.mybatis.generator.plugins.RowBoundsPlugin" />
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin" />
        <plugin type="org.mybatis.generator.plugins.CachePlugin" />


        <plugin type="org.mybatis.generator.plugins.MapperConfigPlugin">
            <property name="fileName" value="${generator.mapperConfigFilename}" />
            <property name="targetPackage" value="${generator.mapperPackage}" />
            <property name="targetProject"
                value="${generator.targetProject}/src/main/java" />
        </plugin>
        <plugin type="org.mybatis.generator.plugins.RenameExampleClassPlugin">
            <property name="searchString" value="Example$" />
            <property name="replaceString" value="Criteria" />
        </plugin>

        <!-- 注释 -->
        <commentGenerator>
            <property name="suppressAllComments" value="true" /><!-- 是否取消注释 -->
            <property name="suppressDate" value="true" /> <!-- 是否生成注释代时间戳 -->
        </commentGenerator>

        <!-- jdbc连接 -->
        <jdbcConnection driverClass="${jdbc.driverClassName}"
            connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}" />
        <!-- 类型转换 -->
        <javaTypeResolver>
            <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!-- 生成实体类地址 -->
        <javaModelGenerator targetPackage="${generator.domainPackage}"
            targetProject="${generator.targetProject}/src/main/java">
            <!-- 是否在当前路径下新加一层schema,eg:fase路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
            <property name="enableSubPackages" value="true" />
            <!-- 是否针对string类型的字段在set的时候进行trim调用 -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <!-- 生成mapxml文件 -->
        <sqlMapGenerator targetPackage="${generator.mapperPackage}"
            targetProject="${generator.targetProject}/src/main/java">
            <!-- 是否在当前路径下新加一层schema,eg:fase路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <!-- 生成mapxml对应client,也就是接口dao -->
        <javaClientGenerator targetPackage="${generator.daoPackage}"
            targetProject="${generator.targetProject}/src/main/java" type="XMLMAPPER">
            <!-- 是否在当前路径下新加一层schema,eg:fase路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>

        <!-- 配置表信息 -->
        <table tableName="t_user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" 
            enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>  

    </context>
</generatorConfiguration>  
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 之后用mybatis-generator的插件自动生成相应的mapper dao接口 entity既可
  • 具体方法可以先百度 相对来说比较简单的
  • 或者也可以手写一下 毕竟刚开始学手写更能熟悉那些结构-
  • 生成之后还是需要在修改一下的 修改的主要内容在后续代码中

6.下面开始代码部分


  • 首先是Application.java
  • 必须放在主包下面 这样才能成功扫描所有的包
  • 比如我是放在com.tony下面
package com.tony;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan
@EnableAutoConfiguration
@SpringBootApplication
public class Application {
    public static void main(String[] args){
        SpringApplication.run(Application.class, args);
    }
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

  • 然后是controller层 先测试一下SpringBoot能不能运行
  • com.tony.controller
package com.tony.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.tony.service.UserService;

@Controller
@RequestMapping("/test")
public class TestAction {

    @Autowired
    private UserService userService;
    @RequestMapping("/greeting")
    @ResponseBody
    public Object hello(){
        return "Hello Spring";
    }
    @ResponseBody
    @RequestMapping("/user")
    public Object get(@RequestParam String id){
        return userService.findOne(id);
    }
}

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

下面是自动生成的那几个部分 
- com.tony.dao 
- com.tony.mapper 
- com.tony.entity 
不过其实我是修改过的 不是原来自动生成的那些

UserMapper.java

package com.tony.dao;

import com.tony.entity.User;
import com.tony.commons.dao.BaseDao;

public interface UserMapper extends BaseDao<User, String>{

}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

User.java

package com.tony.entity;

import java.io.Serializable;

import com.tony.commons.entity.AbstractEntity;

public class User extends AbstractEntity implements Serializable {
    private String id;

    private String username;

    private String password;

    private static final long serialVersionUID = 1L;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id == null ? null : id.trim();
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username == null ? null : username.trim();
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(getClass().getSimpleName());
        sb.append(" [");
        sb.append("Hash = ").append(hashCode());
        sb.append(", id=").append(id);
        sb.append(", username=").append(username);
        sb.append(", password=").append(password);
        sb.append(", serialVersionUID=").append(serialVersionUID);
        sb.append("]");
        return sb.toString();
    }
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53

UserMapper.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.tony.dao.UserMapper" >
  <resultMap id="BaseResultMap" type="com.tony.entity.User" >
    <id column="id" property="id" jdbcType="VARCHAR" />
    <result column="username" property="username" jdbcType="VARCHAR" />
    <result column="password" property="password" jdbcType="VARCHAR" />
    <result column="create_by" property="createBy" jdbcType="VARCHAR" />
    <result column="create_date" property="createDate" jdbcType="DATE" />
    <result column="last_modified_by" property="lastModifiedBy" jdbcType="VARCHAR" />
    <result column="last_modified_date" property="lastModifiedDate" jdbcType="DATE" />
  </resultMap>


  <sql id="Base_Column_List" >
    id, username, password, create_by, create_date, last_modified_by, last_modified_date
  </sql>

  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String" >
    select 
    <include refid="Base_Column_List" />
    from t_user
    where id = #{id,jdbcType=VARCHAR}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.String" >
    delete from t_user
    where id = #{id,jdbcType=VARCHAR}
  </delete>

  <insert id="insert" parameterType="com.tony.entity.User" >
    insert into t_user (id, username, password, 
      create_by, create_date, last_modified_by, 
      last_modified_date)
    values (#{id,jdbcType=VARCHAR}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 
      #{createBy,jdbcType=VARCHAR}, #{createDate,jdbcType=DATE}, #{lastModifiedBy,jdbcType=VARCHAR}, 
      #{lastModifiedDate,jdbcType=DATE})
  </insert>
  <insert id="insertSelective" parameterType="com.tony.entity.User" >
    insert into t_user
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="username != null" >
        username,
      </if>
      <if test="password != null" >
        password,
      </if>
      <if test="createBy != null" >
        create_by,
      </if>
      <if test="createDate != null" >
        create_date,
      </if>
      <if test="lastModifiedBy != null" >
        last_modified_by,
      </if>
      <if test="lastModifiedDate != null" >
        last_modified_date,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=VARCHAR},
      </if>
      <if test="username != null" >
        #{username,jdbcType=VARCHAR},
      </if>
      <if test="password != null" >
        #{password,jdbcType=VARCHAR},
      </if>
      <if test="createBy != null" >
        #{createBy,jdbcType=VARCHAR},
      </if>
      <if test="createDate != null" >
        #{createDate,jdbcType=DATE},
      </if>
      <if test="lastModifiedBy != null" >
        #{lastModifiedBy,jdbcType=VARCHAR},
      </if>
      <if test="lastModifiedDate != null" >
        #{lastModifiedDate,jdbcType=DATE},
      </if>
    </trim>
  </insert>


  <update id="updateByPrimaryKeySelective" parameterType="com.tony.entity.User" >
    update t_user
    <set >
      <if test="username != null" >
        username = #{username,jdbcType=VARCHAR},
      </if>
      <if test="password != null" >
        password = #{password,jdbcType=VARCHAR},
      </if>
      <if test="createBy != null" >
        create_by = #{createBy,jdbcType=VARCHAR},
      </if>
      <if test="createDate != null" >
        create_date = #{createDate,jdbcType=DATE},
      </if>
      <if test="lastModifiedBy != null" >
        last_modified_by = #{lastModifiedBy,jdbcType=VARCHAR},
      </if>
      <if test="lastModifiedDate != null" >
        last_modified_date = #{lastModifiedDate,jdbcType=DATE},
      </if>
    </set>
    where id = #{id,jdbcType=VARCHAR}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.tony.entity.User" >
    update t_user
    set username = #{username,jdbcType=VARCHAR},
      password = #{password,jdbcType=VARCHAR},
      create_by = #{createBy,jdbcType=VARCHAR},
      create_date = #{createDate,jdbcType=DATE},
      last_modified_by = #{lastModifiedBy,jdbcType=VARCHAR},
      last_modified_date = #{lastModifiedDate,jdbcType=DATE}
    where id = #{id,jdbcType=VARCHAR}
  </update>

  <cache />
</mapper>
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125

接下来是一些需要自己写的 
com.tony.commons.dao 
BaseDao.java

package com.tony.commons.dao;

import java.io.Serializable;

public interface BaseDao<T extends Serializable , ID extends Serializable> {
    int deleteByPrimaryKey(ID id);

    int insert(T record);

    int insertSelective(T record);


    T selectByPrimaryKey(ID id);


    int updateByPrimaryKeySelective(T record);

    int updateByPrimaryKey(T record);
}

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

com.tony.commons.entity 
AbstractEntity.java

package com.tony.commons.entity;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.MappedSuperclass;
import javax.validation.constraints.NotNull;

import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;


@MappedSuperclass
public abstract class AbstractEntity implements  Serializable {

    private static final long serialVersionUID = 1L;

    private String id;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @CreatedBy
    @NotNull
    private String createBy;

    @CreatedDate
    @NotNull
    private Date createDate = new Date();

    @LastModifiedBy
    private String lastModifiedBy;

    @LastModifiedDate
    private Date lastModifiedDate = new Date();



    public String getCreateBy() {
        return createBy;
    }

    public void setCreateBy(String createBy) {
        this.createBy = createBy;
    }



    public Date getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }

    public String getLastModifiedBy() {
        return lastModifiedBy;
    }

    public void setLastModifiedBy(String lastModifiedBy) {
        this.lastModifiedBy = lastModifiedBy;
    }

    public Date getLastModifiedDate() {
        return lastModifiedDate;
    }

    public void setLastModifiedDate(Date lastModifiedDate) {
        this.lastModifiedDate = lastModifiedDate;
    }
}

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80

com.tony.commons.service 
BaseService.java

package com.tony.commons.service;

import java.io.Serializable;

public interface BaseService<T extends Serializable> {


    T findOne(String id);

}

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

com.tony.commons.service.impl 
BaseServiceImpl.java

package com.tony.commons.service.impl;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.tony.commons.dao.BaseDao;
import com.tony.commons.entity.AbstractEntity;
import com.tony.commons.service.BaseService;

@Transactional
public abstract class BaseServiceImpl<T extends AbstractEntity>
        implements BaseService<T> {

    protected abstract BaseDao<T,  String> getDao();

    protected Class<T> entityClazz;


    @SuppressWarnings("unchecked")
    public BaseServiceImpl() {
        Type genType = getClass().getGenericSuperclass();
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        entityClazz = (Class<T>) params[0];
    }



    @Transactional(readOnly = true)
    public T findOne(String id) {
        Assert.notNull(id);
        return getDao().selectByPrimaryKey(id);
    }

}

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38

com.tony.service 
UserService.java

package com.tony.service;

import com.tony.entity.User;
import com.tony.commons.service.BaseService;

public interface UserService extends BaseService<User> {
    User findOneById(String Id);
}

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

com.tony.service.impl 
UserServiceImpl.java

package com.tony.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.tony.dao.UserMapper;
import com.tony.entity.User;
import com.tony.service.UserService;
import com.tony.commons.dao.BaseDao;
import com.tony.commons.service.impl.BaseServiceImpl;

@Service
@Transactional
public class UserServiceImpl extends BaseServiceImpl<User>
        implements UserService {

    @Autowired
    private UserMapper userDao;


    public User findOneById(String Id) {
        return getDao().selectByPrimaryKey(Id);
    }


    @Override
    protected BaseDao<User, String> getDao() {
        return userDao;
    }
}

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

下面两个是Mybatis的配置类 
com.tony.config.mybatis 
DataBaseConfiguration.java

package com.tony.config.mybatis;

import java.util.Arrays;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.ApplicationContextException;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

@Configuration
@EnableTransactionManagement
public class DataBaseConfiguration implements EnvironmentAware {

    private RelaxedPropertyResolver propertyResolver;

    private static Logger log = LoggerFactory
            .getLogger(DataBaseConfiguration.class);

    private Environment env;

    public void setEnvironment(Environment env) {
        this.env = env;
        this.propertyResolver = new RelaxedPropertyResolver(env, "jdbc.");
    }

    @Bean(destroyMethod = "shutdown")
    public DataSource dataSource() {
        log.debug("Configruing DataSource");
        if (propertyResolver.getProperty("url") == null
                && propertyResolver.getProperty("databaseName") == null) {
            log.error("Your database conncetion pool configuration is incorrct ! The application "
                    + "cannot start . Please check your jdbc");
            Arrays.toString(env.getActiveProfiles());
            throw new ApplicationContextException(
                    "DataBase connection pool is not configured correctly");
        }
        HikariConfig config = new HikariConfig();
        config.setDataSourceClassName(propertyResolver
                .getProperty("dataSourceClassName"));
        if (propertyResolver.getProperty("url") == null
                || "".equals(propertyResolver.getProperty("url"))) {
            config.addDataSourceProperty("databaseName",
                    propertyResolver.getProperty("databaseName"));
            config.addDataSourceProperty("serverName",
                    propertyResolver.getProperty("serverName"));
        } else {
            config.addDataSourceProperty("url",
                    propertyResolver.getProperty("url"));
        }
        config.setUsername(propertyResolver.getProperty("username"));
        config.setPassword(propertyResolver.getProperty("password"));
        if ("com.mysql.jdbc.jdbc2.optional.MysqlDataSource"
                .equals(propertyResolver.getProperty("dataSourceName"))) {
            config.addDataSourceProperty("cachePrepStmts",
                    propertyResolver.getProperty("cachePrepStmts"));
            config.addDataSourceProperty("prepStmtCacheSize",
                    propertyResolver.getProperty("prepStmtsCacheSize"));
            config.addDataSourceProperty("prepStmtCacheSqlLimit",
                    propertyResolver.getProperty("prepStmtCacheSqlLimit"));
            config.addDataSourceProperty("userServerPrepStmts",
                    propertyResolver.getProperty("userServerPrepStmts"));
        }
        return new HikariDataSource(config);
    }

}

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75

MybatisConfiguration.java

package com.tony.config.mybatis;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@ConditionalOnClass({ EnableTransactionManagement.class, EntityManager.class })
@AutoConfigureAfter({ DataBaseConfiguration.class })
@MapperScan(basePackages={"com.tony.dao"})
public class MybatisConfiguration implements EnvironmentAware {

    private static Log logger = LogFactory.getLog(MybatisConfiguration.class);

    private RelaxedPropertyResolver propertyResolver;

    @Inject
    private DataSource dataSource;

    public void setEnvironment(Environment environment) {
        this.propertyResolver = new RelaxedPropertyResolver(environment,
                "mybatis.");
    }

    @Bean
    @ConditionalOnMissingBean
    public SqlSessionFactory sqlSessionFactory() {
        try {
            SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
            sessionFactory.setDataSource(dataSource);
            sessionFactory.setTypeAliasesPackage(propertyResolver
                    .getProperty("typeAliasesPackage"));
            sessionFactory
                    .setMapperLocations(new PathMatchingResourcePatternResolver()
                            .getResources(propertyResolver
                                    .getProperty("mapperLocations")));
            sessionFactory
                    .setConfigLocation(new DefaultResourceLoader()
                            .getResource(propertyResolver
                                    .getProperty("configLocation")));

            return sessionFactory.getObject();
        } catch (Exception e) {
            logger.warn("Could not confiure mybatis session factory");
            return null;
        }
    }

    @Bean
    @ConditionalOnMissingBean
    public DataSourceTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring Boot整合MyBatis配置文件主要包括以下几个方面: 1. 数据库连接配置 在application.properties或application.yml中配置数据库连接信息,包括数据库URL、用户名、密码等。 2. MyBatis配置 在application.properties或application.yml中配置MyBatis的相关配置,包括Mapper扫描路径、MyBatis配置文件路径等。 3. 数据源配置 在Spring Boot中,可以使用自带的数据源或者第三方数据源,如Druid、HikariCP等。需要在配置文件配置数据源相关信息。 4. Mapper配置MyBatis中,需要配置Mapper接口和Mapper.xml文件的对应关系。可以使用@MapperScan注解或者在MyBatis配置文件配置。 以上是Spring Boot整合MyBatis的主要配置文件内容,具体实现可以参考Spring Boot官方文档或者相关教程。 ### 回答2: Spring Boot是一个基于Spring框架的快速开发Java Web应用的工具。而Mybatis是一个优秀的持久层框架。在实际开发中,很多项目会将Spring Boot和Mybatis集成起来使用,这样可以使开发更加高效,代码更加简洁。下面我将介绍Spring Boot整合Mybatis配置步骤。 1.添加依赖 在pom.xml中加入Spring Boot和Mybatis的依赖。 ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.6</version> </dependency> ``` 2.设置数据源 在application.properties中设置数据源参数,包括数据库名称、用户名、密码等等。 ``` spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&autoReconnect=true spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver ``` 3.配置Mybatis 在resources目录下新建mybatis文件夹,在其中创建一些必要的配置文件,如SqlMapper.xml、mybatis-config.xml、Application.yml等。 a、SqlMapper.xml 配置连接mysql并定义Mapper操作的SQL语句,可以通过namespace来设置映射接口。在这里我们可以看到它是里面是调用的映射接口 ID。 ``` <?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.nian.springboot.mapper.StudentMapper"> <select id="selectByPrimaryKey" resultType="com.nian.springboot.pojo.Student"> select * from student where id = #{id,jdbcType=INTEGER} </select> </mapper> ``` b、mybatis-config.xml mybatis-config.xml用于配置Mybatis相关信息。 ``` <?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="logImpl" value="LOG4J"/> </settings> <typeAliases> <typeAlias type="com.nian.springboot.pojo.Student" alias="Student"/> </typeAliases> <mappers> <mapper resource="mapper/StudentMapper.xml"/> </mappers> </configuration> ``` c、Application.yml 在resources目录下新建application.yml文件,用于设置Spring Boot应用程序的配置,包括服务器端口、运行环境等。 ``` spring: servlet: multipart: max-file-size: 10MB max-request-size: 100MB async: request-timeout: 60000 datasource: url: jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=false username: root password: root driver-class-name: com.mysql.jdbc.Driver mybatis: config-location: classpath:mybatis/mybatis-config.xml mapper-locations: classpath*:mapper/**/*.xml type-aliases-package: com.nian.springboot.pojo ``` 4.创建mapper 创建mapper文件夹,并创建映射接口,如StudentMapper.java。 ``` public interface StudentMapper { Student selectByPrimaryKey(Integer id); } ``` 5.创建entity 创建实体类,映射数据库中的表,如Student.java。 ``` public class Student { private Integer id; private String name; private Integer age; private String sex; //getter setter } ``` 6.创建service 创建service,实现业务逻辑,如StudentService.java。 ``` @Service public class StudentService { @Autowired private StudentMapper studentMapper; public Student selectByPrimaryKey(Integer id) { return studentMapper.selectByPrimaryKey(id); } } ``` 7.创建Controller 创建Controller接口,处理请求,如StudentController.java。 ``` @RestController @RequestMapping("/student") public class StudentController { @Autowired private StudentService studentService; @RequestMapping(value = "/selectByPrimaryKey", method = RequestMethod.GET) public Student selectByPrimaryKey(@RequestParam("id") Integer id) { return studentService.selectByPrimaryKey(id); } } ``` 以上就是Spring Boot整合Mybatis的大致步骤,当然,具体实现跟业务有关。可以先按照这个框架搭建结构,再根据具体业务逻辑进行扩展和修改。整合后,我们就可以用Spring Boot和Mybatis在数据库中进行数据的 CRUD(增删改查) 操作了。 ### 回答3: Spring Boot 是一个基于 Spring 框架的快速开发框架,它具有简单、快速、灵活等优点,可用于快速搭建 Web 应用程序。MyBatis 是一款优秀的持久化框架,可以帮助开发者简化 DAO 层的开发。在实际的项目中,常常需要将 Spring Boot 与 MyBatis 结合起来使用,以帮助实现数据的持久化操作。本文将向读者介绍 Spring Boot 如何整合 MyBatis配置文件。 1. 添加依赖 首先,需要在 pom.xml 文件中添加 MyBatis 和数据库驱动程序的依赖。常用的数据库驱动程序有 MySQL、Oracle 等,具体的依赖信息可以在 Maven 仓库中查找。在 pom.xml 中添加如下代码: ``` <dependencies> <!-- MyBatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.0</version> </dependency> <!-- MySQL 驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.48</version> </dependency> </dependencies> ``` 2. 配置数据源 在 Spring Boot 中,可以使用 application.properties 或 application.yml 的配置文件配置数据源。需要注意的是,数据源的配置需要放在 Spring Boot 的自动配置类上方,以便在 MyBatis 配置文件中使用。这里以 MySQL 数据库为例,配置如下: ``` spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver ``` 3. 配置 MyBatis 在 Spring Boot 集成 MyBatis 的过程中,还需要配置 MyBatis 的相关参数,例如 MyBatis 的 mapper、configuration 等。Spring Boot 通过扫描指定的包来自动装配 mapper,并且 MyBatis配置文件 mybatis-config.xml 可以省略。在 application.properties 或 application.yml 中添加 MyBatis 相关配置: ``` mybatis.mapper-locations=classpath*:mapper/*.xml mybatis.configuration.map-underscore-to-camel-case=true mybatis.configuration.cache-enabled=true ``` 4. 创建 mapper 接口和实体类 在 Spring Boot 中,可以使用注解方式来声明 mapper 接口和实体类。在 mapper 接口上加上`@Mapper` 注解,在实体类上加上`@TableName` 注解即可: ``` @Mapper public interface UserMapper { @Select("select * from user where id=#{userId}") User findUserById(int userId); } @Data @TableName(value = "user") public class User { @TableId(value = "id",type = IdType.AUTO) private Integer id; private String userName; private String password; } ``` 5. 测试 最后,在 controller 中引入 mapper 接口,即可调用其方法进行数据的操作: ``` @RestController public class UserController { @Autowired private UserMapper userMapper; @RequestMapping("/user/{userId}") public User getUserById(@PathVariable int userId){ User user=userMapper.findUserById(userId); return user; } } ``` 以上是 Spring Boot 整合 MyBatis配置方法,通过这种方式可以快速地实现对数据库的操作。同时,Spring Boot 还集成了其他的数据库操作框架,如 JPA、Hibernate 等,读者可以根据需要选择使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值