MyBatis提供了攔截器接口,我們可以實現自己的攔截器,將其作為一個plugin裝入到SqlSessionFactory中。
首先要說的是,Spring在依賴注入bean的時候,會把所有實現MyBatis中Interceptor接口的所有類都注入到SqlSessionFactory中,作為plugin存在。既然如此,我們集成一個plugin便很簡單了,只需要使用@Bean創建PageHelper對象即可。
1、添加pom依賴
1
2
3
4
5
|
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version> 4.1 . 0 </version> </dependency> |
2、MyBatisConfiguration.java類配置
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
package com.example.mybatis; import java.util.Properties; import javax.sql.DataSource; import org.apache.ibatis.plugin.Interceptor; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.annotation.TransactionManagementConfigurer; import com.github.pagehelper.PageHelper; @Configuration //加上這個注解,使得支持事務 @EnableTransactionManagement public class MyBatisConfig implements TransactionManagementConfigurer { @Autowired private DataSource dataSource; @Override public PlatformTransactionManager annotationDrivenTransactionManager() { return new DataSourceTransactionManager(dataSource); } @Bean (name = "sqlSessionFactory" ) public SqlSessionFactory sqlSessionFactoryBean(PageHelper pageHelper) { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); //自定義數據庫配置的時候,需要將pageHelper的bean注入到Plugins中,如果采用系統默認的數據庫配置,則只需要定義pageHelper的bean,會自動注入。 bean.setPlugins( new Interceptor[] { pageHelper }); try { return bean.getObject(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } @Bean public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) { return new SqlSessionTemplate(sqlSessionFactory); } @Bean public PageHelper pageHelper() { PageHelper pageHelper = new PageHelper(); Properties p = new Properties(); p.setProperty( "offsetAsPageNum" , "true" ); p.setProperty( "rowBoundsWithCount" , "true" ); p.setProperty( "reasonable" , "true" ); p.setProperty( "dialect" , "mysql" ); pageHelper.setProperties(p); return pageHelper; } } |
3、分頁查詢測試
1
2
3
4
5
|
@RequestMapping ( "/likename" ) public List<Student> likeName( @RequestParam String name){ PageHelper.startPage( 1 , 1 ); return stuMapper.likeName(name); } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。