ORM框架之Mybatis(六)mybatis通用mapper
一、简介通用mapper
1.1 官方介绍:(官网:https://mapperhelper.github.io/docs/)
通用Mapper都可以极大的方便开发人员。可以随意的按照自己的需要选择通用方法,还可以很方便的开发自己的通用方法。
极其方便的使用MyBatis单表的增删改查。
支持单表操作,不支持通用的多表联合查询。
- 不是表中字段的属性必须加
@Transient
注解 - 通用 Mapper 不支持 devtools 热加载
1.2 代码官方托管地址:(也是刘增辉开源项目,他还开源了一个很牛的分页插件page—helper)
github地址:https://github.com/abel533/Mapper
码云地址:https://gitee.com/free/Mapper
二、通用mapper实例演示
2.1 创建项目用数据表:
首先创建数据库common_mapper(使用的是mysql数据库)
然后在该数据库下创建数据表:
CREATE TABLE `tabple_emp` (
`emp_id` int NOT NULL AUTO_INCREMENT ,
`emp_name` varchar(500) NULL ,
`emp_salary` double(15,5) NULL ,
`emp_age` int NULL ,
PRIMARY KEY (`emp_id`)
);
INSERT INTO `tabple_emp` (`emp_name`, `emp_salary`, `emp_age`) VALUES ('tom', '1254.37', '27');
INSERT INTO `tabple_emp` (`emp_name`, `emp_salary`, `emp_age`) VALUES ('jerry', '6635.42', '38');
INSERT INTO `tabple_emp` (`emp_name`, `emp_salary`, `emp_age`) VALUES ('bob', '5560.11', '40');
INSERT INTO `tabple_emp` (`emp_name`, `emp_salary`, `emp_age`) VALUES ('kate', '2209.11', '22');
INSERT INTO `tabple_emp` (`emp_name`, `emp_salary`, `emp_age`) VALUES ('justin', '4203.15', '30');
创建好之后:
2.2 创建maven项目Pro01Mapper
2.2.1配置pom文件:
<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.xiaomifeng1010.mapper</groupId><artifactId>Pro01Mapper</artifactId><version>0.0.1-SNAPSHOT</version><dependencies><dependency><groupId>tk.mybatis</groupId><artifactId>mapper</artifactId><version>4.0.0-beta3</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.9</version></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency><dependency><groupId>cglib</groupId><artifactId>cglib</artifactId><version>2.2</version></dependency><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.6.8</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>1.7.7</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>1.7.7</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.2.8</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>1.2.2</version></dependency><dependency><groupId>com.mchange</groupId><artifactId>c3p0</artifactId><version>0.9.2</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>4.3.10.RELEASE</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.37</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-orm</artifactId><version>4.3.10.RELEASE</version></dependency></dependencies>
</project>
注意mapper需要的依赖为:
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>4.0.0-beta3</version>
</dependency>
2.2.2 在resources文件夹下配置spring-context.xml、mybatis-config.xml、log4j.properties、jdbc.properties
spring-context.xml配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"><!-- 配置数据源 --><context:property-placeholder location="classpath:jdbc.properties"/><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="user" value="${jdbc.user}"/><property name="password" value="${jdbc.password}"/><property name="jdbcUrl" value="${jdbc.url}"/><property name="driverClass" value="${jdbc.driver}"/></bean><!-- 整合MyBatis --><bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="configLocation" value="classpath:mybatis-config.xml"/><property name="dataSource" ref="dataSource"/></bean><!-- 整合通用Mapper所需要做的配置修改: --><!-- 原始全类名:org.mybatis.spring.mapper.MapperScannerConfigurer --><!-- 通用Mapper使用:tk.mybatis.spring.mapper.MapperScannerConfigurer --><bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.xiaomifeng1010.mapper.mappers"/></bean><!-- 配置Service自动扫描的包 --><context:component-scan base-package="com.xiaomifeng1010.mapper.services"/><!-- 配置声明式事务 --><bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"/></bean><aop:config><aop:advisor advice-ref="txAdvice" pointcut="execution(* *..*Service.*(..))"/></aop:config><tx:advice id="txAdvice" transaction-manager="dataSourceTransactionManager"><tx:attributes><tx:method name="get*" read-only="true"/><tx:method name="save*" rollback-for="java.lang.Exception" propagation="REQUIRES_NEW"/><tx:method name="remove*" rollback-for="java.lang.Exception" propagation="REQUIRES_NEW"/><tx:method name="update*" rollback-for="java.lang.Exception" propagation="REQUIRES_NEW"/></tx:attributes></tx:advice>
</beans>
mybatis-config.xml配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration></configuration>
log4j.properties配置文件:
log4j.rootLogger=DEBUG,myConsole
log4j.appender.myConsole=org.apache.log4j.ConsoleAppender
log4j.appender.myConsole.ImmediateFlush=true
log4j.appender.myConsole.Target=System.out
log4j.appender.myConsole.layout=org.apache.log4j.PatternLayout
log4j.appender.myConsole.layout.ConversionPattern=[%-5p] %d(%r) --> [%t] %l: %m %x %nlog4j.logger.com.mchange.v2=ERROR
jdbc.properties配置文件
jdbc.user=root
jdbc.password=123456
jdbc.url=jdbc:mysql://localhost:3306/common_mapper?useUnicode=true&characterEncoding=utf8
jdbc.driver=com.mysql.jdbc.Driver
2.3创建实体类和mapper类
package com.xiaomifeng1010.mapper.entities;import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;@Entity
@Table(name="tabple_emp")
public class Employee {@Id@GeneratedValue(strategy=GenerationType.IDENTITY)private Integer empId;//emp_id@Column(name="emp_name")private String empName;//emp_name@Column(name="emp_salary")private Double empSalary;//emp_salary@Column(name="emp_age")private Integer empAge;//emp_agepublic Employee() {}public Employee(Integer empId, String empName, Double empSalary, Integer empAge) {super();this.empId = empId;this.empName = empName;this.empSalary = empSalary;this.empAge = empAge;}@Overridepublic String toString() {return "Employee [empId=" + empId + ", empName=" + empName + ", empSalary=" + empSalary + ", empAge=" + empAge+ "]";}public Integer getEmpId() {return empId;}public void setEmpId(Integer empId) {this.empId = empId;}public String getEmpName() {return empName;}public void setEmpName(String empName) {this.empName = empName;}public Double getEmpSalary() {return empSalary;}public void setEmpSalary(Double empSalary) {this.empSalary = empSalary;}public Integer getEmpAge() {return empAge;}public void setEmpAge(Integer empAge) {this.empAge = empAge;}}
创建mapper类:
package com.xiaomifeng1010.mapper.mappers;import com.xiaomifeng1010.mapper.entities.Employee;import tk.mybatis.mapper.common.Mapper;/*** 具体操作数据库的Mapper接口,需要继承通用Mapper提供的核心接口:Mapper<Employee>* 泛型类型就是实体类的类型* @author Lenovo**/
public interface EmployeeMapper extends Mapper<Employee> {}
继承通用mapper接口即可,查看mapper接口源码:
通过继承mapper接口,既可以生成基本的增删改查方法。
创建service类
package com.xiaomifeng1010.mapper.services;import java.util.List;import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import com.xiaomifeng1010.mapper.entities.Employee;
import com.xiaomifeng1010.mapper.mappers.EmployeeMapper;import tk.mybatis.mapper.entity.Example;@Service
public class EmployeeService {@Autowiredprivate EmployeeMapper employeeMapper;public Employee getOne(Employee employeeQueryCondition) {return employeeMapper.selectOne(employeeQueryCondition);}public Employee getEmployeeById(Integer empId) {return employeeMapper.selectByPrimaryKey(empId);}public boolean isExists(Integer empId) {return employeeMapper.existsWithPrimaryKey(empId);}public void saveEmployee(Employee employee) {employeeMapper.insert(employee);}public void saveEmployeeSelective(Employee employee) {employeeMapper.insertSelective(employee);}public void updateEmployeeSelective(Employee employee) {employeeMapper.updateByPrimaryKeySelective(employee);}public void removeEmployee(Employee employee) {employeeMapper.delete(employee);}public void removeEmployeeById(Integer empId) {employeeMapper.deleteByPrimaryKey(empId);}public List<Employee> getEmpListByExample(Example example) {return employeeMapper.selectByExample(example);}public List<Employee> getEmpListByRowBounds(RowBounds rowBounds) {return employeeMapper.selectByRowBounds(null, rowBounds);}}
2.4 单元测试类,编写测试方法
package com.xiaomifeng1010.mapper.test;import java.sql.Connection;
import java.sql.SQLException;import javax.sql.DataSource;import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class MapperTest {private ApplicationContext iocContainer = new ClassPathXmlApplicationContext("spring-context.xml");@Testpublic void testDataSource() throws SQLException {DataSource dataSource = iocContainer.getBean(DataSource.class);Connection connection = dataSource.getConnection();System.out.println(connection);}}
运行后:
获取到了连接。
测试具体增删改查方法:
package com.xiaomifeng1010.mapper.test;import java.util.List;import org.apache.ibatis.session.RowBounds;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;import com.xiaomifeng1010.mapper.entities.Employee;
import com.xiaomifeng1010.mapper.services.EmployeeService;import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;public class EmployeeMapperTest {private ApplicationContext iocContainer = new ClassPathXmlApplicationContext("spring-context.xml");private EmployeeService employeeService = iocContainer.getBean(EmployeeService.class);@Testpublic void testSelectOne() {//1.创建封装查询条件的实体类对象Employee employeeQueryCondition = new Employee(null, "bob", 5560.11, null);//2.执行查询Employee employeeQueryResult = employeeService.getOne(employeeQueryCondition);//3.打印System.out.println(employeeQueryResult);}@Testpublic void testSelect() {}@Testpublic void testSelectAll() {}@Testpublic void testSelectCount() {}@Testpublic void testSelectByPrimaryKey() {//1.提供id值Integer empId = 3;//2.执行根据主键进行的查询Employee employee = employeeService.getEmployeeById(empId);//3.打印结果System.out.println(employee);}@Testpublic void testExistsWithPrimaryKey() {//1.提供主键值Integer empId = 33;//2.执行查询boolean exists = employeeService.isExists(empId);//3.打印结果System.out.println(exists);}@Testpublic void testInsert() {//1.创建实体类对象封装要保存到数据库的数据Employee employee = new Employee(null, "emp03", 3000.00, 23);//2.执行插入操作employeeService.saveEmployee(employee);//3.获取employee对象的主键字段值Integer empId = employee.getEmpId();System.out.println("empId="+empId);}@Testpublic void testInsertSelective() {//1.创建实体类对象封装要保存到数据库的数据Employee employee = new Employee(null, "emp04", null, 23);//2.执行插入操作employeeService.saveEmployeeSelective(employee);}@Testpublic void testUpdateByPrimaryKey() {}@Testpublic void testUpdateByPrimaryKeySelective() {//1.创建用于测试的实体类Employee employee = new Employee(7, "empNewName", null, null);//2.执行更新employeeService.updateEmployeeSelective(employee);}@Testpublic void testDelete() {//1.声明实体类变量作为查询条件Employee employee = null;//2.执行删除employeeService.removeEmployee(employee);}@Testpublic void testDeleteByPrimaryKey() {//1.提供主键值Integer empId = 13;//2.执行删除employeeService.removeEmployeeById(empId);}@Testpublic void testSelectByExample() {//目标:WHERE (emp_salary>? AND emp_age<?) OR (emp_salary<? AND emp_age>?)//1.创建Example对象Example example = new Example(Employee.class);//***********************//i.设置排序信息example.orderBy("empSalary").asc().orderBy("empAge").desc();//ii.设置“去重”example.setDistinct(true);//iii.设置select字段example.selectProperties("empName","empSalary");//***********************//2.通过Example对象创建Criteria对象Criteria criteria01 = example.createCriteria();Criteria criteria02 = example.createCriteria();//3.在两个Criteria对象中分别设置查询条件//property参数:实体类的属性名//value参数:实体类的属性值criteria01.andGreaterThan("empSalary", 3000).andLessThan("empAge", 25);criteria02.andLessThan("empSalary", 5000).andGreaterThan("empAge", 30);//4.使用OR关键词组装两个Criteria对象example.or(criteria02);//5.执行查询List<Employee> empList = employeeService.getEmpListByExample(example);for (Employee employee : empList) {System.out.println(employee);}}@Testpublic void testSelectByRowBounds() {int pageNo = 3;int pageSize = 5;int index = (pageNo - 1) * pageSize;RowBounds rowBounds = new RowBounds(index, pageSize);List<Employee> empList = employeeService.getEmpListByRowBounds(rowBounds);for (Employee employee : empList) {System.out.println(employee);}}}
测试testInsert()方法:
原本5条数据,出入一条,返回id=6
ORM框架之Mybatis(六)mybatis通用mapper相关推荐
- 第一章:ORM框架发展历程和MyBatis的核心应用
ORM框架的发展历史与MyBatis的高级应用 一.ORM框架的发展历程 1. JDBC操作 1.1 JDBC操作的特点 最初的时候我们肯定是直接通过jdbc来直接操作数据库的,本地数据库我们有一张t ...
- (转)MyBatis框架的学习(六)——MyBatis整合Spring
http://blog.csdn.net/yerenyuan_pku/article/details/71904315 本文将手把手教你如何使用MyBatis整合Spring,这儿,我本人使用的MyB ...
- MyBatis 为什么需要通用 Mapper ?
一.通用 Mapper 的用途 ? 我个人最早用 MyBatis 时,先是完全手写,然后用上了 MyBatis 代码生成器(简称为 MBG),在使用 MBG 过程中,发现一个很麻烦的问题,如果数据库字 ...
- MyBatis 为什么需要通用 Mapper ? 1
版权声明:版权归博主所有,转载请带上本文链接!联系方式:abel533@gmail.com https://blog.csdn.net/isea533/article/details/83045335 ...
- mybatis sql linux,通用mapper生成sql及mybatis使用过程
sql装配,自己实现一个,通用mapper和mybatis-generator是两个东西各自功能不同,结合使用而已 通用mapper: 1,省略单表操作的xml 2,不必写实现类(用通用mapper的 ...
- java用tkmapper分组查询_tk.mybatis 中的通用Mapper自定义SQL语句
前言 今天就是想写点什么,其实还有很多没写的东西呢!笔记里边好多东西都挺好的,经验加实践总结出来的.就是都没有系统的整理,至于原因吧,有很多,最重要的一点就是我有点懒.今天写个最简单的东西,现在的开发 ...
- Springboot+Mybatis+通用Mapper多数据源实现数据同步
有个需求需要查询远程数据库,然后将远程数据库中的数据抓取到本地,远程数据库中的数据是每天都增加的,所以就需要写个程序自动实现实时抓取. 这里我用到的框架是Springboot2.0+Mybatis+M ...
- (转)MyBatis框架的学习(七)——MyBatis逆向工程自动生成代码
http://blog.csdn.net/yerenyuan_pku/article/details/71909325 什么是逆向工程 MyBatis的一个主要的特点就是需要程序员自己编写sql,那么 ...
- mysql通用mapper_这就是——通用Mapper
image.png 什么是通用mapper? 通用mapper 可以极大的方便开发人员进行ORM,提供极其方便的单表增删改查. 可以按照自己的需要选择通用方法,还能很方便的开发自己的通用方法. 为什么 ...
- 通用mapper——自定义搭配继承Mapper
前提 通用Mapper--tk.mybatis(Example) 正文 由于tk.mybatis.mapper.common.Mapper中只有 BaseMapper<T>, Exampl ...
最新文章
- .net反射详解 原文://http://blog.csdn.net/wenyan07/article/details/27882363
- 第三届广东省强网杯网络安全大赛WEB题writeup
- windows:(1)xmind常用快捷键
- 吃西瓜 最大子矩阵 三维的。 rqnoj93
- GeoPoint与LocationData
- 使用gdb和core dump迅速定位段错误
- Visual Stdio 注册表相关路径
- android 小学课程,小学课堂(小学学习软件)
- Linux之netstat命令详解
- iPhone Application Programming Guide, Ch4
- ImportError: cannot import name ‘abs‘
- String、StringBuilder、StringBuffer
- LTE通讯相关2:频带、信道带宽和频点号EARFCN
- Node-red初级入门
- LPC1788 IAP的实现及遇见的问题
- WPS的标题样式如何保存成默认
- git-commit-amend踩坑
- ei会议论文录用但不参加会议_科学网—推荐一个录用论文全部发表在EI期刊上的会议 - 徐庆征的博文...
- 《还是要相信》读书笔记
- 庖丁解牛Transformer原理
热门文章
- 电脑经常死机是什么原因
- poi,HSSFWorkbook,Excel导出,代码示例
- linux环境下启动git,linux系统安装git及git常用命令
- python不调包实现sobel_python利用百度云接口实现车牌识别的示例
- 伪元素选择器使用场景2-仿土豆网显示隐藏遮罩案例(CSS3)
- 如何使用Java进行简单爬虫
- vue组件样式scoped
- php+crontab+shell方案实现的秒级定时发起异步请求回调方案
- 第四(装饰器、迭代器、生成器)
- 熟悉 scrollTop ,轻松做5个方面的事情。