├── README.md ├── build.gradle ├── settings.gradle └── src └── main ├── java └── com │ └── mm │ └── dev │ ├── DevApplication.java │ ├── config │ ├── ApplicationFilter.java │ ├── ApplicationServlet.java │ └── DataSourceConfig.java │ ├── controller │ └── HelloSpringBootController.java │ ├── dao │ ├── jpa │ │ └── UserDao.java │ └── mapper │ │ └── UserMapper.java │ ├── entity │ └── User.java │ ├── expands │ └── mybatis │ │ ├── dialect │ │ ├── Dialect.java │ │ ├── MySql5Dialect.java │ │ ├── OracleDialect.java │ │ └── SQLServer2005Dialect.java │ │ └── plugins │ │ ├── PaginationResultSetInterceptor.java │ │ └── PaginationStatementInterceptor.java │ └── service │ ├── UserService.java │ └── impl │ └── UserServiceImpl.java └── resources ├── application.properties ├── datasource.properties ├── logback.xml ├── mapper └── user-mapper.xml └── static └── img └── 14ce36d3d539b600354070b7eb50352ac65cb727.jpg /README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liumangafei/spring-boot-jpa-mybatis-gradle/bd7f1f81222ba347774c36104b4429df67b2d0d2/README.md -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | group 'com.mm' 2 | version '1.0-SNAPSHOT' 3 | 4 | 5 | buildscript { 6 | repositories { 7 | 8 | mavenLocal() 9 | 10 | // maven { 11 | // url 'http://192.168.8.91:8081/nexus/content/groups/public/' 12 | // artifactUrls 'http://192.168.8.91:8081/nexus/content/repositories/thirdparty/' 13 | // artifactUrls 'http://192.168.8.91:8081/nexus/content/repositories/Newmix-Releases/' 14 | // artifactUrls 'http://192.168.8.91:8081/nexus/content/repositories/Newmix-Snapshots/' 15 | // } 16 | 17 | mavenCentral() 18 | 19 | } 20 | dependencies { 21 | classpath 'org.springframework.boot:spring-boot-gradle-plugin:1.2.4.RELEASE' 22 | classpath 'org.springframework:springloaded:1.2.3.RELEASE' 23 | } 24 | } 25 | 26 | 27 | apply plugin: 'java' 28 | apply plugin: 'maven' 29 | apply plugin: 'idea' 30 | apply plugin: 'spring-boot' 31 | 32 | 33 | 34 | idea { 35 | module { 36 | inheritOutputDirs = false 37 | outputDir = file("$buildDir/classes/main/") 38 | } 39 | } 40 | 41 | 42 | 43 | jar { 44 | baseName = 'MAN_DEV' 45 | version = '1.0-SNAPSHOT' 46 | } 47 | 48 | 49 | 50 | repositories { 51 | 52 | mavenLocal() 53 | 54 | // maven { 55 | // url 'http://192.168.8.91:8081/nexus/content/groups/public/' 56 | // artifactUrls 'http://192.168.8.91:8081/nexus/content/repositories/thirdparty/' 57 | // artifactUrls 'http://192.168.8.91:8081/nexus/content/repositories/Newmix-Releases/' 58 | // artifactUrls 'http://192.168.8.91:8081/nexus/content/repositories/Newmix-Snapshots/' 59 | // } 60 | 61 | mavenCentral() 62 | 63 | } 64 | 65 | 66 | 67 | dependencies { 68 | 69 | compile 'com.alibaba:druid:1.0.14' 70 | compile 'org.mybatis:mybatis:3.2.8' 71 | compile 'org.mybatis:mybatis-spring:1.2.2' 72 | compile 'mysql:mysql-connector-java:5.1.35' 73 | 74 | compile 'org.springframework.boot:spring-boot-starter-jdbc:1.2.4.RELEASE' 75 | compile 'org.springframework.boot:spring-boot-starter-data-jpa:1.2.4.RELEASE' 76 | compile 'org.springframework.security:spring-security-config:3.2.7.RELEASE' 77 | 78 | compile ('org.springframework.boot:spring-boot-starter-web:1.2.4.RELEASE') { 79 | exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat' 80 | } 81 | 82 | compile ('org.springframework.boot:spring-boot-starter-jetty:1.2.4.RELEASE') { 83 | exclude group: 'org.eclipse.jetty.websocket' 84 | } 85 | 86 | testCompile group: 'junit', name: 'junit', version: '4.11' 87 | } 88 | 89 | 90 | 91 | uploadArchives { 92 | 93 | repositories.mavenDeployer { 94 | 95 | repository(url: 'http://192.168.8.91:8081/nexus/content/repositories/Newmix-Releases') { 96 | authentication(userName: 'admin', password: 'admin123') 97 | } 98 | 99 | snapshotRepository(url: 'http://192.168.8.91:8081/nexus/content/repositories/Newmix-Snapshots') { 100 | authentication(userName: 'admin', password: 'admin123') 101 | } 102 | 103 | pom.version = '1.0-SNAPSHOT' 104 | pom.groupId = 'com.mm' 105 | pom.artifactId = 'dev' 106 | pom.packaging = 'jar' 107 | 108 | } 109 | 110 | } -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'dev' 2 | 3 | -------------------------------------------------------------------------------- /src/main/java/com/mm/dev/DevApplication.java: -------------------------------------------------------------------------------- 1 | package com.mm.dev; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.boot.autoconfigure.orm.jpa.EntityManagerFactoryBuilder; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.PropertySource; 8 | import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; 9 | 10 | import javax.sql.DataSource; 11 | import java.util.Properties; 12 | 13 | /** 14 | * Created by Lipengfei on 2015/6/24. 15 | */ 16 | @SpringBootApplication 17 | @PropertySource(value = {"classpath:/application.properties", "classpath:/datasource.properties"}) 18 | public class DevApplication { 19 | 20 | public static void main(String[] args) { 21 | SpringApplication.run(DevApplication.class, args); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/mm/dev/config/ApplicationFilter.java: -------------------------------------------------------------------------------- 1 | package com.mm.dev.config; 2 | 3 | import com.alibaba.druid.support.http.WebStatFilter; 4 | import org.springframework.boot.context.embedded.FilterRegistrationBean; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.web.filter.CharacterEncodingFilter; 8 | 9 | import java.util.ArrayList; 10 | import java.util.List; 11 | 12 | 13 | @Configuration 14 | public class ApplicationFilter { 15 | 16 | @Bean 17 | public FilterRegistrationBean encodingFilter() { 18 | CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter(); 19 | FilterRegistrationBean mappingEncodingFilter = new FilterRegistrationBean(encodingFilter); 20 | 21 | List urlPatterns = new ArrayList(); 22 | urlPatterns.add("/*"); 23 | mappingEncodingFilter.setUrlPatterns(urlPatterns); 24 | mappingEncodingFilter.setOrder(2); 25 | 26 | return mappingEncodingFilter; 27 | } 28 | 29 | @Bean 30 | public FilterRegistrationBean webStatFilter() { 31 | 32 | WebStatFilter webStatFilter = new WebStatFilter(); 33 | FilterRegistrationBean mappingDruid = new FilterRegistrationBean(webStatFilter); 34 | 35 | List urlPatterns = new ArrayList(); 36 | urlPatterns.add("/*"); 37 | mappingDruid.setUrlPatterns(urlPatterns); 38 | mappingDruid.setOrder(3); 39 | 40 | return mappingDruid; 41 | } 42 | 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/mm/dev/config/ApplicationServlet.java: -------------------------------------------------------------------------------- 1 | package com.mm.dev.config; 2 | 3 | import com.alibaba.druid.support.http.StatViewServlet; 4 | import org.springframework.beans.factory.annotation.Qualifier; 5 | import org.springframework.boot.context.embedded.ServletRegistrationBean; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | 9 | import javax.servlet.Servlet; 10 | 11 | /** 12 | * Created by Administrator on 2015/6/29. 13 | */ 14 | @Configuration 15 | public class ApplicationServlet { 16 | 17 | @Bean 18 | public ServletRegistrationBean mappingStatViewServlet(){ 19 | 20 | StatViewServlet statViewServlet = new StatViewServlet(); 21 | ServletRegistrationBean mappingStatViewServlet = new ServletRegistrationBean(statViewServlet,"/druid/*"); 22 | 23 | return mappingStatViewServlet; 24 | } 25 | 26 | 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/mm/dev/config/DataSourceConfig.java: -------------------------------------------------------------------------------- 1 | package com.mm.dev.config; 2 | 3 | import com.alibaba.druid.pool.DruidDataSource; 4 | import com.mm.dev.expands.mybatis.plugins.PaginationResultSetInterceptor; 5 | import com.mm.dev.expands.mybatis.plugins.PaginationStatementInterceptor; 6 | import org.apache.ibatis.plugin.Interceptor; 7 | import org.apache.ibatis.session.SqlSessionFactory; 8 | import org.mybatis.spring.SqlSessionFactoryBean; 9 | import org.mybatis.spring.SqlSessionTemplate; 10 | import org.mybatis.spring.annotation.MapperScan; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.boot.autoconfigure.orm.jpa.EntityManagerFactoryBuilder; 13 | import org.springframework.context.annotation.Bean; 14 | import org.springframework.context.annotation.Configuration; 15 | import org.springframework.core.env.Environment; 16 | import org.springframework.core.io.support.PathMatchingResourcePatternResolver; 17 | import org.springframework.core.io.support.ResourcePatternResolver; 18 | import org.springframework.jdbc.datasource.DataSourceTransactionManager; 19 | import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; 20 | import org.springframework.transaction.annotation.EnableTransactionManagement; 21 | import org.springframework.util.StringUtils; 22 | 23 | import javax.sql.DataSource; 24 | import java.util.Properties; 25 | 26 | /** 27 | * Created by Lipengfei on 2015/6/26. 28 | */ 29 | @Configuration 30 | @MapperScan(basePackages = "com.mm.dev.dao.mapper", sqlSessionFactoryRef = "sqlSessionFactory", sqlSessionTemplateRef = "sqlSessionTemplate") 31 | @EnableTransactionManagement 32 | public class DataSourceConfig { 33 | 34 | @Autowired 35 | private Environment env; 36 | 37 | @Bean 38 | public DataSource dataSource(){ 39 | 40 | DruidDataSource dataSource = new DruidDataSource(); 41 | dataSource.setDriverClassName(env.getProperty("mysql.driverClassName")); 42 | dataSource.setUrl(env.getProperty("mysql.url")); 43 | dataSource.setUsername(env.getProperty("mysql.username")); 44 | dataSource.setPassword(env.getProperty("mysql.password")); 45 | dataSource.setInitialSize(Integer.parseInt(env.getProperty("mysql.initialSize"))); 46 | dataSource.setMinIdle(Integer.parseInt(env.getProperty("mysql.minIdle"))); 47 | dataSource.setMaxActive(Integer.parseInt(env.getProperty("mysql.maxActive"))); 48 | 49 | return dataSource; 50 | } 51 | 52 | @Bean 53 | public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception { 54 | 55 | SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); 56 | 57 | // 获取properties中的对应配置信息 58 | String mapperPackage = env.getProperty("spring.mybatis.mapperPackage"); 59 | String dialect = env.getProperty("spring.mybatis.dialect"); 60 | 61 | Properties properties = new Properties(); 62 | properties.setProperty("dialect", dialect); 63 | 64 | 65 | sessionFactory.setDataSource(dataSource); 66 | sessionFactory.setConfigurationProperties(properties); 67 | // 设置MapperLocations路径 68 | if(!StringUtils.isEmpty(mapperPackage)){ 69 | ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); 70 | sessionFactory.setMapperLocations(resourcePatternResolver.getResources(mapperPackage)); 71 | } 72 | // 设置插件 73 | sessionFactory.setPlugins(new Interceptor[]{ 74 | new PaginationStatementInterceptor(), 75 | new PaginationResultSetInterceptor() 76 | }); 77 | 78 | return sessionFactory.getObject(); 79 | } 80 | 81 | @Bean 82 | public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory){ 83 | return new SqlSessionTemplate(sqlSessionFactory); 84 | } 85 | 86 | @Bean 87 | public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder, DataSource dataSource) { 88 | 89 | LocalContainerEntityManagerFactoryBean entityManagerFactory = builder.dataSource(dataSource).build(); 90 | 91 | Properties properties = new Properties(); 92 | properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect"); 93 | properties.setProperty("hibernate.hbm2ddl.auto", "update"); 94 | 95 | entityManagerFactory.setPackagesToScan("com.mm.dev.entity"); 96 | entityManagerFactory.setJpaProperties(properties); 97 | 98 | return entityManagerFactory; 99 | } 100 | 101 | @Bean 102 | public DataSourceTransactionManager transactionManager(DataSource dataSource){ 103 | return new DataSourceTransactionManager(dataSource); 104 | } 105 | 106 | } 107 | -------------------------------------------------------------------------------- /src/main/java/com/mm/dev/controller/HelloSpringBootController.java: -------------------------------------------------------------------------------- 1 | package com.mm.dev.controller; 2 | 3 | import com.mm.dev.entity.User; 4 | import com.mm.dev.service.UserService; 5 | import org.apache.commons.logging.Log; 6 | import org.apache.commons.logging.LogFactory; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.data.domain.Page; 9 | import org.springframework.data.domain.Pageable; 10 | import org.springframework.stereotype.Controller; 11 | import org.springframework.transaction.annotation.Transactional; 12 | import org.springframework.web.bind.annotation.RequestMapping; 13 | import org.springframework.web.bind.annotation.ResponseBody; 14 | 15 | import java.util.List; 16 | 17 | /** 18 | * Created by Lipengfei on 2015/6/24. 19 | */ 20 | @Controller 21 | @RequestMapping("/") 22 | public class HelloSpringBootController { 23 | 24 | private final static Log log = LogFactory.getLog(HelloSpringBootController.class); 25 | 26 | @Autowired 27 | private UserService userService; 28 | 29 | @Transactional 30 | @RequestMapping("/") 31 | @ResponseBody 32 | public String sayHello(Pageable pageable){ 33 | 34 | Page all = userService.getAll(pageable); 35 | 36 | User user = userService.getUser(1L); 37 | 38 | List userList = userService.getUserList(); 39 | 40 | Page allList = userService.getUserAll(pageable); 41 | 42 | System.out.println(all.getTotalPages()); 43 | System.out.println(user.getId()); 44 | System.out.println(userList.get(0).getId()); 45 | System.out.println(allList.getTotalPages()); 46 | 47 | userService.save(); 48 | userService.saveUser(); 49 | 50 | return "hello SpringBoot! -- userId:"; 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/mm/dev/dao/jpa/UserDao.java: -------------------------------------------------------------------------------- 1 | package com.mm.dev.dao.jpa; 2 | 3 | import com.mm.dev.entity.User; 4 | import org.springframework.data.domain.Page; 5 | import org.springframework.data.domain.Pageable; 6 | import org.springframework.data.jpa.repository.JpaRepository; 7 | import org.springframework.stereotype.Repository; 8 | 9 | /** 10 | * Created by Lipengfei on 2015/6/27. 11 | */ 12 | @Repository 13 | public interface UserDao extends JpaRepository { 14 | 15 | Page findAll(Pageable pageable); 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/mm/dev/dao/mapper/UserMapper.java: -------------------------------------------------------------------------------- 1 | package com.mm.dev.dao.mapper; 2 | 3 | import com.mm.dev.entity.User; 4 | import org.apache.ibatis.annotations.Param; 5 | import org.springframework.data.domain.Page; 6 | import org.springframework.data.domain.Pageable; 7 | 8 | import java.util.List; 9 | 10 | /** 11 | * Created by Lipengfei on 2015/6/26. 12 | */ 13 | public interface UserMapper { 14 | 15 | List findAll(); 16 | 17 | Page getUserAll(@Param("pageable")Pageable pageable); 18 | 19 | void save(User user); 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/mm/dev/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.mm.dev.entity; 2 | 3 | import javax.persistence.*; 4 | 5 | /** 6 | * Created by Lipengfei on 2015/6/26. 7 | */ 8 | @Entity 9 | @Table(name = "user") 10 | public class User { 11 | 12 | @Id 13 | @GeneratedValue(strategy = GenerationType.AUTO) 14 | private Long id; 15 | 16 | private String username; 17 | 18 | private String password; 19 | 20 | public Long getId() { 21 | return id; 22 | } 23 | 24 | public void setId(Long id) { 25 | this.id = id; 26 | } 27 | 28 | public String getUsername() { 29 | return username; 30 | } 31 | 32 | public void setUsername(String username) { 33 | this.username = username; 34 | } 35 | 36 | public String getPassword() { 37 | return password; 38 | } 39 | 40 | public void setPassword(String password) { 41 | this.password = password; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/mm/dev/expands/mybatis/dialect/Dialect.java: -------------------------------------------------------------------------------- 1 | package com.mm.dev.expands.mybatis.dialect; 2 | 3 | public abstract class Dialect { 4 | 5 | public static enum Type { 6 | MYSQL, ORACLE, SQLSERVER 7 | } 8 | 9 | public abstract String getLimitString(String querySqlString, int offset, int limit); 10 | 11 | public abstract String getCountString(String querySqlString); 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/mm/dev/expands/mybatis/dialect/MySql5Dialect.java: -------------------------------------------------------------------------------- 1 | package com.mm.dev.expands.mybatis.dialect; 2 | 3 | public class MySql5Dialect extends Dialect { 4 | 5 | public String getLimitString(String querySqlString, int offset, int limit) { 6 | return querySqlString + " limit " + offset + " ," + limit; 7 | } 8 | 9 | @Override 10 | public String getCountString(String querySqlString) { 11 | 12 | int limitIndex = querySqlString.lastIndexOf("limit"); 13 | 14 | if(limitIndex != -1){ 15 | querySqlString = querySqlString.substring(0, limitIndex != -1 ? limitIndex : querySqlString.length() - 1); 16 | } 17 | 18 | return "SELECT COUNT(*) FROM (" + querySqlString + ") tem"; 19 | } 20 | 21 | public boolean supportsLimit() { 22 | return true; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/mm/dev/expands/mybatis/dialect/OracleDialect.java: -------------------------------------------------------------------------------- 1 | package com.mm.dev.expands.mybatis.dialect; 2 | 3 | public class OracleDialect extends Dialect { 4 | 5 | public String getLimitString(String querySqlString, int offset, int limit) { 6 | 7 | boolean isForUpdate = false; 8 | if (querySqlString.toLowerCase().endsWith(" for update")) { 9 | querySqlString = querySqlString.substring(0, querySqlString.length() - 11); 10 | isForUpdate = true; 11 | } 12 | 13 | StringBuffer pagingSelect = new StringBuffer(querySqlString.length() + 100); 14 | 15 | pagingSelect 16 | .append("select * from ( select row_.*, rownum rownum_ from ( "); 17 | 18 | pagingSelect.append(querySqlString); 19 | 20 | pagingSelect.append(" ) row_ ) where rownum_ > " + offset 21 | + " and rownum_ <= " + (offset + limit)); 22 | 23 | if (isForUpdate) { 24 | pagingSelect.append(" for update"); 25 | } 26 | 27 | return pagingSelect.toString(); 28 | } 29 | 30 | @Override 31 | public String getCountString(String querySqlString) { 32 | return null; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/mm/dev/expands/mybatis/dialect/SQLServer2005Dialect.java: -------------------------------------------------------------------------------- 1 | package com.mm.dev.expands.mybatis.dialect; 2 | 3 | /** 4 | * Created with IntelliJ IDEA. 5 | * User: LPF 6 | * Date: 13-10-18 7 | * Time: 下午1:41 8 | * To change this template use File | Settings | File Templates. 9 | */ 10 | public class SQLServer2005Dialect extends Dialect{ 11 | 12 | @Override 13 | public String getLimitString(String querySqlString, int offset, int limit) { 14 | StringBuffer pagingBuilder = new StringBuffer(); 15 | String orderby = getOrderByPart(querySqlString); 16 | String distinctStr = ""; 17 | 18 | String loweredString = querySqlString.toLowerCase(); 19 | String sqlPartString = querySqlString; 20 | if (loweredString.trim().startsWith("select")) { 21 | int index = 6; 22 | if (loweredString.startsWith("select distinct")) { 23 | distinctStr = "DISTINCT "; 24 | index = 15; 25 | } 26 | sqlPartString = sqlPartString.substring(index); 27 | } 28 | pagingBuilder.append(sqlPartString); 29 | 30 | // if no ORDER BY is specified use fake ORDER BY field to avoid errors 31 | if (orderby == null || orderby.length() == 0) { 32 | orderby = "ORDER BY CURRENT_TIMESTAMP"; 33 | } 34 | 35 | StringBuffer result = new StringBuffer(); 36 | result.append("WITH query AS (SELECT ") 37 | .append(distinctStr) 38 | .append("TOP 100 PERCENT ") 39 | .append(" ROW_NUMBER() OVER (") 40 | .append(orderby) 41 | .append(") as __row_number__, ") 42 | .append(pagingBuilder) 43 | .append(") SELECT * FROM query WHERE __row_number__ BETWEEN ") 44 | .append(offset + 1).append(" AND ").append(offset+limit) 45 | .append(" ORDER BY __row_number__"); 46 | 47 | return result.toString(); 48 | } 49 | 50 | static String getOrderByPart(String sql) { 51 | String loweredString = sql.toLowerCase(); 52 | int orderByIndex = loweredString.indexOf("order by"); 53 | if (orderByIndex != -1) { 54 | // if we find a new "order by" then we need to ignore 55 | // the previous one since it was probably used for a subquery 56 | return sql.substring(orderByIndex); 57 | } else { 58 | return ""; 59 | } 60 | } 61 | 62 | @Override 63 | public String getCountString(String querySqlString) { 64 | return null; 65 | } 66 | } -------------------------------------------------------------------------------- /src/main/java/com/mm/dev/expands/mybatis/plugins/PaginationResultSetInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.mm.dev.expands.mybatis.plugins; 2 | 3 | import com.mm.dev.expands.mybatis.dialect.Dialect; 4 | import com.mm.dev.expands.mybatis.dialect.MySql5Dialect; 5 | import com.mm.dev.expands.mybatis.dialect.OracleDialect; 6 | import com.mm.dev.expands.mybatis.dialect.SQLServer2005Dialect; 7 | import org.apache.commons.logging.Log; 8 | import org.apache.commons.logging.LogFactory; 9 | import org.apache.ibatis.binding.MapperMethod; 10 | import org.apache.ibatis.executor.parameter.ParameterHandler; 11 | import org.apache.ibatis.executor.resultset.DefaultResultSetHandler; 12 | import org.apache.ibatis.executor.resultset.ResultSetHandler; 13 | import org.apache.ibatis.mapping.BoundSql; 14 | import org.apache.ibatis.plugin.*; 15 | import org.apache.ibatis.reflection.MetaObject; 16 | import org.apache.ibatis.reflection.factory.DefaultObjectFactory; 17 | import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory; 18 | import org.apache.ibatis.session.Configuration; 19 | import org.apache.ibatis.session.SqlSession; 20 | import org.apache.ibatis.session.SqlSessionFactory; 21 | import org.apache.ibatis.session.SqlSessionFactoryBuilder; 22 | import org.springframework.data.domain.Page; 23 | import org.springframework.data.domain.PageImpl; 24 | import org.springframework.data.domain.Pageable; 25 | 26 | import java.sql.PreparedStatement; 27 | import java.sql.ResultSet; 28 | import java.sql.SQLException; 29 | import java.sql.Statement; 30 | import java.util.ArrayList; 31 | import java.util.List; 32 | import java.util.Properties; 33 | 34 | @Intercepts({@Signature(type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class})}) 35 | public class PaginationResultSetInterceptor implements Interceptor { 36 | 37 | private final static Log log = LogFactory.getLog(PaginationResultSetInterceptor.class); 38 | 39 | @Override 40 | public Object intercept(Invocation invocation) throws Throwable { 41 | 42 | DefaultResultSetHandler resultSetHandler = (DefaultResultSetHandler) invocation.getTarget(); 43 | MetaObject metaResultSetHandler = MetaObject.forObject(resultSetHandler, new DefaultObjectFactory(), new DefaultObjectWrapperFactory()); 44 | 45 | try { 46 | ParameterHandler parameterHandler = (ParameterHandler) metaResultSetHandler.getValue("parameterHandler"); 47 | Object parameterObject = parameterHandler.getParameterObject(); 48 | 49 | Pageable pagination = null; 50 | 51 | if(parameterObject instanceof MapperMethod.ParamMap){ 52 | 53 | MapperMethod.ParamMap paramMapObject = (MapperMethod.ParamMap)parameterObject ; 54 | 55 | 56 | if(paramMapObject != null){ 57 | for(Object key : paramMapObject.keySet()){ 58 | if(paramMapObject.get(key) instanceof Pageable){ 59 | pagination = (Pageable) paramMapObject.get(key); 60 | break; 61 | } 62 | } 63 | } 64 | } 65 | 66 | if (pagination != null) { 67 | 68 | BoundSql boundSql = (BoundSql) metaResultSetHandler.getValue("parameterHandler.boundSql"); 69 | Configuration configuration = (Configuration) metaResultSetHandler.getValue("configuration"); 70 | String originalSql = boundSql.getSql(); 71 | 72 | 73 | Dialect.Type databaseType = Dialect.Type.valueOf(configuration.getVariables().getProperty("dialect").toUpperCase()); 74 | Dialect dialect = null; 75 | 76 | switch (databaseType) { 77 | case MYSQL: 78 | dialect = new MySql5Dialect(); 79 | break; 80 | case ORACLE: 81 | dialect = new OracleDialect(); 82 | break; 83 | case SQLSERVER: 84 | dialect = new SQLServer2005Dialect(); 85 | break; 86 | } 87 | 88 | 89 | // 修改sql,用于返回总记录数 90 | String sql = dialect.getCountString(originalSql); 91 | Long totalRecord = getTotalRecord(configuration, sql); 92 | 93 | 94 | Object result = invocation.proceed(); 95 | Page page = new PageImpl((List)result, pagination, totalRecord); 96 | 97 | 98 | // // 设置返回对象类型 99 | // metaResultSetHandler.setValue("mappedStatement.resultMaps[0].type.name", Page.class.getName()); 100 | 101 | // 设置返回值 102 | List pageList = new ArrayList(); 103 | pageList.add(page); 104 | 105 | return pageList; 106 | } 107 | } catch (Exception e) { 108 | throw new Exception("Overwrite SQL : Fail!"); 109 | } 110 | 111 | return invocation.proceed(); 112 | } 113 | 114 | /** 115 | * 获取总记录数 116 | * @param sql 117 | * @return 118 | */ 119 | private Long getTotalRecord(Configuration configuration, String sql){ 120 | 121 | Long result = 0L; 122 | 123 | SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration); 124 | SqlSession session = sqlSessionFactory.openSession(); 125 | 126 | try { 127 | PreparedStatement statement = session.getConnection().prepareStatement(sql); 128 | ResultSet resultSet = statement.executeQuery(); 129 | while (resultSet.next()){ 130 | result = resultSet.getLong(1); 131 | } 132 | } catch (SQLException e) { 133 | e.printStackTrace(); 134 | } finally { 135 | session.close(); 136 | } 137 | 138 | return result; 139 | } 140 | 141 | @Override 142 | public Object plugin(Object target) { 143 | return Plugin.wrap(target, this); 144 | } 145 | 146 | @Override 147 | public void setProperties(Properties properties) { 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /src/main/java/com/mm/dev/expands/mybatis/plugins/PaginationStatementInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.mm.dev.expands.mybatis.plugins; 2 | 3 | import com.mm.dev.expands.mybatis.dialect.Dialect; 4 | import com.mm.dev.expands.mybatis.dialect.MySql5Dialect; 5 | import com.mm.dev.expands.mybatis.dialect.OracleDialect; 6 | import com.mm.dev.expands.mybatis.dialect.SQLServer2005Dialect; 7 | import org.apache.commons.logging.Log; 8 | import org.apache.commons.logging.LogFactory; 9 | import org.apache.ibatis.binding.MapperMethod; 10 | import org.apache.ibatis.executor.parameter.ParameterHandler; 11 | import org.apache.ibatis.executor.statement.StatementHandler; 12 | import org.apache.ibatis.mapping.BoundSql; 13 | import org.apache.ibatis.plugin.*; 14 | import org.apache.ibatis.reflection.MetaObject; 15 | import org.apache.ibatis.reflection.factory.DefaultObjectFactory; 16 | import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory; 17 | import org.apache.ibatis.session.Configuration; 18 | import org.springframework.data.domain.Pageable; 19 | 20 | import java.sql.Connection; 21 | import java.util.Properties; 22 | 23 | @Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class})}) 24 | public class PaginationStatementInterceptor implements Interceptor { 25 | 26 | private final static Log log = LogFactory 27 | .getLog(PaginationStatementInterceptor.class); 28 | 29 | @Override 30 | public Object intercept(Invocation invocation) throws Throwable { 31 | 32 | StatementHandler statementHandler = (StatementHandler) invocation.getTarget(); 33 | 34 | ParameterHandler parameterHandler = statementHandler.getParameterHandler(); 35 | Object parameterObject = parameterHandler.getParameterObject(); 36 | 37 | Pageable pagination = null; 38 | 39 | if(parameterObject instanceof MapperMethod.ParamMap){ 40 | 41 | MapperMethod.ParamMap paramMapObject = (MapperMethod.ParamMap)parameterObject ; 42 | 43 | 44 | if(paramMapObject != null){ 45 | for(Object key : paramMapObject.keySet()){ 46 | if(paramMapObject.get(key) instanceof Pageable){ 47 | pagination = (Pageable) paramMapObject.get(key); 48 | break; 49 | } 50 | } 51 | } 52 | } 53 | 54 | if (pagination != null) { 55 | 56 | MetaObject metaStatementHandler = MetaObject.forObject(statementHandler, new DefaultObjectFactory(), new DefaultObjectWrapperFactory()); 57 | Configuration configuration = (Configuration) metaStatementHandler.getValue("delegate.configuration"); 58 | Dialect.Type databaseType = null; 59 | 60 | try { 61 | databaseType = Dialect.Type.valueOf(configuration.getVariables().getProperty("dialect").toUpperCase()); 62 | } catch (Exception e) { 63 | throw new Exception("Generate SQL: Obtain DatabaseType Failed!"); 64 | } 65 | 66 | Dialect dialect = null; 67 | switch (databaseType) { 68 | case MYSQL: 69 | dialect = new MySql5Dialect(); 70 | break; 71 | case ORACLE: 72 | dialect = new OracleDialect(); 73 | break; 74 | case SQLSERVER: 75 | dialect = new SQLServer2005Dialect(); 76 | break; 77 | } 78 | 79 | String originalSql = (String) metaStatementHandler.getValue("delegate.boundSql.sql"); 80 | metaStatementHandler.setValue("delegate.boundSql.sql", dialect.getLimitString(originalSql, pagination.getPageNumber(), pagination.getPageSize())); 81 | 82 | if (log.isDebugEnabled()) { 83 | BoundSql boundSql = statementHandler.getBoundSql(); 84 | log.debug("Generate SQL : " + boundSql.getSql()); 85 | } 86 | 87 | return invocation.proceed(); 88 | } 89 | 90 | return invocation.proceed(); 91 | } 92 | 93 | @Override 94 | public Object plugin(Object target) { 95 | return Plugin.wrap(target, this); 96 | } 97 | 98 | @Override 99 | public void setProperties(Properties properties) { 100 | } 101 | 102 | } 103 | -------------------------------------------------------------------------------- /src/main/java/com/mm/dev/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.mm.dev.service; 2 | 3 | import com.mm.dev.entity.User; 4 | import org.springframework.data.domain.Page; 5 | import org.springframework.data.domain.Pageable; 6 | 7 | import java.util.List; 8 | 9 | /** 10 | * Created by Lipengfei on 2015/6/26. 11 | */ 12 | public interface UserService { 13 | 14 | User getUser(Long id); 15 | 16 | Page getAll(Pageable pageable); 17 | 18 | List getUserList(); 19 | 20 | Page getUserAll(Pageable pageable); 21 | 22 | void save(); 23 | 24 | void saveUser(); 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/mm/dev/service/impl/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.mm.dev.service.impl; 2 | 3 | import com.mm.dev.dao.jpa.UserDao; 4 | import com.mm.dev.dao.mapper.UserMapper; 5 | import com.mm.dev.entity.User; 6 | import com.mm.dev.service.UserService; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.data.domain.Page; 9 | import org.springframework.data.domain.Pageable; 10 | import org.springframework.stereotype.Service; 11 | import org.springframework.transaction.annotation.Transactional; 12 | 13 | import java.util.List; 14 | 15 | /** 16 | * Created by Lipengfei on 2015/6/26. 17 | */ 18 | @Service 19 | public class UserServiceImpl implements UserService { 20 | 21 | @Autowired 22 | private UserDao userDao; 23 | 24 | @Autowired 25 | private UserMapper userMapper; 26 | 27 | @Override 28 | public User getUser(Long id) { 29 | return userDao.getOne(id); 30 | } 31 | 32 | @Override 33 | public Page getAll(Pageable pageable){ 34 | return userDao.findAll(pageable); 35 | } 36 | 37 | @Override 38 | public List getUserList() { 39 | return userMapper.findAll(); 40 | } 41 | 42 | @Override 43 | public Page getUserAll(Pageable pageable) { 44 | return userMapper.getUserAll(pageable); 45 | } 46 | 47 | @Transactional 48 | @Override 49 | public void save() { 50 | 51 | User user = new User(); 52 | user.setUsername("7"); 53 | user.setPassword("7"); 54 | 55 | userDao.save(user); 56 | 57 | // throw new RuntimeException("保存异常!"); 58 | } 59 | 60 | @Transactional 61 | @Override 62 | public void saveUser() { 63 | 64 | User user = new User(); 65 | user.setUsername("8"); 66 | user.setPassword("8"); 67 | 68 | userMapper.save(user); 69 | 70 | throw new RuntimeException("保存异常!"); 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | # Server 5 | server.port=9000 6 | server.sessionTimeout=30 7 | 8 | 9 | 10 | # Specify the DBMS 11 | spring.jpa.database = MYSQL 12 | # Show or not log for each sql query 13 | spring.jpa.show-sql = true 14 | # Hibernate ddl auto (create, create-drop, update) 15 | spring.jpa.hibernate.ddl-auto = create 16 | # Naming strategy 17 | spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy 18 | # stripped before adding them to the entity manager) 19 | spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect 20 | 21 | 22 | 23 | # Mybatis 24 | spring.mybatis.mapperPackage=/mapper/*-mapper.xml 25 | spring.mybatis.dialect=mysql -------------------------------------------------------------------------------- /src/main/resources/datasource.properties: -------------------------------------------------------------------------------- 1 | # Druid 2 | 3 | # Datasource 4 | mysql.driverClassName=com.mysql.jdbc.Driver 5 | mysql.url=jdbc:mysql://192.168.8.91:3306/man_ui_dev?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useOldAliasMetadataBehavior=true 6 | mysql.username=root 7 | mysql.password=123456 8 | mysql.initialSize=1 9 | mysql.minIdle=1 10 | mysql.maxActive=20 -------------------------------------------------------------------------------- /src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | dev 5 | 6 | 7 | 8 | 9 | 10 | ${LOG_HOME}/devLog.%d{yyyy-MM-dd}.log 11 | 30 12 | 13 | 14 | %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{100} - %msg%n 15 | 16 | 17 | 1000MB 18 | 19 | 20 | 21 | 22 | 23 | %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{100} - %msg%n 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /src/main/resources/mapper/user-mapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | id, username, password 13 | 14 | 15 | 20 | 21 | 26 | 27 | 28 | INSERT INTO user (username, password) VALUES (#{username}, #{password}) 29 | 30 | 31 | -------------------------------------------------------------------------------- /src/main/resources/static/img/14ce36d3d539b600354070b7eb50352ac65cb727.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liumangafei/spring-boot-jpa-mybatis-gradle/bd7f1f81222ba347774c36104b4429df67b2d0d2/src/main/resources/static/img/14ce36d3d539b600354070b7eb50352ac65cb727.jpg --------------------------------------------------------------------------------