Spring boot 整合 tk mybatis 插件

转:http://blog.csdn.net/u013187139/article/details/68944972


在众多orm框架中,我对mybatis最熟悉,所以我采用mybatis进行整合,对我们的orm框架,这里我们也提出几点要求

  • 支持分页
  • curd接口抽象处理
  • 事务控制
  • 多数据源

在查阅了一些资料后,找到目前为止最简单的一种整合mybatis方式,这里贴出原始博客地址

http://blog.didispace.com/springbootmybatis/

参照大神的整合,我们的整合异常的顺利,贴出我们增加的代码

在pom中添加以下依赖

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.1.1</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.21</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

在application.properties 中增加以下配置

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
  • 1
  • 2
  • 3
  • 4
  • 5

表结构

Create Table: CREATE TABLE `userinfo` (
  `id` int(20) NOT NULL AUTO_INCREMENT,
  `username` varchar(20) DEFAULT NULL,
  `password` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

编写dao层代码,新建UserDao 接口

@Mapper
public interface UserDao {
    @Select("SELECT * FROM USERINFO WHERE username = #{username}")
    UserInfo findByName(@Param("username") String username);

    @Insert("INSERT INTO USERINFO(username, password) VALUES(#{username}, #{password})")
    int insert(@Param("username") String name, @Param("password") String password);

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

在业务层增加对dao层接口的引用,修改TestInterFace,TestInterFaceImpl

public interface TestInterFace {

    public int testInterFace();

    public UserInfo testUser();

    public int insertUser(String username,String password);//新增的接口
}


@Service
public class TestInterFaceImpl implements TestInterFace {
    //引入dao层接口
    @Autowired UserDao userDao;
    @Override public int testInterFace() {
    return 0;
    }

    @Override public UserInfo testUser() {
    return new UserInfo();
    }

    //新增的接口实现
    @Override public int insertUser(String username,String password) {
    return userDao.insert(username,password);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

接下来修改我们的controller,提供对外的接口,修改UserController

@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    private TestInterFace testInterFace;

    @RequestMapping("/get")
    @ResponseBody UserInfo getUser() {
    return testInterFace.testUser();
    }

    //增加新的对外访问接口
    @RequestMapping("/add")
    @ResponseBody String add() {
        testInterFace.insertUser("username123寇鑫","password123寇鑫");
        return "插入成功";
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

来测试一下我们的新接口,访问 http://localhost:8080/user/add

数据库插入

看到浏览器已经正常返回了,接下来去数据库看看数据有没有实际插入

+----+-------------------+-------------------+
| id | username          | password          |
+----+-------------------+-------------------+
|  1 | username123寇鑫   | password123寇鑫   |
+----+-------------------+-------------------+
  • 1
  • 2
  • 3
  • 4
  • 5

可以看到,在我们的表中,已经插入了一条数据,并且中文显示正常。但现在每次新加一个接口,都要对应的写一条sql,这样很麻烦,而且不利于开发,业务方不能专注于业务的开发,所以我们要抽象出来通用的curd接口,并且支付分页。

2017-04-04

mybatis有很多成熟的分页插件以及通用接口插件,这里我们也采用目前较为成熟的方案,不必重复造轮子。 
添加pom

 <!--分页插件-->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>4.2.1</version>
</dependency>
<!--通用Mapper-->
<dependency>
    <groupId>tk.mybatis</groupId>
    <artifactId>mapper</artifactId>
    <version>3.3.9</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

因为springboot 不需要设置xml,所以这里都采用注解和代码的形式注入插件

新建配置类

package com.kx.springboot.dao.mybatis;

import com.github.pagehelper.PageHelper;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.util.Properties;

/**
 * Created by kx on 17/4/2.
 */
public class MyBatisConfig {
    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactoryBean() {
    SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
//  bean.setDataSource(dataSource());

    bean.setTypeAliasesPackage("com.kx.springboot.bean");

    //分页插件设置
    PageHelper pageHelper = new PageHelper();
    Properties properties = new Properties();
    properties.setProperty("reasonable", "true");
    properties.setProperty("supportMethodsArguments", "true");
    properties.setProperty("returnPageInfo", "check");
    properties.setProperty("params", "count=countSql");
    pageHelper.setProperties(properties);

    //添加分页插件
    bean.setPlugins(new Interceptor[]{pageHelper});

    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    try {
        //基于注解扫描Mapper,不需配置xml路径
        //bean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
        return bean.getObject();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47

新建配置扫描类

package com.kx.springboot.dao.mybatis;

import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;

import java.util.Properties;

/**
 * Created by kx on 17/4/2.
 */
@Configuration
//必须在MyBatisConfig注册后再加载MapperScannerConfigurer,否则会报错
@AutoConfigureAfter(MyBatisConfig.class)
public class MyBatisMapperScannerConfig {
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
    MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
    mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
    mapperScannerConfigurer.setBasePackage("com.kx.springboot.dao.mybatis");

    //初始化扫描器的相关配置,这里我们要创建一个Mapper的父类
    Properties properties = new Properties();
    properties.setProperty("mappers", "com.kx.springboot.dao.baseDao.MyMapper");
    properties.setProperty("notEmpty", "false");
    properties.setProperty("IDENTITY", "MYSQL");

    mapperScannerConfigurer.setProperties(properties);

    return mapperScannerConfigurer;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

新建对外暴露接口

package com.kx.springboot.dao.baseDao;

import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;

/**
 * Created by kx on 17/4/2.
 */
public interface MyMapper<T> extends Mapper<T>, MySqlMapper<T> {
    //TODO
    //FIXME 特别注意,该接口不能被扫描到,否则会出错
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

现在,修改我们的dao层实现类,继承我们的通用接口

@Mapper
public interface UserDao extends MyMapper<UserInfo> {

}
  • 1
  • 2
  • 3
  • 4
  • 5

在业务层中增加想要调用的方法

public interface TestInterFace {

    public int testInterFace();

    public UserInfo testUser();

    public int insertUser(UserInfo userInfo);

//新增加的方法
    List<UserInfo> selectALL();
}


@Service
public class TestInterFaceImpl implements TestInterFace {
    @Autowired UserDao userDao;
    @Override public int testInterFace() {
    return 0;
    }

    @Override public UserInfo testUser() {
    return new UserInfo();
    }

    @Override public int insertUser(UserInfo userInfo) {
    return userDao.insert(userInfo);
    }

    //新增加的实现
    @Override
    public List<UserInfo> selectALL(){
    return userDao.selectAll();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

看到我们在调用userDao时已经有了通用的单表查询方法。将新接口暴露给http,修改controller

@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    private TestInterFace testInterFace;

    @RequestMapping("/get")
    @ResponseBody UserInfo getUser() {
    return testInterFace.testUser();
    }

    @RequestMapping("/add")
    @ResponseBody String add() {
        UserInfo user = new UserInfo();
        user.setUsername("username123寇鑫");
        user.setPassword("password123寇鑫");
        testInterFace.insertUser(user);
        return "插入成功";
    }

//新增的接口方法
    @RequestMapping("/getall")
    @ResponseBody List<UserInfo> getall() {
        return testInterFace.selectALL();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

访问http://localhost:8080/user/getall

程序抛出异常

### Error querying database.  Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'ssmtest.user_info' doesn't exist
### The error may exist in com/kx/springboot/dao/UserDao.java (best guess)
### The error may involve defaultParameterMap
### The error occurred while setting parameters
### SQL: SELECT username,password  FROM user_info
### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'ssmtest.user_info' doesn't exist
; bad SQL grammar []; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'ssmtest.user_info' doesn't exist] with root cause

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'ssmtest.user_info' doesn't exist
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

从异常可以看出来,我们的表和我们查询数据库的字段没有映射起来,查询资料后发现原因是通用插件的问题,默认的字段中有下划线,我们需要手动指定映射

修改userinfo类

package com.kx.springboot.bean;

import javax.persistence.Column;
import javax.persistence.Table;

/**
 * Created by kx on 17/3/29.
 */
 //增加注解声明表名
@Table(name = "userinfo")
public class UserInfo {
    //增加注解声明字段名
    @Column(name = "username")
    private String username = "username寇鑫123";
    @Column(name = "password")
    private String password = "password寇鑫123";

    public String getUsername() {
    return username;
    }

    public void setUsername(String username) {
    this.username = username;
    }

    public String getPassword() {
    return password;
    }

    public void setPassword(String password) {
    this.password = password;
    }

    @Override public String toString() {
    return "User{" + "username='" + username + '\'' + ", password='" + password + '\'' + '}';
    }
}

猜你喜欢

转载自blog.csdn.net/u014695188/article/details/78241167
今日推荐