您的位置:首页 > 编程语言 > Java开发

10.玩转Spring Boot 集成Mybatis

2016-12-21 19:56 661 查看

玩转Spring Boot 集成Mybatis

      Spring Boot 提供了JDBC与JPA的支持,由于本人比较喜欢用Mybatis,所以基本上都是用的Mybatis其余的都很少用,也算是对Mybatis的偏爱吧,下面说说Spring Boot怎么跟Mybatis集成开发。

首先创建工程

      创建工程名称为:springboot-mybatis,创建完后如下图:



1.使用mybatis-spring集成

      (1)在pom.xml中添加Spring Boot、Mybatis以及mysql驱动包的依赖,添加后代码如下:
<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.chengli</groupId>
<artifactId>springboot-mybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot-mybatis</name>
<url>http://maven.apache.org</url>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.2.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<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-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
</project>
     
注意:记得选择项目Update Project,不然会改变不了哦。

      (2)新建application.properties文件,在文件加入以下内容:
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
     
注意:以上内容是我本地的数据库,可根据你实际的情况进行修改。

      (3)新建Mybatis的config类,代码如下:

package com.chengli.springboot.mybatis.config;

import javax.sql.DataSource;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@MapperScan(basePackages = { "com.chengli.springboot.mybatis" },annotationClass=Mapper.class)
@EnableTransactionManagement
public class MybatisConfig {
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));

return sqlSessionFactoryBean.getObject();
}

@Bean
public PlatformTransactionManager transactionManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}

}

      注意:@Configuration注解声明该类为一个配置类,@MapperScan注解用于扫描Mapper,类似Spring的@ComponentScan,这里我指定了扫描的根包,annotationClass指定使用@Mapper的注解类。setMapperLocations设置了XML路径,如果全部基于注解的话这里可以不用配置,我比较喜好将SQL放到XML中管理, 所以这里使用了XML。@EnableTransactionManagement注解开启注解事务,使用transactionManager创建了事务管理器,事务在这里不做叙述,在后面的博文中专门来讲事务。

      (4)新建用户Mapper类,代码如下:
package com.chengli.springboot.mybatis.dao;

import org.apache.ibatis.annotations.Mapper;

import com.chengli.springboot.mybatis.pojo.User;

@Mapper
public interface UserMapper {
User selectById(Long id);

int deleteById(Long id);
}


      (5)新建用户实体,代码如下:
package com.chengli.springboot.mybatis.pojo;

public class User {
private Long id;
private String name;
private String sex;
private Integer age;

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getSex() {
return sex;
}

public void setSex(String sex) {
this.sex = sex;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

}


      (6)在src/main/resources下新建文件夹mapper,然后在mapper中新建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.chengli.springboot.mybatis.dao.UserMapper">
<resultMap id="BaseResultMap" type="com.chengli.springboot.mybatis.pojo.User">
<id column="id" property="id" jdbcType="BIGINT" />
<result column="name" property="name" jdbcType="VARCHAR" />
<result column="sex" property="sex" jdbcType="VARCHAR" />
<result column="age" property="age" jdbcType="INTEGER" />
</resultMap>

<select id="selectById" resultMap="BaseResultMap" parameterType="java.lang.Long">
select
id,name,sex,age
from user
where id = #{id,jdbcType=BIGINT}
</select>

<delete id="deleteById" parameterType="java.lang.Long">
delete from user where id = #{id,jdbcType=BIGINT}
</delete>
</mapper>


      (7)新建Service类,代码如下:
package com.chengli.springboot.mybatis.service;

import com.chengli.springboot.mybatis.pojo.User;

public interface UserService {
User selectById(Long id);

void deleteById(Long id);
}

package com.chengli.springboot.mybatis.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.chengli.springboot.mybatis.dao.UserMapper;
import com.chengli.springboot.mybatis.pojo.User;
import com.chengli.springboot.mybatis.service.UserService;

@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;

@Override
public User selectById(Long id) {
return userMapper.selectById(id);
}

@Override
@Transactional
public void deleteById(Long id) {
userMapper.deleteById(id);
}

}


      (8)在来一个启动入口类
package com.chengli.springboot.mybatis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.chengli.springboot.mybatis.service.UserService
import com.chengli.springboot.mybatis.pojo.User;

@SpringBootApplication
@RestController
public class MainConfig {
@Autowired
private UserService userService;

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

@RequestMapping("/get/user/{id}")
public User getUserById(@PathVariable Long id) {
return userService.selectById(id);
}
}


      (8)到这里就大功告成了,启动在浏览器上输入显示如下:



2.使用mybatis-spring-boot-starter集成

      使用mybatis-spring-boot-starter集成Mybatis比较简单,目前依赖的Spring Boot 1.3.3版本,使用mybatis-spring-boot-starter集成配置不灵活,不建议使用,这里就不在叙述了。



3.Mybatis添加插件

      有时候需要往Mybatis里面添加插件,例如分页啊,在上面的代码中,我们在创建SqlSessionFactoryBean的时候,就可以添加插件了,具体代码如下:
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));

//添加Mybatis插件,例如分页,在之类创建你插件添加进去即可,这里我就不做叙述了。
//sqlSessionFactoryBean.setPlugins(new Interceptor[]{你的插件});

return sqlSessionFactoryBean.getObject();
}


完整的示例代码放在QQ交流群中 springboot-mybatis.zip

有兴趣的朋友可以加群探讨相互学习:

Spring Boot QQ交流群:599546061
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息