当前位置:   article > 正文

IDEA基于gradle项目使用mybatis-generator自动生成代码(实例)_idea gradel项目使用mybatis插件

idea gradel项目使用mybatis插件

Mybatis Generator是一个mybatis工具项目,用于生成mybatismodel,mapper,dao持久层代码。MybatisGenerator提供了maven plugin,ant targetjava三种方式启动。现在主流的构建工具是gradle,虽然mybatisgenerator没有提供gradle的插件,但gradle可以调用ant任务,因此,gradle也能启动MybatisGenerator

环境说明

· 数据库:mysql

· 数据库配置文件:src/main/resources/mybatis/db-mysql.properties

· 项目中使用了mybatistk.mybatis:mapper:3.3.2插件


一、数据库准备

  1. /*
  2. Navicat MySQL Data Transfer
  3. Source Server : aaaa
  4. Source Server Version : 50045
  5. Source Host : localhost:3306
  6. Source Database : studentdb
  7. Target Server Type : MYSQL
  8. Target Server Version : 50045
  9. File Encoding : 65001
  10. Date: 2015-09-28 16:57:18
  11. */
  12. SET FOREIGN_KEY_CHECKS=0;
  13. -- ----------------------------
  14. -- Table structure for `admin`
  15. -- ----------------------------
  16. DROP TABLE IF EXISTS `admin`;
  17. CREATE TABLE `admin` (
  18. `Id` int(11) NOT NULL auto_increment,
  19. `username` varchar(20) default NULL,
  20. `password` varchar(20) default NULL,
  21. `name` varchar(20) default NULL,
  22. PRIMARY KEY (`Id`)
  23. ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
  24. -- ----------------------------
  25. -- Records of admin
  26. -- ----------------------------
  27. INSERT INTO `admin` VALUES ('1', 'admin', 'admin', '超级管理员');
  28. -- ----------------------------
  29. -- Table structure for `course`
  30. -- ----------------------------
  31. DROP TABLE IF EXISTS `course`;
  32. CREATE TABLE `course` (
  33. `Id` int(11) NOT NULL,
  34. `name` varchar(20) default NULL,
  35. `teacher_id` int(11) default NULL,
  36. PRIMARY KEY (`Id`),
  37. KEY `teacher_course` (`teacher_id`),
  38. CONSTRAINT `teacher_course` FOREIGN KEY (`teacher_id`) REFERENCES `teacher` (`Id`) ON DELETE CASCADE ON UPDATE CASCADE
  39. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  40. -- ----------------------------
  41. -- Records of course
  42. -- ----------------------------
  43. INSERT INTO `course` VALUES ('1', '面向对象程序设计', '201');
  44. INSERT INTO `course` VALUES ('2', '软件项目管理', '202');
  45. INSERT INTO `course` VALUES ('3', '基于ssh框架项目开发', '203');
  46. -- ----------------------------
  47. -- Table structure for `score`
  48. -- ----------------------------
  49. DROP TABLE IF EXISTS `score`;
  50. CREATE TABLE `score` (
  51. `Id` int(11) NOT NULL auto_increment,
  52. `student_id` int(11) default NULL,
  53. `course_id` int(11) default NULL,
  54. `score` double(6,1) default NULL,
  55. PRIMARY KEY (`Id`),
  56. KEY `stu_score` (`student_id`),
  57. KEY `course_score` (`course_id`),
  58. CONSTRAINT `course_score` FOREIGN KEY (`course_id`) REFERENCES `course` (`Id`) ON DELETE CASCADE ON UPDATE CASCADE,
  59. CONSTRAINT `stu_score` FOREIGN KEY (`student_id`) REFERENCES `student` (`Id`) ON DELETE CASCADE ON UPDATE CASCADE
  60. ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
  61. -- ----------------------------
  62. -- Records of score
  63. -- ----------------------------
  64. INSERT INTO `score` VALUES ('1', '101', '1', '100.0');
  65. INSERT INTO `score` VALUES ('2', '102', '1', '99.0');
  66. INSERT INTO `score` VALUES ('4', '101', '3', '222.0');
  67. -- ----------------------------
  68. -- Table structure for `student`
  69. -- ----------------------------
  70. DROP TABLE IF EXISTS `student`;
  71. CREATE TABLE `student` (
  72. `Id` int(11) NOT NULL,
  73. `name` varchar(20) default NULL,
  74. `password` varchar(20) default NULL,
  75. `sex` int(20) default NULL,
  76. `clazz` varchar(20) default NULL,
  77. `birthday` varchar(20) default NULL,
  78. PRIMARY KEY (`Id`)
  79. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  80. -- ----------------------------
  81. -- Records of student
  82. -- ----------------------------
  83. INSERT INTO `student` VALUES ('101', '林大雷', '1111', '1', '13软件2', '1996-03-24');
  84. INSERT INTO `student` VALUES ('102', '萧炎亮', '0000', '0', '13软件1', '1995-08-01');
  85. INSERT INTO `student` VALUES ('103', '叶凡凯', '0000', '1', '13软件1', '1994-01-23');
  86. INSERT INTO `student` VALUES ('104', '李牧尘', '1111', '0', '13软件1', '1997-12-05');
  87. INSERT INTO `student` VALUES ('105', '刘红枫', '0000', '1', '13软件2', '1995-11-15');
  88. -- ----------------------------
  89. -- Table structure for `teacher`
  90. -- ----------------------------
  91. DROP TABLE IF EXISTS `teacher`;
  92. CREATE TABLE `teacher` (
  93. `Id` int(11) NOT NULL,
  94. `name` varchar(20) default NULL,
  95. `password` varchar(20) default NULL,
  96. `sex` int(11) default NULL,
  97. `birthday` varchar(20) default NULL,
  98. `course_id` int(11) default NULL,
  99. `professional` varchar(20) default NULL,
  100. PRIMARY KEY (`Id`),
  101. KEY `course_teacher` (`course_id`),
  102. CONSTRAINT `course_teacher` FOREIGN KEY (`course_id`) REFERENCES `course` (`Id`) ON DELETE CASCADE ON UPDATE CASCADE
  103. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  104. -- ----------------------------
  105. -- Records of teacher
  106. -- ----------------------------
  107. INSERT INTO `teacher` VALUES ('201', '李青山', '0000', '1', '1965-01-01', '1', '教授');
  108. INSERT INTO `teacher` VALUES ('202', '唐嫣然', '0000', '1', '1968-01-01', '2', '教授');
  109. INSERT INTO `teacher` VALUES ('203', '萧玄茂', '0000', '1', '1978-01-01', '3', '高级教师');


二、db-mysql.properties内容

  1. # JDBC 驱动类名
  2. # JDBC URL: jdbc:mysql:// + 数据库主机地址 + 端口号 + 数据库名
  3. jdbc.url=jdbc:mysql://localhost:3306/test
  4. # JDBC 用户名及密码
  5. jdbc.user=root
  6. jdbc.pass=123
  7. jdbc.driverClassName=com.mysql.jdbc.Driver
  8. # 生成实体类所在的包
  9. package.model=com.ssm.model
  10. # 生成 mapper 类所在的包
  11. package.mapper=com.ssm.dao
  12. # 生成 mapper xml 文件所在的包,默认存储在 resources 目录下
  13. package.xml=mapper

三、generatorConfig.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE generatorConfiguration
  3. PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  4. "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
  5. <generatorConfiguration>
  6. <context id="MysqlContext" targetRuntime="MyBatis3" defaultModelType="flat">
  7. <property name="beginningDelimiter" value="`"/>
  8. <property name="endingDelimiter" value="`"/>
  9. <commentGenerator>
  10. <property name="suppressDate" value="true"/>
  11. </commentGenerator>
  12. <jdbcConnection driverClass="${driverClass}"
  13. connectionURL="${connectionURL}"
  14. userId="${userId}"
  15. password="${password}">
  16. </jdbcConnection>
  17. <javaModelGenerator targetPackage="${modelPackage}" targetProject="${src_main_java}"/>
  18. <sqlMapGenerator targetPackage="${sqlMapperPackage}" targetProject="${src_main_resources}"/>
  19. <javaClientGenerator targetPackage="${mapperPackage}" targetProject="${src_main_java}" type="XMLMAPPER"/>
  20. <!-- sql占位符,表示所有的表 -->
  21. <table tableName="%" enableCountByExample="false" enableUpdateByExample="false"
  22. enableDeleteByExample="false" enableSelectByExample="false"
  23. selectByExampleQueryId="false">
  24. </table>
  25. </context>
  26. </generatorConfiguration>

四、build.gradle的配置

    1.步骤说明
  1. 1、添加
  2. configurations {
  3. mybatisGenerator
  4. }
  5. 2、添加依赖
  6. mybatisGenerator 'org.mybatis.generator:mybatis-generator-core:1.3.2'
  7. mybatisGenerator 'mysql:mysql-connector-java:5.1.38'
  8. mybatisGenerator 'tk.mybatis:mapper:3.3.1'
  9. 3、添加任务
  10. def getDbProperties = {
  11. def properties = new Properties()
  12. file("src/main/resources/mybatis/db-mysql.properties").withInputStream { inputStream ->
  13. properties.load(inputStream)
  14. }
  15. properties;
  16. }
  17. task mybatisGenerate << {
  18. def properties = getDbProperties()
  19. ant.properties['targetProject'] = projectDir.path
  20. ant.properties['driverClass'] = properties.getProperty("jdbc.driverClassName")
  21. ant.properties['connectionURL'] = properties.getProperty("jdbc.url")
  22. ant.properties['userId'] = properties.getProperty("jdbc.user")
  23. ant.properties['password'] = properties.getProperty("jdbc.pass")
  24. ant.properties['src_main_java'] = sourceSets.main.java.srcDirs[0].path
  25. ant.properties['src_main_resources'] = sourceSets.main.resources.srcDirs[0].path
  26. ant.properties['modelPackage'] = properties.getProperty("package.model")
  27. ant.properties['mapperPackage'] = properties.getProperty("package.mapper")
  28. ant.properties['sqlMapperPackage'] =properties.getProperty("package.xml")
  29. ant.taskdef(
  30. name: 'mbgenerator',
  31. classname: 'org.mybatis.generator.ant.GeneratorAntTask',
  32. classpath: configurations.mybatisGenerator.asPath
  33. )
  34. ant.mbgenerator(overwrite: true,
  35. configfile: 'src/main/resources/mybatis/generatorConfig.xml', verbose: true) {
  36. propertyset {
  37. propertyref(name: 'targetProject')
  38. propertyref(name: 'userId')
  39. propertyref(name: 'driverClass')
  40. propertyref(name: 'connectionURL')
  41. propertyref(name: 'password')
  42. propertyref(name: 'src_main_java')
  43. propertyref(name: 'src_main_resources')
  44. propertyref(name: 'modelPackage')
  45. propertyref(name: 'mapperPackage')
  46. propertyref(name: 'sqlMapperPackage')
  47. }
  48. }
  49. }

    2.完整build.gradle配置

  1. group 'person.xjl'
  2. version '1.0-SNAPSHOT'
  3. apply plugin: 'java'
  4. apply plugin: 'war'
  5. sourceCompatibility = 1.8
  6. ext {
  7. spring_version = "4.3.14.RELEASE"
  8. }
  9. repositories {
  10. maven {
  11. url 'http://maven.aliyun.com/nexus/content/groups/public/'
  12. }
  13. mavenCentral()
  14. }
  15. //1、添加
  16. configurations {
  17. mybatisGenerator
  18. }
  19. dependencies {
  20. testCompile group: 'junit', name: 'junit', version: '4.11'
  21. // https://mvnrepository.com/artifact/org.springframework/spring-webmvc
  22. //springmvc + Spring Configuration
  23. compile "org.springframework:spring-web:$spring_version"
  24. compile "org.springframework:spring-webmvc:$spring_version"
  25. compile "org.springframework:spring-aop:$spring_version"
  26. compile "org.springframework:spring-aspects:$spring_version"
  27. compile "org.springframework:spring-beans:$spring_version"
  28. compile "org.springframework:spring-context:$spring_version"
  29. compile "org.springframework:spring-context-support:$spring_version"
  30. compile "org.springframework:spring-core:$spring_version"
  31. compile "org.springframework:spring-expression:$spring_version"
  32. compile "org.springframework:spring-jdbc:$spring_version"
  33. compile "org.springframework:spring-messaging:$spring_version"
  34. compile "org.springframework:spring-orm:$spring_version"
  35. compile "org.springframework:spring-tx:$spring_version"
  36. compile "org.springframework:spring-test:$spring_version"
  37. //MyBatis
  38. compile "org.mybatis:mybatis:3.4.1"
  39. //mybatis spring 插件
  40. compile "org.mybatis:mybatis-spring:1.3.1"// https://mvnrepository.com/artifact/javax.servlet/jstl
  41. compile group: 'javax.servlet', name: 'jstl', version: '1.2'
  42. // https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api
  43. compile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.1.0'
  44. // https://mvnrepository.com/artifact/javax/javaee-api
  45. compile group: 'javax', name: 'javaee-api', version: '7.0'
  46. // https://mvnrepository.com/artifact/mysql/mysql-connector-java
  47. compile group: 'mysql', name: 'mysql-connector-java', version: '5.1.21'
  48. //公共资源包
  49. compile "commons-logging:commons-logging:1.2"
  50. compile "commons-lang:commons-lang:2.6"
  51. compile "org.apache.commons:commons-collections4:4.0"
  52. compile "commons-beanutils:commons-beanutils:1.8.3"
  53. compile "commons-dbcp:commons-dbcp:1.4"
  54. compile "commons-pool:commons-pool:1.6"
  55. compile group: 'log4j', name: 'log4j', version: '1.2.17'
  56. //2、添加依赖
  57. mybatisGenerator 'org.mybatis.generator:mybatis-generator-core:1.3.2'
  58. mybatisGenerator 'mysql:mysql-connector-java:5.1.21'
  59. mybatisGenerator 'tk.mybatis:mapper:3.3.1'
  60. }
  61. //3、添加任务
  62. def getDbProperties = {
  63. def properties = new Properties()
  64. file("src/main/resources/mybatis/db-mysql.properties").withInputStream { inputStream ->
  65. properties.load(inputStream)
  66. }
  67. properties;
  68. }
  69. task mybatisGenerate << {
  70. def properties = getDbProperties()
  71. ant.properties['targetProject'] = projectDir.path
  72. ant.properties['driverClass'] = properties.getProperty("jdbc.driverClassName")
  73. ant.properties['connectionURL'] = properties.getProperty("jdbc.url")
  74. ant.properties['userId'] = properties.getProperty("jdbc.user")
  75. ant.properties['password'] = properties.getProperty("jdbc.pass")
  76. ant.properties['src_main_java'] = sourceSets.main.java.srcDirs[0].path
  77. ant.properties['src_main_resources'] = sourceSets.main.resources.srcDirs[0].path
  78. ant.properties['modelPackage'] = properties.getProperty("package.model")
  79. ant.properties['mapperPackage'] = properties.getProperty("package.mapper")
  80. ant.properties['sqlMapperPackage'] =properties.getProperty("package.xml")
  81. ant.taskdef(
  82. name: 'mbgenerator',
  83. classname: 'org.mybatis.generator.ant.GeneratorAntTask',
  84. classpath: configurations.mybatisGenerator.asPath
  85. )
  86. ant.mbgenerator(overwrite: true,
  87. configfile: 'src/main/resources/mybatis/generatorConfig.xml', verbose: true) {
  88. propertyset {
  89. propertyref(name: 'targetProject')
  90. propertyref(name: 'userId')
  91. propertyref(name: 'driverClass')
  92. propertyref(name: 'connectionURL')
  93. propertyref(name: 'password')
  94. propertyref(name: 'src_main_java')
  95. propertyref(name: 'src_main_resources')
  96. propertyref(name: 'modelPackage')
  97. propertyref(name: 'mapperPackage')
  98. propertyref(name: 'sqlMapperPackage')
  99. }
  100. }
  101. }


 五、运行

在gradle中刷新,点开module下的other,里找到mybatisGenarate,双击



声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/307489
推荐阅读
相关标签
  

闽ICP备14008679号