MyBatis基于Spring-boot集成通用Mapper以及pagehelper分页插件(含源码下载)

配置

POM文件

<parent>
<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>1.5.6.RELEASE</version>
	<relativePath />
</parent>

<properties>
	<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
	<java.version>1.8</java.version>
</properties>

<dependencies>
	<dependency>
		<groupId>tk.mybatis</groupId>
		<artifactId>mapper-spring-boot-starter</artifactId>
		<version>RELEASE</version>
	</dependency>
	<dependency>
		<groupId>com.github.pagehelper</groupId>
		<artifactId>pagehelper-spring-boot-starter</artifactId>
		<version>RELEASE</version>
	</dependency>
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
	</dependency>
	<dependency>
		<groupId>org.mybatis.spring.boot</groupId>
		<artifactId>mybatis-spring-boot-starter</artifactId>
		<version>1.3.1</version>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-jdbc</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-test</artifactId>
		<scope>test</scope>
	</dependency>
</dependencies>

同一环境1.5.7.RELEASE版本的Spring-boot会抛Caused by: java.lang.IllegalStateException: Cannot load driver class: com.mysql.jdbc.Driver异常,1.5.6.RELEASE以及1.5.5.RELEASE版本亲测没问题


application.properties配置文件

#数据库
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test
spring.datasource.username=root
spring.datasource.password=741852
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

#mybatis&&通用Mapper
mybatis.type-aliases-package=com.karle.bean
mybatis.mapper-locations=classpath:mapper/*.xml
mapper.mappers=com.karle.tk.TkMapper
mapper.identity=MYSQL

#分页插件
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql

#log
logging.file=logger.log
logging.level.*=debug

映射实体(省略字段get、set)

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Table(name = "user")
public class User {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Integer id;

	/**
	 * 名称
	 */
	@Column(name = "name")
	private String name;

	/**
	 * 年龄
	 */
	@Column(name = "age")
	private Integer age;

	/**
	 * 身份编号
	 */
	@Column(name = "card_no")
	private Integer cardNo;

	/**
	 * 生日
	 */
	@Column(name = "birthday")
	private Date birthday;
}

本地通用Mapper接口(继承通用Mapper接口)

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

public interface TkMapper<T> extends Mapper<T>, MySqlMapper<T> {

}

Mapper接口:基本的增、删、改、查方法
MySqlMapper:针对MySQL的额外补充接口,支持批量插入

业务接口(继承“本地通用Mapper接口")

import org.apache.ibatis.annotations.Param;

import com.karle.bean.User;
import com.karle.tk.TkMapper;

public interface UserMapper extends TkMapper<User> {

	public User selectByCardNo(@Param("cardNo") int cardNo);

}

Spring-boot启动类,@MapperScan仅扫描业务接口包,不能扫描本地通用Mapper接口包,否则报java.lang.ClassCastException: sun.reflect.generics.reflectiveObjects.TypeVariableImpl cannot be cast to java.lang.Class异常

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan(basePackages = { "com.karle.mapper" })
public class SpringBootMyBatisApplication {

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

单元测试


import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.github.pagehelper.PageHelper;
import com.karle.bean.User;
import com.karle.mapper.UserMapper;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootMyBatisApplicationTests {

	@Autowired
	private UserMapper mapper;

	// 插入一条新记录
	@Test
	public void insertOne() {
		User newUser = new User();
		int cardNo = (int) (Math.random() * 10000000);
		newUser.setAge(24);
		newUser.setBirthday(new Date());
		newUser.setName(cardNo + "用户");
		newUser.setCardNo(cardNo);
		mapper.insertSelective(newUser);
		System.out.println("插入成功");
	}

	// 批量插入记录
	@Test
	public void insertMore() {
		List<User> recordList = new ArrayList<User>();
		for (int i = 0; i < 2; i++) {
			User newUser = new User();
			int cardNo = (int) (Math.random() * 10000000);
			newUser.setAge(26);
			newUser.setBirthday(new Date());
			newUser.setName(cardNo + "批量插入用户");
			newUser.setCardNo(cardNo);
			recordList.add(newUser);
		}
		mapper.insertList(recordList);
		System.out.println("批量插入成功");
	}

	// 根据唯一编号查询用户(通用Mapper查询)
	@Test
	public void selectByCardNo() {
		User paramBean = new User();
		paramBean.setCardNo(6647403);
		User dbUser = mapper.selectOne(paramBean);
		if (dbUser != null) {
			System.out.println("数据库用户(通用Mapper查询):" + dbUser.getName());
			return;
		}
		System.out.println("查无此用户");
	}

	// 根据唯一编号查询用户(XML查询)
	@Test
	public void selectByCardNoByXml() {
		User dbUser = mapper.selectByCardNo(6105967);
		if (dbUser != null) {
			System.out.println("数据库用户(XML查询):" + dbUser.getName());
			return;
		}
		System.out.println("查无此用户");
	}

	// 根据年龄查询一组用户
	@Test
	public void selectByAge() {
		User paramBean = new User();
		paramBean.setAge(24);
		List<User> dbUserList = mapper.select(paramBean);
		System.out.println("总共查询数:" + dbUserList.size());
	}

	// 分页查询用户
	@Test
	public void selectByPage() {
		PageHelper.offsetPage(1, 5);
		List<User> dbUserList = mapper.select(null);
		for (User item : dbUserList) {
			System.out.println("分页用户:" + item.getName());
		}
	}

	// 更新用户信息
	@Test
	public void updateOneInfo() {
		User paramBean = new User();
		paramBean.setId(1);
		paramBean.setAge(26);
		mapper.updateByPrimaryKeySelective(paramBean);
		System.out.println("更新成功");
	}

}

集成通用Mapper可以像hibernate那样“面向对象”进行数据库操作了,pagehelper分页也弥补了Mybatis本身不支持分页机制的小缺陷;为Mybatis添这两小插件,你还在犹豫使用Mybatis或者Hibernate吗?快拥抱Mybatis吧

(完)

Demo下载(2分):http://download.csdn.net/download/qq_19260029/9982948

脱单APP

推荐文章:
1:【代码规范神器】阿里巴巴Java开发规约IDE插件使用教程(P3C)
2: Eclipse新建Spring-boot项目,打包部署并输出HelloWord
3:程序员如何脱单?看完脱单率至少增加80%

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值