chenyangsocool
认真学习 认真生活
Intellij Idea下搭建基于Spring+SpringMvc+MyBatis的WebApi接口架构
2018-08-16 09:27 更新
强烈推荐使用Springboot来搭建MVC框架!
强烈推荐使用Springboot来搭建MVC框架!
强烈推荐使用Springboot来搭建MVC框架!
后文仅供学习参考,但是新项目强烈推荐使用Springboot来搭建MVC框架!
2018-03-06 22:42
开发工具:Intellij Idea 2017.3.4(后文统一称为idea)
运行环境:java 9、tomcat 9(经测试在Java7+tomcat7上也可以,其它自行测试)
开发框架:Spring、SpringMvc、Mybatis(后文统一称为SSM)
包管理工具:Maven
最终实现:WebApi接口架构、半自动MyBatis生成工具
本项目的GitHub地址:https://github.com/chenyangsocool/ssm.git
为了让没有接触过idea开发工具的同学也能顺利搭建,本教程尽可能详细。如果有不明白的地方可以在留言处反馈,我会及时更新文档。
一、创建基于Maven的SSM项目
1.打开idea,点击Create New Project,如图1.1:
图1.1
2.点击左侧的Maven,勾上Create from archetype,最后在列表中选上maven-archetype-webapp选项后Next,如图1.2:
(注意别看错,不是cocoon-22-archetype-webapp)
图1.2
3.设置GroupId和ArtifactId,其中GroupId可以认为是你的Java项目包结构,而ArtifactId认为是你的项目名称,如图1.3:
图1.3
4.配置你的Maven目录、Maven配置文件以及jar包存放目录,如图1.4:
(配置Maven过程略)
图1.4
其中,Maven镜像地址推荐使用阿里镜像,setting.xml的<mirrors></mirrors>标签内添加如下内容:
<mirror> <id>alimaven</id> <name>aliyun maven</name> <url>http://maven.aliyun.com/nexus/content/groups/public/</url> <mirrorOf>central</mirrorOf> </mirror>
这样你的jar包下载速度就会炒鸡快~
5.填写项目名称、Module名称。这里我都使用默认。如图1.5:
图1.5
6.idea右下角提示处理:
6.1.Maven的包导入,如图1.6.1:
点击Import Changes。每次你修改了pom.xml后都会弹出该提示。
6.2.Frameworks,点击Configure,如图1.6.2:
会弹出提示:No Frameworks are detected。这里暂时不用理会。
7.项目的pom.xml文件如下:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.chenyangsocool</groupId> <artifactId>ssm</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>ssm Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <!-- spring版本号 --> <spring.version>4.0.2.RELEASE</spring.version> <!-- mybatis版本号 --> <mybatis.version>3.2.6</mybatis.version> <!-- log4j日志文件管理包版本 --> <slf4j.version>1.7.7</slf4j.version> <log4j.version>1.2.16</log4j.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <!-- 表示开发的时候引入,发布的时候不会加载此包 --> <scope>test</scope> </dependency> <!-- spring核心包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!-- mybatis核心包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- mybatis/spring包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <!-- 导入java ee jar 包 --> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> </dependency> <!-- 导入Mysql数据库链接jar包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.30</version> </dependency> <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.2.2</version> </dependency> <!-- JSTL标签类 --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- 日志文件管理包 --> <!-- log start --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <!-- 格式化对象,方便输出日志 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.41</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- log end --> <!-- 映入JSON --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <!-- 上传组件包 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <!-- mybatis-generator --> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.6</version> </dependency> <!-- commons-io --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency> <!-- commons-codec --> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.11</version> </dependency> <!-- commons-lang3 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.7</version> </dependency> </dependencies> <build> <finalName>ssm</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <configuration> <source>1.7</source> <target>1.7</target> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins> </build> </project>
8.进行Spring、SpringMvc和MyBatis的整合:
8.1.先给出我的整合后的项目结构,如图1.8.1:
图1.8.1
8.2.在resouces下新建jdbc.properties数据库连接属性文件:
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf-8 username=root password=root #定义初始连接数 initialSize=0 #定义最大连接数 maxActive=20 #定义最大空闲 maxIdle=20 #定义最小空闲 minIdle=1 #定义最长等待时间 maxWait=60000
8.3.在resouces下新建log4j.properties日志记录文件:
#定义LOG输出级别 log4j.rootLogger=INFO,Console,File #定义日志输出目的地为控制台 log4j.appender.Console=org.apache.log4j.ConsoleAppender log4j.appender.Console.Target=System.out #可以灵活地指定日志输出格式,下面一行是指定具体的格式 log4j.appender.Console.layout = org.apache.log4j.PatternLayout log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n #文件大小到达指定尺寸的时候产生一个新的文件 log4j.appender.File = org.apache.log4j.RollingFileAppender #指定输出目录 log4j.appender.File.File = logs/springmvcMybatis/ssm.log #定义文件最大大小 log4j.appender.File.MaxFileSize = 10MB #输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志 log4j.appender.File.Threshold = ALL log4j.appender.File.layout = org.apache.log4j.PatternLayout log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH:mm:ss}][%c]%m%n
8.5.创建如下文件:
在main目录下创建名为java的package,创建完成后右键该package》Mark Directory as 》Sources Root;
在java目录下创建包com.chenyangsocool.ssm,再接着创建controller、dao、model、service包目录;
在resources下创建mapping文件夹,如图1.8.5:
图1.8.5
8.4.在resouces下新建Spring与Mybatis整合所需的文件,spring-mybatis.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 自动扫描 --> <context:component-scan base-package="com.chenyangsocool.ssm" /> <!-- 引入配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties" /> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="${initialSize}"></property> <!-- 连接池最大数量 --> <property name="maxActive" value="${maxActive}"></property> <!-- 连接池最大空闲 --> <property name="maxIdle" value="${maxIdle}"></property> <!-- 连接池最小空闲 --> <property name="minIdle" value="${minIdle}"></property> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="${maxWait}"></property> </bean> <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描mapping.xml文件 --> <property name="mapperLocations" value="classpath:mapping/*.xml"></property> </bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.chenyangsocool.ssm.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> </beans>
此时,<property name="mapperLocations" value="classpath:mapping/*.xml"></property>中,*.xml是报错的红色状态,别担心,一会在里面放入xml格式的mapping文件后错误就会消失。
8.5.在resouces下新建spring-mvc.xml文件:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!--避免IE执行AJAX时,返回JSON出现下载文件 --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <!-- 启动SpringMVC的注解功能,完成请求和注解model的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON转换器 --> </list> </property> </bean> <!-- 对静态资源的访问 --> <!-- <mvc:resources mapping="/js/**" location="/js/" /> <mvc:resources mapping="/css/**" location="/css/" /> --> <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 --> <context:component-scan base-package="com.chenyangsocool.ssm.controller" /> <!-- 添加注解驱动 --> <mvc:annotation-driven enable-matrix-variables="true" /> <!-- 允许对静态资源文件的访问 --> <mvc:default-servlet-handler /> <!-- 定义跳转的文件的前后缀 ,视图模式配置 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 --> <property name="prefix" value="/WEB-INF/view/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 默认编码 --> <property name="defaultEncoding" value="UTF-8" /> <!-- 文件大小最大值 --> <property name="maxUploadSize" value="10485760000" /> <!-- 内存中的最大值 --> <property name="maxInMemorySize" value="40960" /> </bean> </beans>
8.6.配置web.xml文件:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>Archetype Created Web Application</display-name> <!-- Spring和mybatis的配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mybatis.xml</param-value> </context-param> <!-- 编码过滤器 --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <async-supported>true</async-supported> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- Spring监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 防止Spring内存溢出监听器 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!-- Spring MVC servlet --> <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <!-- 此处可以可以配置成*.do,对应struts的后缀习惯 --> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>/index.html</welcome-file> <welcome-file>/index.jsp</welcome-file> </welcome-file-list> </web-app>
至此,基于SSM的Maven项目搭建完毕~
二、测试SSM框架
先放上该大步骤完成后的结构图,如图2:
图2
1.创建数据库:
DROP TABLE IF EXISTS `test`; CREATE TABLE test ( id INT PRIMARY KEY NOT NULL COMMENT 'id' AUTO_INCREMENT, context NVARCHAR(50) NOT NULL COMMENT '内容', view_count INT DEFAULT 0 NOT NULL COMMENT '浏览次数' ); ALTER TABLE test COMMENT = '测试'; insert into `test`(`context`,`view_count`) values ('测试内容:xfjmjj',10086);
2.在view文件夹下创建test/index.jsp文件,如图2.2:
图2.2
3.test/index.jsp内容:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>index</title> </head> <body> <h2>test's index</h2> <br/> ${test.id}<br/> ${test.context}<br/> ${test.viewCount} </body> </html>
4.添加resources/mapping/TestMapper.xml:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.chenyangsocool.ssm.dao.TestDao" > <resultMap id="BaseResultMap" type="com.chenyangsocool.ssm.model.Test" > <id column="id" property="id" jdbcType="INTEGER" /> <result column="context" property="context" jdbcType="VARCHAR" /> <result column="view_count" property="viewCount" jdbcType="INTEGER" /> </resultMap> <sql id="Base_Column_List" > id, context, view_count </sql> <select id="getModelById" resultMap="BaseResultMap" parameterType="java.lang.Integer" > select <include refid="Base_Column_List" /> from test where id = #{id,jdbcType=INTEGER} </select> </mapper>
5.添加service/ITestService.java:
package com.chenyangsocool.ssm.service; import com.chenyangsocool.ssm.model.Test; public interface ITestService { public Test getModelById(int id); }
6.添加service/impl/TestServiceImpl.java:
package com.chenyangsocool.ssm.service.impl; import com.chenyangsocool.ssm.dao.TestDao; import com.chenyangsocool.ssm.model.Test; import com.chenyangsocool.ssm.service.ITestService; import org.springframework.stereotype.Service; import javax.annotation.Resource; @Service public class TestServiceImpl implements ITestService { @Resource private TestDao testDao; @Override public Test getModelById(int id) { return testDao.getModelById(id); } }
7.添加controller/TestController.java:
package com.chenyangsocool.ssm.controller; import com.chenyangsocool.ssm.model.Test; import com.chenyangsocool.ssm.service.ITestService; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; @Controller @RequestMapping("/test") public class TestController { @Resource private ITestService testService; @RequestMapping("/index_page") public String showIndex(HttpServletRequest request, Model model) { int id = Integer.parseInt(request.getParameter("id")); Test test = this.testService.getModelById(id); //绑定对象到test/index.jsp model.addAttribute("test", test); return "test/index"; } @RequestMapping("/index_api") @ResponseBody public Test Index(HttpServletRequest request,Model model) { int id = Integer.parseInt(request.getParameter("id")); return this.testService.getModelById(id); } }
三、配置Tomcat
(安装Tomcat过程略)
1.工具栏中Run 》Edit Configurations 》左上角+号 》Tomcat Server 》Local,然后点击右下角的Fix按钮,在弹出框中选择ssm:war exploded,如图3.1:
图3.1
2.在弹出的窗口中进行设置,将Name可以设置为testTomcat(不改也行),将Application context手动填入/ssm如图3.2:
3.切换到标签页,按图3.3中设置:
图3.3
至此,基于SSM框架的WebApi接口项目搭建完成,点击idea右上角的绿色三角形▶️运行项目:
输入http://localhost:8080/ssm/test/index_page?id=1,可以看到网页;
输入http://localhost:8080/ssm/test/index_api?id=1,可以看到json接口。
四、集成Mybatis-generator
1.添加测试数据库:
DROP TABLE IF EXISTS `user`; CREATE TABLE user ( id INT PRIMARY KEY NOT NULL COMMENT 'id' AUTO_INCREMENT, context NVARCHAR(50) NOT NULL COMMENT '内容', view_count INT DEFAULT 0 NOT NULL COMMENT '浏览次数' ); ALTER TABLE user COMMENT = '测试'; insert into `user`(`context`,`view_count`) values ('测试内容:xfjmjj',10086);
2.添加com.chenyangsocool.ssm.tools.mybatis/RemarksCommentGenerator.java,该文件自定义了生成的文件的注释,会将数据库中的注释转换成实体类中的注释:
package com.chenyangsocool.ssm.tools.mybatis; import java.util.Date; import org.apache.commons.lang3.time.DateFormatUtils; import org.mybatis.generator.api.IntrospectedColumn; import org.mybatis.generator.api.IntrospectedTable; import org.mybatis.generator.api.dom.java.Field; import org.mybatis.generator.api.dom.java.JavaElement; import org.mybatis.generator.api.dom.java.Method; import org.mybatis.generator.api.dom.java.TopLevelClass; import org.mybatis.generator.config.MergeConstants; import org.mybatis.generator.internal.DefaultCommentGenerator; import org.mybatis.generator.internal.util.StringUtility; /** * 官方类似的功能见,在版本1.3.3中添加的 addRemarkComments <br> * http://www.mybatis.org/generator/configreference/commentGenerator.html <br> * https://github.com/mybatis/generator/issues/23 * * @see DefaultCommentGenerator#addRemarkComments */ public class RemarksCommentGenerator extends DefaultCommentGenerator { @Override public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) { topLevelClass.addJavaDocLine("/**"); String remarks = introspectedTable.getRemarks(); if (StringUtility.stringHasValue(remarks)) { String[] remarkLines = remarks.split(System.getProperty("line.separator")); for (String remarkLine : remarkLines) { topLevelClass.addJavaDocLine(" * " + remarkLine); } } topLevelClass.addJavaDocLine(" * "); StringBuilder sb = new StringBuilder(); sb.append(" * "); sb.append(introspectedTable.getFullyQualifiedTable()); topLevelClass.addJavaDocLine(sb.toString()); topLevelClass.addJavaDocLine(" *"); addJavadocTag(topLevelClass, false); topLevelClass.addJavaDocLine(" */"); } public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) { field.addJavaDocLine("/**"); String remarks = introspectedColumn.getRemarks(); if (StringUtility.stringHasValue(remarks)) { String[] remarkLines = remarks.split(System.getProperty("line.separator")); for (String remarkLine : remarkLines) { field.addJavaDocLine(" * " + remarkLine); } } field.addJavaDocLine(" *"); StringBuilder sb = new StringBuilder(); sb.append(" * "); sb.append(introspectedTable.getFullyQualifiedTable()); sb.append('.'); sb.append(introspectedColumn.getActualColumnName()); field.addJavaDocLine(sb.toString()); field.addJavaDocLine(" *"); addJavadocTag(field, false); field.addJavaDocLine(" */"); } public void addFieldComment(Field field, IntrospectedTable introspectedTable) { field.addJavaDocLine("/**"); addJavadocTag(field, false); field.addJavaDocLine(" */"); } public void addGetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) { method.addJavaDocLine("/**"); addJavadocTag(method, false); method.addJavaDocLine(" */"); } public void addSetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) { method.addJavaDocLine("/**"); addJavadocTag(method, false); method.addJavaDocLine(" */"); } protected void addJavadocTag(JavaElement javaElement, boolean markAsDoNotDelete) { StringBuilder sb = new StringBuilder(); sb.append(" * "); sb.append(MergeConstants.NEW_ELEMENT_TAG); if (markAsDoNotDelete) { sb.append(" do_not_delete_during_merge"); //$NON-NLS-1$ } String s = getDateString(); if (s != null) { sb.append(' '); sb.append(s); } javaElement.addJavaDocLine(sb.toString()); } protected String getDateString() { return DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"); } }
3.添加resources/generatorConfig.xml:
<?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> <context id="context"> <!-- 是否生成注释 --> <commentGenerator type="com.chenyangsocool.ssm.tools.mybatis.RemarksCommentGenerator"> </commentGenerator> <!-- 数据库连接 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://chenyangsocool.tpddns.cn:3306/ssm" userId="young" password="young" /> <!-- 生成的包名和工程名 --> <javaModelGenerator targetPackage="com.chenyangsocool.ssm.model" targetProject="src/main/java"/> <sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources" /> <javaClientGenerator targetPackage="com.chenyangsocool.ssm.dao" targetProject="src/main/java" type="XMLMAPPER" /> <!-- 数据库表 --> <table tableName="user" domainObjectName="User"> <!-- 设置别名 --> <!-- <columnOverride column="login_pwd" property="loginPwd" /> --> </table> </context> </generatorConfiguration>
4.添加com.chenyangsocool.ssm.tools.mybatis/MyBatisGen.java:
package com.chenyangsocool.ssm.tools.mybatis; import java.io.File; import java.util.ArrayList; import java.util.List; import org.mybatis.generator.api.MyBatisGenerator; import org.mybatis.generator.config.Configuration; import org.mybatis.generator.config.xml.ConfigurationParser; import org.mybatis.generator.internal.DefaultShellCallback; /** * 使用Java运行 MyBatis Generator */ public class MyBatisGen { public static void main(String[] args) throws Exception { File file=new File(""); String abspath=file.getAbsolutePath()+"/src/main/resources/generatorConfig.xml"; File configFile = new File(abspath); List<String> warnings = new ArrayList<String>(); boolean overwrite = true; ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = cp.parseConfiguration(configFile); DefaultShellCallback callback = new DefaultShellCallback(overwrite); MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); myBatisGenerator.generate(null); } }
右键main函数,选择“Run MyBatisGen.main()”,即可自动生成相对应的mybatis映射文件(其中实体类拥有中文注释,很nice)
本项目的GitHub地址:https://github.com/chenyangsocool/ssm.git
参考资料: