Spring Boot学习(2):Spring Boot集成MyBatis

目录

一、引言

二、导入jar包

三、配置

1、注解方式

2、XML方式

四、验证


一、引言

上篇文章介绍了怎么在 IntelliJ IDEA 创建Spring Boot项目,这篇文章我们将接着上次创建的Spring Boot项目,介绍Spring Boot如何集成Mybatis,包括 注解 Xml配置文件 两种形式

二、导入jar包

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--用于SpingBoot和Mybatis集成-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>
        <!--用于创建MySQL连接-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

三、配置

1、注解方式

包结构:

1)在application.properties中配置MySQL连接信息

spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

2)在DemoApplication类上加@MapperScan,该注解的作用是自动去对应的包下扫描Mapper接口文件。

@SpringBootApplication
@MapperScan("com.example.demo.dao")
public class DemoApplication {

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

3)在UserMapper.java中用注解方式编辑SQL

@Service
public interface UserMapper {
    @Select("select * from user where id = #{id, jdbcType=INTEGER}")
    User selectByPrimaryKey(Integer id);
}

到此,Spring Boot集成Mybatis的注解方式已经完成。

2、XML方式

上面讲了基于注解形式的Spring Boot+Mybatis,但是在我们的实际开发中,注解形式并不多见,我们更多的是用XML文件形式,下面我们就来看看XML方式怎么来实现。

1)在application.properties中配置MySQL连接信息(和注解方式相同,如果已经配置过,跳过此步骤)

2)在Application类上加@MapperScan(和注解方式相同,如果已经配置过,跳过此步骤)

3)在application.properties中配置mapper文件的路径

spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

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

4)在UserMapper.java中定义接口

@Service
public interface UserMapper {
    List<User> selectAll();

    List<User> selectUserByNameAndAge(Map<String, Object> map);

    List<User> selectUserByNameList(List<String> nameList);

    @Select("select * from user where id = #{id, jdbcType=INTEGER}")
    User selectByPrimaryKey(Integer id);
}

5)编辑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.example.demo.dao.UserMapper">
    <resultMap id="BaseResultMap" type="com.example.demo.dao.bean.User">
        <id column="id" property="id" jdbcType="INTEGER"/>
        <result column="name" property="name" jdbcType="VARCHAR"/>
        <result column="age" property="age" jdbcType="INTEGER"/>
    </resultMap>
    <sql id="Base_Column_List">
        id, name, age
    </sql>
    <select id="selectAll" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from user
    </select>
    <select id="selectUserByNameList" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from user
        where name in
        <foreach collection="list" item="name" index="index" open="(" close=")" separator=",">
            #{name, jdbcType=VARCHAR}
        </foreach>
    </select>
    <select id="selectUserByNameAndAge" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from user
        <where>
            <if test="name != null and name != ''">
                name = #{name, jdbcType=VARCHAR}
            </if>
            <if test="age != null and age != ''">
                and age = #{age, jdbcType=INTEGER}
            </if>
        </where>

    </select>
</mapper>

6)如果想根据自己的需求,定制MyBatis,那么我们还需要创建mybatis-config.xml(名字不唯一,大家随意),并在application.properties文件中配置mybatis-config.xml扫描路径。

mybatis-config.xml:

<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <!-- 这个配置使全局的映射器启用或禁用缓存 -->
        <setting name="cacheEnabled" value="false" />
        <!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载 -->
        <setting name="lazyLoadingEnabled" value="true" />
        <!-- 当启用时,有延迟加载属性的对象在被调用时将会完全加载任意属性。否则,每种属性将会按需要加载 -->
        <setting name="aggressiveLazyLoading" value="true" />
        <!-- 允许或不允许多种结果集从一个单独的语句中返回(需要适合的驱动) -->
        <setting name="multipleResultSetsEnabled" value="true" />
        <!-- 使用列标签代替列名。不同的驱动在这方便表现不同。参考驱动文档或充分测试两种方法来决定所使用的驱动 -->
        <setting name="useColumnLabel" value="true" />
        <!-- 允许JDBC支持生成的键。需要适合的驱动。如果设置为true则这个设置强制生成的键被使用,尽管一些驱动拒绝兼容但仍然有效(比如Derby) -->
        <setting name="useGeneratedKeys" value="true" />
        <!-- 指定MyBatis如何自动映射列到字段/属性。PARTIAL只会自动映射简单,没有嵌套的结果。FULL会自动映射任意复杂的结果(嵌套的或其他情况) -->
        <setting name="autoMappingBehavior" value="PARTIAL" />
        <!--当检测出未知列(或未知属性)时,如何处理,默认情况下没有任何提示,这在测试的时候很不方便,不容易找到错误。
        NONE : 不做任何处理 (默认值)
        WARNING : 警告日志形式的详细信息
        FAILING : 映射失败,抛出异常和详细信息
        -->
        <setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>
        <!-- 配置默认的执行器。SIMPLE执行器没有什么特别之处。REUSE执行器重用预处理语句。BATCH执行器重用语句和批量更新 -->
        <setting name="defaultExecutorType" value="SIMPLE" />
        <!-- 设置超时时间,它决定驱动等待一个数据库响应的时间 -->
        <setting name="defaultStatementTimeout" value="25000" />
        <!--设置查询返回值数量,可以被查询数值覆盖  -->
        <setting name="defaultFetchSize" value="100"/>
        <!-- 允许在嵌套语句中使用分页-->
        <setting name="safeRowBoundsEnabled" value="false"/>
        <!--是否开启自动驼峰命名规则映射,即从经典数据库列名 A_COLUMN 到经典 Java 属性名 aColumn 的类似映射。-->
        <setting name="mapUnderscoreToCamelCase" value="false"/>
        <!--MyBatis利用本地缓存机制(Local Cache)防止循环引用(circular references)和加速重复嵌套查询。 默认值为 SESSION,这种情况下会缓存一个会话中执行的所有查询。 若设置值为 STATEMENT,本地会话仅用在语句执行上,对相同 SqlSession 的不同调用将不会共享数据。-->
        <setting name="localCacheScope" value="SESSION"/>
        <!-- 当没有为参数提供特定的 JDBC 类型时,为空值指定 JDBC 类型。 某些驱动需要指定列的 JDBC 类型,多数情况直接用一般类型即可,比如 NULL、VARCHAR、OTHER。-->
        <setting name="jdbcTypeForNull" value="OTHER"/>
        <!-- 指定哪个对象的方法触发一次延迟加载。-->
        <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
    </settings>
    <typeAliases>
        <typeAlias alias="Integer" type="java.lang.Integer" />
        <typeAlias alias="Long" type="java.lang.Long" />
        <typeAlias alias="HashMap" type="java.util.HashMap" />
        <typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
        <typeAlias alias="ArrayList" type="java.util.ArrayList" />
        <typeAlias alias="LinkedList" type="java.util.LinkedList" />
    </typeAliases>
</configuration>

application.properties:

spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

mybatis.config-location=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

四、验证

各位博友可自行验证。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值