`
234390216
  • 浏览: 10193216 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
博客专栏
A5ee55b9-a463-3d09-9c78-0c0cf33198cd
Oracle基础
浏览量:460801
Ad26f909-6440-35a9-b4e9-9aea825bd38e
springMVC介绍
浏览量:1771787
Ce363057-ae4d-3ee1-bb46-e7b51a722a4b
Mybatis简介
浏览量:1395412
Bdeb91ad-cf8a-3fe9-942a-3710073b4000
Spring整合JMS
浏览量:393882
5cbbde67-7cd5-313c-95c2-4185389601e7
Ehcache简介
浏览量:678212
Cc1c0708-ccc2-3d20-ba47-d40e04440682
Cas简介
浏览量:529286
51592fc3-854c-34f4-9eff-cb82d993ab3a
Spring Securi...
浏览量:1178713
23e1c30e-ef8c-3702-aa3c-e83277ffca91
Spring基础知识
浏览量:461862
4af1c81c-eb9d-365f-b759-07685a32156e
Spring Aop介绍
浏览量:150116
2f926891-9e7a-3ce2-a074-3acb2aaf2584
JAXB简介
浏览量:66835
社区版块
存档分类
最新评论

Spring Boot(19)——使用Mybatis

阅读更多

使用Mybatis

Mybatis官方提供了整合Spring Boot的Starter,需要在Spring Boot应用中使用Mybatis,需要在pom.xml中添加如下依赖,当前最新的版本是1.3.2。

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
</dependency>

mybatis-spring-boot-starter默认会扫描@SpringBootApplication标注的Class所在package下的标注了@org.apache.ibatis.annotations.Mapper的接口作为Mapper,并注册为Spring bean。所以此时可以定义类似如下这样的Mapper接口。

@Mapper
public interface UserMapper {

    @Select("select * from tb_user where username=#{username}")
    User findByUsername(String username);
    
}

然后可以在需要的地方遵循Spring规范进行自动注入即可。

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;
    
    public User findByUsername(String username) {
        return this.userMapper.findByUsername(username);
    }
    
}

以上就是最简单的在Spring Boot应用中使用Mybatis的方式了。Mybatis的自动配置由org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration负责,其会自动寻找DataSource bean,然后注册SqlSessionFactory、SqlSessionTemplate类型的bean,并能自动扫描Mapper接口。

如果不想通过注解写SQL,想使用Mapper.xml也是可以的,比如下面就是UserMapper对应的UserMapper.xml,其中定义了一个findById的查询。

<?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.elim.springboot.mybatis.UserMapper">

    <select id="findById" resultType="com.elim.springboot.mybatis.User"
        parameterType="java.lang.Long">
        select * from tb_user where id=#{id}
    </select>

</mapper>

那对应的UserMapper接口中也需要定义一个findById方法,这个时候UserMapper接口的定义是如下这样子。

@Mapper
public interface UserMapper {

    @Select("select * from tb_user where username=#{username}")
    User findByUsername(String username);
    
    User findById(Long id);
    
}

接下来的用法是一模一样的。但是需要注意的是UserMapper接口上的@Mapper注解不能去掉,因为此时Mybatis还要靠它来识别Mapper接口。如果希望不加上@Mapper也能被识别为Mapper接口,则需要引入@MapperScan。比如下面代码就通过@MapperScan指定了将扫描com.elim.springboot.mybatis包及其子包下的接口。@MapperScan还可以通过markerInterface属性指定需要扫描的接口继承的父接口,通过annotationClass属性指定Mapper接口上应该添加的注解,可以通过sqlSessionTemplateRef属性指定扫描到的Mapper接口需要绑定的SqlSessionTemplate对应的bean,可以通过sqlSessionFactoryRef属性指定需要使用的SqlSessionFactory对应的bean,更多配置信息可以参考MapperScan的API文档。

@SpringBootApplication
@MapperScan(basePackages="com.elim.springboot.mybatis")
public class MybatisApplication {

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

如果我们的Mapper是放在不同的package下面的,则可以指定多个package,packages属性对应的是一个数组。如果所放的多个package是具有一定规则的,则可以应用通配符来表示。比如下面的将扫描com.elim.package1.mapper,也会扫描com.elim.package2.mapper等等。如果期望匹配任意多级目录,则可以使用两个*,比如com.elim.**.mapper,会扫描com.elim.package1.package2.mapper包。

@SpringBootApplication
@MapperScan(basePackages="com.elim.*.mapper")
public class MybatisApplication {

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

可以通过mybatis.*进行一些自定义的配置。可以通过mybatis.type-aliases-package指定需要注册类型别名的包,多个包之间可以通过英文的逗号或分号分隔。比如下面的代码就指定了将扫描com.elim.springboot.mybatis包下面的Class进行别名注册。

mybatis.type-aliases-package=com.elim.springboot.mybatis

可以通过mybatis.executor-type=BATCH指定默认的ExecutorType为BATCH,对应Executor为BatchExecutor。

可以通过mybatis.type-handlers-package=com.elim.springboot.mybatis指定将在com.elim.springboot.mybatis包下寻找TypeHandler并进行注册,多个包之间可以通过英文的逗号或分号分隔。

如果Mapper.xml文件跟Mapper接口不是存放在相同的路径下,可以通过mybatis.mapper-locations属性指定Mapper.xml文件存放的路径,可以同时指定多个路径,多个路径间以英文的逗号分隔。

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

如果需要对org.apache.ibatis.session.Configuration进行全局配置可以通过mybatis.configuration.*进行配置,org.apache.ibatis.session.Configuration中拥有set方法的都是可以配置的,详情请参考对应的API文档。

使用Interceptor

MybatisAutoConfiguration会自动把bean容器中定义的org.apache.ibatis.plugin.Interceptor注册到创建的SqlSessionFactory中,所以如果需要开发自己的Interceptor,只需要把它定义为一个Spring bean即可自动完成注册,比如下面这样。

@Intercepts({
        @Signature(method = "query", type = Executor.class, args = { MappedStatement.class, Object.class,
                RowBounds.class, ResultHandler.class }),
        @Signature(method = "prepare", type = StatementHandler.class, args = { Connection.class, Integer.class}) })
@Component
public class MyInterceptor implements Interceptor {

    public Object intercept(Invocation invocation) throws Throwable {
        Object result = invocation.proceed();
        System.out.println("Invocation.proceed()--" + result + "---" + invocation.getMethod().getName());
        return result;
    }

    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    public void setProperties(Properties properties) {
        String prop1 = properties.getProperty("prop1");
        String prop2 = properties.getProperty("prop2");
        System.out.println(prop1 + "------" + prop2);
    }

}

但如果是需要使用第三方已经实现好的Interceptor怎么办呢?比如需要使用流行的分页插件pagehelper,首先当然是引入PageHelper的依赖了。

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.1.4</version>
</dependency>

然后可以通过定义一个@Configuration配置类,然后定义PageInterceptor为一个bean,比如下面这样。

@Configuration
public class ThirdInterceptorConfiguration {
    
    @Bean
    public PageInterceptor newPageInterceptor() {
        PageInterceptor pageInterceptor = new PageInterceptor();
        Properties properties = new Properties();
        properties.put("dialet", "mysql");
        pageInterceptor.setProperties(properties);
        return pageInterceptor;
    }

}

最简单的办法是直接使用PageHelper提供的Spring Boot Starter,其PageHelperAutoConfiguration会负责往SqlSessionFactory中注册PageInterceptor。可以通过pagehelper.*配置相关的自定义属性。

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.2.5</version>
</dependency>

ConfigurationCustomizer

ConfigurationCustomizer是mybatis-spring-boot-starter提供的一个可用于对Configuration对象进行一些自定义配置的接口。MybatisAutoConfiguration在进行自动配置时会自动获取bean容器中定义的所有的ConfigurationCustomizer类型的bean,在创建好Configuration对象后会一一调用它们的customize()方法。下面的代码定义了一个ConfigurationCustomizer类型的bean,其配置启用了Mybatis的懒加载。

@Component
public class MyConfigurationCustomizer implements ConfigurationCustomizer {

    @Override
    public void customize(Configuration configuration) {
        configuration.setLazyLoadingEnabled(true);
    }

}

参考文档

http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/

(注:本文是基于Spring Boot 2.0.3所写)

 

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics