码迷,mamicode.com
首页 > 编程语言 > 详细

MyBatis-Spring-Boot 使用总结

时间:2016-09-15 06:17:56      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:

 

首先,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.
 
就是说,使用了该Starter之后,只需要定义一个DataSource即可,它会自动创建使用该DataSource的SqlSessionFactoryBean以及SqlSessionTemplate。会自动扫描你的Mappers,连接到SqlSessionTemplate,并注册到Spring上下文中。
 
MyBatis-Spring-Boot-Application的配置参数也是保存在application.properties文件中,使用前缀 mybatis 。
PropertyDescription
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") 是用来设置别名,而非用于扫描。
 
 
 
 

MyBatis-Spring-Boot 使用总结

标签:

原文地址:http://www.cnblogs.com/larryzeal/p/5874107.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!