MyBatis-Spring-Boot 使用总结 - LarryZeal - 博客园

接 MyBatis-Spring 使用总结

mybatis开发团队为Spring Boot 提供了 MyBatis-Spring-Boot-Starter

首先,MyBatis-Spring-Boot-Starter will:

  • Autodetect an existing DataSource.
  • Will create and register an instance of a SqlSessionFactoryBean passing that DataSource as an input.
  • Will create and register an instance of a SqlSessionTemplate got out of the SqlSessionFactoryBean.
  • Autoscan your mappers, link them to the SqlSessionTemplate and register them to Spring context so they can be injected into your beans.

    来源: http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/index.html

就是说,使用了该Starter之后,只需要定义一个DataSource即可,它会自动创建使用该DataSource的SqlSessionFactoryBean以及SqlSessionTemplate。会自动扫描你的Mappers,连接到SqlSessionTemplate,并注册到Spring上下文中。

MyBatis-Spring-Boot-Application的配置参数也是保存在application.properties文件中,使用前缀 mybatis 。

Property

Description

config-location

MyBatis xml config file (optional)

mapper-locations

Mapper xml config files (optional)

type-aliases-package

Package to search for type aliases (optional)

type-handlers-package

Package to search for type aliases (optional)

executor-type

Executor type: SIMPLE, REUSE, BATCH (optional)

configuration

A MyBatis Configuration bean. About available properties see the MyBatis reference page. NOTE This property cannot use at the same time with the config-location.       

(Starter)设置mapper有两种方法:

①使用config-location指定一个config xml,在里面设置 mapper 和 alias 。见例子1。

②使用type-aliases-package,需要配合自动扫描Mappers使用。

针对第二种,需要注意的是,如果想要自动扫描Mappers,需要在Mapper接口上标注@Mapper,否则失败。另外,还需要在application.properties文件中声明:mybatis.type-aliases-package 。

mapper-locations这个配置参数仅当mapper xml与mapper class不在同一个目录下时有效。所以一般可以忽略。

例子1(通过 mybatis.config-location 指定config xml,然后在里面设置别名和mapper包):

application.properties

mybatis.config-location=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>

<typeAliases>
    <package name="sample.mybatis.domain"/>
</typeAliases>
<mappers>
    <mapper resource="sample/mybatis/mapper/CityMapper.xml"/>
    <mapper resource="sample/mybatis/mapper/HotelMapper.xml"/>
</mappers>

</configuration>

复制代码; "复制代码")

例子2(通过 mybatis.type-aliases-package 和 @Mapper 来配置mybatis):

application.properties

mybatis.type-aliases-package=com.expert.pojo

复制代码; "复制代码")

package com.expert.dao;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import com.expert.pojo.User;
@Mapper
public interface UserMapper {
// @Select("SELECT * FROM user WHERE id = #{ id }")

User getById(String id);

@Select("SELECT * FROM user WHERE id = #{ id }")
User getById2(String id);

}

复制代码; "复制代码")

注意:@Alias("xxx") 是用来设置别名,而非用于扫描。


Original url: Access
Created at: 2019-03-01 18:49:19
Category: default
Tags: none

请先后发表评论
  • 最新评论
  • 总共0条评论