使用MyBatis-Spring-Boot-Starter快速集成mybatis

版权声明:请附链接,自由转载 https://blog.csdn.net/kangkanglou/article/details/81776489

MyBatis-Spring-Boot-Starter是什么?

The MyBatis-Spring-Boot-Starter help you build quickly MyBatis applications on top of the Spring Boot.

MyBatis-Spring-Boot-Starter可以帮助你快速创建基于Spring Boot的MyBatis应用程序。

使用MyBatis-Spring-Boot-Starter可以达到什么效果?

  • 构建独立的MyBatis应用程序
  • 零模板
  • 更少的XML配置文件

引入MyBatis-Spring-Boot-Starter模块之后,其可以:

  • 自动检测DataSource
  • 使用SqlSessionFactoryBean注册SqlSessionFactory 实例,并设置DataSource数据源
  • 基于SqlSessionFactory自动注册SqlSessionTemplate实例
  • 自动扫描@Mapper注解类,并通过SqlSessionTemplate注册到Spring Context中

其实,简单来讲,MyBatis-Spring-Boot-Starter就是参照Spring Boot的设计思想,化繁为简,以简单注解的方式让用户快速上手。

首先,我们引入依赖:

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

配置数据源

spring:
  application:
    name: spring-mybatis
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    url: "jdbc:mysql://192.168.43.61:3306/cib"
    username: icbc
    password: icbc

MyBatis的配置,主要是开启数据库中的字段名与实体对象属性的驼峰转换

mybatis:
  configuration:
    map-underscore-to-camel-case: true
    default-statement-timeout: 30
    default-fetch-size: 100

定义一个简单的Mapper类,包含增、改、查操作,这里我们没有使用@Mapper注解,而是通过在应用程序启动时通过@MapperScann注解指定扫描目录,这样避免了每一个Mapper类都要增加@Mapper注解的繁琐。

@Service
public interface UserMapper {
    @Select("select * from cib_user where id = #{id}")
    /**
     * 或者使用Results来映射
     @Results(
     {
     @Result(property = "createTime", column = "create_time"),
     @Result(property = "userName", column = "user_name")
     }
     )
     */
    User findUserById(@Param("id") int id);

    @Select("select * from cib_user")
    List<User> findAllUsers();

    @Insert("insert into cib_user (user_name,create_time) values(#{userName},#{createTime})")
    void addUser(User user);

    @Update("update cib_user set user_name=#{userName},create_time=#{createTime} where id = #{id}")
    void updateUser(User user);
}

启动我们的应用程序

@SpringBootApplication
@MapperScan("cn.cib.service")
public class SpringMyBatisApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringMyBatisApplication.class, args);
    }
}

源码地址:https://github.com/ypmc/spring-cloud/tree/master/spring-mybatis

参考文档:http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/

猜你喜欢

转载自blog.csdn.net/kangkanglou/article/details/81776489