通用mapper认识和用法
认识
什么是通用mapper?
- 通用mapper 可以极大的方便开发人员进行ORM,提供极其方便的单表增删改查。
- 什么是通用mapper,一句话简单说,它就是个辅助mybatis极简单表开发的组件。它不是为了替代mybatis,而是让mybatis的开发更方便。
- 可以按照自己的需要选择通用方法,还能很方便的开发自己的通用方法。
为什么要用通用mapper?
原生Mybatis的痛点
- mapper.xml文件里有大量的sql,当数据库表字段变动,配置文件就要修改
- 需要自己实现sql分页,select * from table where . . . limit 1,3 自己手写分页,除了传参page、pageSize,还需要返回条目总数count。
- 数据库可移植性差:如果项目更换数据库,比如oracle–>mysql,mapper.xml中的sql要重新写,因为Oracle的PLSQL 和mysql 支持的函数是不同的。
- 生成的代码量过大。
- 批量操作,批量插入,批量更新,需要自写。
导包
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>3.1.2</version>
</dependency>
mybatis的config文件:mybatis-mapper-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>
<plugins>
<!-- 分页插件 -->
<plugin interceptor="com.github.pagehelper.PageHelper">
<property name="dialect" value="mysql"/>
<property name="reasonable" value="true"/>
</plugin>
<plugin interceptor="tk.mybatis.mapper.mapperhelper.MapperInterceptor">
<!--================================================-->
<!--可配置参数说明(一般无需修改)-->
<!--================================================-->
<!--UUID生成策略-->
<!--配置UUID生成策略需要使用OGNL表达式-->
<!--默认值32位长度:@java.util.UUID@randomUUID().toString().replace("-", "")-->
<!--<property name="UUID" value="@java.util.UUID@randomUUID().toString()"/>-->
<!--主键自增回写方法,默认值MYSQL,详细说明请看文档-->
<property name="IDENTITY" value="MYSQL"/>
<!--序列的获取规则,使用{num}格式化参数,默认值为{0}.nextval,针对Oracle-->
<!--可选参数一共3个,对应0,1,2,分别为SequenceName,ColumnName,PropertyName-->
<property name="seqFormat" value="{0}.nextval"/>
<!--主键自增回写方法执行顺序,默认AFTER,可选值为(BEFORE|AFTER)-->
<!--<property name="ORDER" value="AFTER"/>-->
<!--通用Mapper接口,多个通用接口用逗号隔开-->
<property name="mappers" value="tk.mybatis.mapper.common.Mapper"/>
</plugin>
</plugins>
</configuration>
spring与mybatis整合配置文件:mybatis.xml
<!-- spring与mybatis整合配置,扫描所有dao -->
<beans:bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<beans:property name="sqlSessionFactory" ref="mybatis.sqlSessionFactory"/>
<beans:property name="basePackage" value="自己的dao包"/>
</beans:bean>
<!-- mybatis文件配置,扫描所有mapper文件 -->
<beans:bean id="mybatis.sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<beans:property name="dataSource" ref="shardingDataSource"/>
<beans:property name="configLocation" value="classpath:mybatis-mapper-config.xml"/>
<beans:property name="mapperLocations">
<beans:list>
<beans:value>classpath:mapper
使用通用Mapper
import tk.mybatis.mapper.common.Mapper;
public interface OrderDao extends Mapper<OrderModel> {
}
这里不止可以继承Mapper,还可以继承其他接口
- BaseMapper:纯增删查改接口
- ConditionMapper : 选择性地按非空条件查询或者删除或者更新
- ExampleMapper : 非选择性按所有条件查询或者删除或者更新
- RowBoundsMapper : 配合分页插件PageHelper可以实现物理分页
调用dao的方法
orderDao.
selectOne(OrderModel record) OrderModel
select(OrderModel. record) List<OrderModet>
updateByPrimaryKeySetective(OrderModeL record) int
updateByPrimaryKey(OrderModel. record) int
delete(OrderModel record) int
deleteByExample(Object example) int
deLeteByPrimaryKey(Object key) int
insert(OrderModel record) int
insertSelective(OrderModel record) int
selectByExample(Object example) List<OrderModel>
selectByExampleAndRowBounds(Object example, RowBounds rowB... List<OrderModel>
selectByPrimaryKey(Object key) OrderModel
selectByRowBounds(OrderModel record, RowBounds rowBounds) List<OrderModel>
selectCount(OrderModel record) int
selectCountByExample(Object example) int
updateByExample(OrderModel record, Object example) int
updateByExampleSelective(OrderModel record, Object example) int
初识 tk.mybatis.mapper 通用mapper
传统Mybatis用法
Spring boot
引用基本的jar到pom
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>1.5.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>1.5.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
sql 数据准备
DROP TABLE IF EXISTS category;
CREATE TABLE category (
category_id INT PRIMARY KEY,
category_name VARCHAR (50) NOT NULL,
description VARCHAR (100)
);
DROP TABLE IF EXISTS product;
CREATE TABLE product (
product_id INT PRIMARY KEY auto_increment,
category_id INT NOT NULL,
product_name VARCHAR (50) NOT NULL,
price DECIMAL
);
DELETE FROM category;
INSERT INTO category (category_id, category_name, description) VALUES
(1, 'Beverages', 'test'),
(2, 'Condiments', 'test'),
(3, 'Oil', 'test');
DELETE FROM product;
INSERT INTO product (product_id, category_id, product_name, price) VALUES
(1, 1, 'Northwind Traders Chai', 18.0000),
(2, 2, 'Northwind Traders Syrup', 7.5000),
(3, 2, 'Northwind Traders Cajun Seasoning', 16.5000),
(4, 3, 'Northwind Traders Olive Oil', 16.5000),
(5, 3, 'Northwind Traders Olive Oil2', 16.5000);
entity
public class Product {
private Integer productID;
private String productName;
private BigDecimal price;
private Integer categoryID;
}
@Table(name = "category")
public class Category {
@Id
@Column(name = "category_id")
private Integer categoryID;
private String categoryName;
private String description;
}
Dao(传统mybatis用法)
@Mapper
public interface ProductDao {
List<Product> getProducts();
}
mapper
- 传统mybatis 我们必须有个xml 文件和Dao 对应起来, tk.maybatis.mapper无需此文件。
<mapper namespace="com.github.wz2cool.demo.tk.mybatis.mapper.ProductDao">
<select id="getProducts" resultType="com.github.wz2cool.demo.tk.mybatis.model.entity.table.Product">
SELECT * FROM product
</select>
</mapper>
设置扫描包
@SpringBootApplication
@MapperScan(basePackages = "com.github.wz2cool.demo.tk.mybatis.mapper")
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
- application.properies(传统mybatis配置,tk.maybatis.mapper可以省略这里的配置。)
mybatis.type-aliases-package=com.github.wz2cool.demo.tk.mybatis.mapper
mybatis.mapper-locations=classpath:com.github.wz2cool.demo.tk.mybatis.mapper
测试
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = TestApplication.class)
public class SimpleTest {
@Autowired
private ProductDao productDao;
@Test
public void testSelect() throws Exception {
List<Product> productList = productDao.getProducts();
assertEquals(true, productList.size() > 0);
}
}
tk.mybatis.mapper 用法
添加引用
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>3.4.2</version>
</dependency>
<!--mapper-->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>1.1.3</version>
</dependency>
继承通用mapper(无xml)
public interface CategoryDao extends Mapper<Category> {
}
测试调用
- dao 里面自带很多方法,比如 selectAll(), insert().
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = TestApplication.class)
public class SimpleTkMapperTest {
@Autowired
private CategoryDao categoryDao;
@Test
public void selectAllTest() {
List<Category> categories = categoryDao.selectAll();
assertEquals(true, categories.size() > 0);
}
@Test
public void insertTest() {
Category newCategory = new Category();
newCategory.setCategoryID(1000);
newCategory.setCategoryName("test");
newCategory.setDescription("for test");
int result = categoryDao.insert(newCategory);
assertEquals(1, result);
}
}