支持Druid连接池设置、多个mapper.xml目录配置, 解决自定义sql扩展在每次执行插件后被覆盖的问题
1-pom.xml 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 <dependencies > <dependency > <groupId > com.alibaba</groupId > <artifactId > druid</artifactId > <version > 1.0.25</version > </dependency > <dependency > <groupId > org.mybatis.spring.boot</groupId > <artifactId > mybatis-spring-boot-starter</artifactId > <version > 1.1.1</version > </dependency > <dependency > <groupId > com.github.pagehelper</groupId > <artifactId > pagehelper</artifactId > <version > 5.1.4</version > </dependency > </dependencies > <build > <plugins > <plugin > <groupId > org.mybatis.generator</groupId > <artifactId > mybatis-generator-maven-plugin</artifactId > <version > 1.3.7</version > <configuration > <configurationFile > src/main/resources/mybatis-generator-config.xml</configurationFile > <verbose > true</verbose > <overwrite > true</overwrite > </configuration > <executions > <execution > <id > Generate MyBatis Artifacts</id > <goals > <goal > generate</goal > </goals > </execution > </executions > <dependencies > <dependency > <groupId > org.mybatis.generator</groupId > <artifactId > mybatis-generator-core</artifactId > <version > 1.3.7</version > </dependency > </dependencies > </plugin > </plugins > </build >
2-db.properties 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 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://ip:3306/test_db?useUnicode=true &characterEncoding=utf-8 spring.datasource.username=user spring.datasource.password=password spring.datasource.initialSize=5 spring.datasource.minIdle=5 spring.datasource.maxActive=20 spring.datasource.maxWait=60000 spring.datasource.timeBetweenEvictionRunsMillis=60000 spring.datasource.minEvictableIdleTimeMillis=300000 spring.datasource.validationQuery=SELECT 1 FROM DUAL spring.datasource.testWhileIdle=true spring.datasource.testOnBorrow=false spring.datasource.testOnReturn=false spring.datasource.poolPreparedStatements=true spring.datasource.maxPoolPreparedStatementPerConnectionSize=20 spring.datasource.filters=stat ,wall,log4j spring.datasource.connectionProperties=druid.stat.mergeSql=true ;druid.stat.slowSqlMillis=5000 spring.datasource.logSlowSql=true mybatis.model-target-package=model包名 mybatis.dao-target-package=dao包名 mybatis.xml-target-package=mapper mybatis.config-locations=classpath:mybatis-config.xml mybatis.mapper-locations=classpath*:mapper*/*.xml
3-mybatis-config.xml 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 <?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 > <settings > <setting name ="cacheEnabled" value ="false" /> <setting name ="defaultStatementTimeout" value ="5" /> <setting name ="mapUnderscoreToCamelCase" value ="true" /> <setting name ="useGeneratedKeys" value ="true" /> </settings > <typeAliases > <typeAlias alias ="Integer" type ="java.lang.Integer" /> <typeAlias alias ="Long" type ="java.lang.Long" /> <typeAlias alias ="HashMap" type ="java.util.HashMap" /> <typeAlias alias ="LinkedHashMap" type ="java.util.LinkedHashMap" /> <typeAlias alias ="ArrayList" type ="java.util.ArrayList" /> <typeAlias alias ="LinkedList" type ="java.util.LinkedList" /> </typeAliases > </configuration >
4-mybatis-generator-config.xml 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 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" > <generatorConfiguration > <properties resource ="db.properties" /> <classPathEntry location ="/Users/John/.m2/repository/mysql/mysql-connector-java/5.1.43/mysql-connector-java-5.1.43.jar" /> <context id ="Mysql" targetRuntime ="MyBatis3Simple" defaultModelType ="flat" > <property name ="beginningDelimiter" value ="`" /> <property name ="endingDelimiter" value ="`" /> <property name ="mergeable" value ="false" /> <property name ="override" value ="true" /> <plugin type ="org.mybatis.generator.plugins.ToStringPlugin" /> <commentGenerator > <property name ="suppressAllComments" value ="true" /> <property name ="suppressDate" value ="true" /> </commentGenerator > <jdbcConnection driverClass ="${spring.datasource.driver-class-name}" connectionURL ="${spring.datasource.url}" userId ="${spring.datasource.username}" password ="${spring.datasource.password}" /> <javaModelGenerator targetPackage ="${mybatis.model-target-package}" targetProject ="src/main/java" > <property name ="trimStrings" value ="true" /> </javaModelGenerator > <sqlMapGenerator targetPackage ="${mybatis.xml-target-package}" targetProject ="src/main/resources" > </sqlMapGenerator > <javaClientGenerator targetPackage ="${mybatis.dao-target-package}" targetProject ="src/main/java" type ="XMLMAPPER" > </javaClientGenerator > <table tableName ="%" /> </context > </generatorConfiguration >
5-DruidConfig.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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 @Configuration @PropertySource (value = "classpath:db.properties" , ignoreResourceNotFound = true )public class DruidConfig { private Logger logger = LoggerFactory.getLogger(DruidConfig.class); @Value ("${spring.datasource.url}" ) private String dbUrl; @Value ("${spring.datasource.username}" ) private String username; @Value ("${spring.datasource.password}" ) private String password; @Value ("${spring.datasource.driver-class-name}" ) private String driverClassName; @Value ("${spring.datasource.initialSize}" ) private int initialSize; @Value ("${spring.datasource.minIdle}" ) private int minIdle; @Value ("${spring.datasource.maxActive}" ) private int maxActive; @Value ("${spring.datasource.maxWait}" ) private int maxWait; @Value ("${spring.datasource.timeBetweenEvictionRunsMillis}" ) private int timeBetweenEvictionRunsMillis; @Value ("${spring.datasource.minEvictableIdleTimeMillis}" ) private int minEvictableIdleTimeMillis; @Value ("${spring.datasource.validationQuery}" ) private String validationQuery; @Value ("${spring.datasource.testWhileIdle}" ) private boolean testWhileIdle; @Value ("${spring.datasource.testOnBorrow}" ) private boolean testOnBorrow; @Value ("${spring.datasource.testOnReturn}" ) private boolean testOnReturn; @Value ("${spring.datasource.filters}" ) private String filters; @Value ("${spring.datasource.logSlowSql}" ) private String logSlowSql; @Bean public ServletRegistrationBean druidServlet () { ServletRegistrationBean reg = new ServletRegistrationBean(); reg.setServlet(new StatViewServlet()); reg.addUrlMappings("/druid/*" ); reg.addInitParameter("loginUsername" , username); reg.addInitParameter("loginPassword" , password); reg.addInitParameter("logSlowSql" , logSlowSql); return reg; } @Bean public FilterRegistrationBean filterRegistrationBean () { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); filterRegistrationBean.setFilter(new WebStatFilter()); filterRegistrationBean.addUrlPatterns("/*" ); filterRegistrationBean.addInitParameter("exclusions" , "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*" ); filterRegistrationBean.addInitParameter("profileEnable" , "true" ); return filterRegistrationBean; } @Bean public DataSource druidDataSource () { DruidDataSource datasource = new DruidDataSource(); datasource.setUrl(dbUrl); datasource.setUsername(username); datasource.setPassword(password); datasource.setDriverClassName(driverClassName); datasource.setInitialSize(initialSize); datasource.setMinIdle(minIdle); datasource.setMaxActive(maxActive); datasource.setMaxWait(maxWait); datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); datasource.setValidationQuery(validationQuery); datasource.setTestWhileIdle(testWhileIdle); datasource.setTestOnBorrow(testOnBorrow); datasource.setTestOnReturn(testOnReturn); try { datasource.setFilters(filters); } catch (SQLException e) { logger.error("druid configuration initialization filter" , e); } return datasource; } }
6-MyBatisConfig.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 @Configuration @AutoConfigureAfter ({DruidConfig.class})@MapperScan (basePackages = "dao包名" )@EnableTransactionManagement public class MyBatisConfig implements TransactionManagementConfigurer { @Autowired private Environment env; @Autowired DataSource dataSource; @Bean public SqlSessionFactoryBean sqlSessionFactoryBean () throws Exception { SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); factoryBean.setDataSource(dataSource); factoryBean.setTypeAliasesPackage(env.getProperty("mybatis.type-aliases-package" )); String[] locations = env.getProperty("mybatis.mapper-locations" ).split("," ); Resource[] resource = new Resource[0 ]; for (String location : locations){ Resource[] res = new PathMatchingResourcePatternResolver().getResources(location.trim()); resource = Arrays.copyOf(resource, res.length + resource.length); System.arraycopy(res, 0 , resource, resource.length - res.length, res.length); } factoryBean.setMapperLocations(resource); Properties properties = new Properties(); properties.setProperty("reasonable" , "true" ); properties.setProperty("supportMethodsArguments" , "true" ); properties.setProperty("pageSizeZero" , "true" ); PageInterceptor interceptor = new PageInterceptor(); interceptor.setProperties(properties); factoryBean.setPlugins(new Interceptor[]{interceptor}); return factoryBean; } @Bean public SqlSessionTemplate sqlSessionTemplate (SqlSessionFactory sqlSessionFactory) { return new SqlSessionTemplate(sqlSessionFactory); } @Bean @Override public PlatformTransactionManager annotationDrivenTransactionManager () { return new DataSourceTransactionManager(dataSource); } }
7-mybatis-generator插件使用 双击执行插件, 会根据mybatis-generator-config.xml配置生成对应的DAO、Model、Mapper.xml