详解intellij idea搭建SSM框架(spring+maven+mybatis+mysql+junit)(上)

时间:2023-07-26 15:14:26

SSM(Spring+SpringMVC+MyBatis)框架集由Spring、SpringMVC、MyBatis三个开源框架整合而成,常作为数据源较简单的web项目的框架。

其中spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架。 SpringMVC分离了控制器、模型对象、分派器以及处理程序对象的角色,这种分离让它们更容易进行定制。 MyBatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架。

本文旨在快速且详细的介绍intellij idea 搭建SSM框架的过过程,特别适合对SSM框架不是很熟且感兴趣的朋友。

v准备工作

开发环境准备

对于如上这类应用的配置,网上已经有很多现成的方案了,基本操作也比较简单,这里就不再单独介绍了。配置好这些就可以开始搭建框架了。

v创建项目

详解intellij idea搭建SSM框架(spring+maven+mybatis+mysql+junit)(上)

详解intellij idea搭建SSM框架(spring+maven+mybatis+mysql+junit)(上)

点击Next,填写GroupId、ArtifactId(groupId一般是域名的反写,也作为项目中类的包名,artifactId是工程名,也就是根文件夹名)

详解intellij idea搭建SSM框架(spring+maven+mybatis+mysql+junit)(上)

然后next,选择本地maven的位置

详解intellij idea搭建SSM框架(spring+maven+mybatis+mysql+junit)(上)

继续next,选择项目保存的位置

详解intellij idea搭建SSM框架(spring+maven+mybatis+mysql+junit)(上)

点击finish,他会自动生成maven骨架,下载所需要的jar包,第一次创建所需要的时间可能比较长,以后就快了,等待其完成。

创建完后的项目结构如图:

详解intellij idea搭建SSM框架(spring+maven+mybatis+mysql+junit)(上)

项目结构简介:

  • .idea文件夹和helloworld.iml是idea的一些配置文件,我们不用管,就算删了也没事,当然删了,重新打开项目,就得重新配置了
  • src文件夹就是我们放项目代码的地方
  • pom.xml是maven的配置文件,我们需要什么jar包,都可以在里面添加依赖,然后maven就会自己帮我们下到本地仓库里面

接下来就需要创建构思项目所需的文件结构,main下新建一个java,用来放java文件,src下新建一个test,用来放测试文件,main下新建一个resources文件夹,鼠标右键,找到make directory as,选择Resources root 如下图:

详解intellij idea搭建SSM框架(spring+maven+mybatis+mysql+junit)(上)

接下来继续完善项目结构:

  • 在main的java文件夹上,鼠标右键,找到 make directory as,选择Sources root(如上图,下同)
  • 在test的java文件夹上(如没有java文件,则手动创建,下同),鼠标右键,找到make directory as,选择Test Sources root
  • 在test的resources文件夹上,鼠标右键,找到make directory as,选择Test Resources root
  • src->main->java下新建package com,再新建package springmvc,这两个对应我们刚开始的groupid
  • springmvc包下新建四个包,controller包用来放前台url映射文件,dao用来放与数据库的接口文件,entity用来放实体类文件,service用来放自己定义的接口
  • applicationContext.xml是spring配置文件
  • sqlmap文件夹里面放实体与数据库的映射文件
  • generatorConfig.xml和generator.properties是mybatis的配置文件
  • jdbc.properties是数据库相关信息
  • log4j.properties是日志配置文件
  • webapp下新建css、images等文件,用来放前端资源
  • web-inf下新建views文件件,jsp文件就放这里面了

按照上面的流程修改后目录结构如下图:

详解intellij idea搭建SSM框架(spring+maven+mybatis+mysql+junit)(上)

v搭建springmvc

配置Maven pom.xml,引入jar包

pom.xml主要描述了项目的maven坐标,依赖关系,开发者需要遵循的规则,缺陷管理系统,组织和licenses,以及其他所有的项目相关因素,是项目级别的配置文件。
<?xml version="1.0" encoding="UTF-8"?>

<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.springmvc</groupId>
<artifactId>hellobeijing</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging> <name>hellobeijing Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://maven.apache.org</url> <properties>
<!-- spring版本号 -->
<spring.version>4.2.5.RELEASE</spring.version>
<!-- mybatis版本号 -->
<mybatis.version>3.2.4</mybatis.version>
<!-- log4j日志文件管理包版本 -->
<slf4j.version>1.6.6</slf4j.version>
<log4j.version>1.2.12</log4j.version>
</properties>
<dependencies>
<!-- spring核心包 -->
<!-- springframe start -->
<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>
<!-- springframe end --> <!-- 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>
<!-- mysql驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.29</version>
</dependency>
<!-- junit测试包 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2.1-b03</version>
<scope>provided</scope>
</dependency> <!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!-- json数据 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.7.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.7.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.1</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<!-- commons -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.5.6</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.8.3</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
<version>1.0</version>
</dependency> <dependency>
<groupId>net.sf.ezmorph</groupId>
<artifactId>ezmorph</artifactId>
<version>1.0.6</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- 日志文件管理包 -->
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</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>
<!--上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<!-- log end -->
</dependencies>
<build>
<finalName>helloworld</finalName>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<!--允许移动生成的文件-->
<verbose>true</verbose>
<!--允许覆盖生成的文件-->
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>
</build> </project>
如果哪里显示红色报错,请检查settings.xml配置的是否正确,如果没问题,仍然显示红色报错,那就将光标移到那一行,然后键入alt+enter,选择update

我的settings.xml

<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd"> <pluginGroups />
<proxies />
<servers /> <localRepository>D:/server/maven/repository</localRepository> <mirrors>
<mirror>
<id>alimaven</id>
<name>aliyun maven</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<mirrorOf>central</mirrorOf>
</mirror>
</mirrors>
<profiles>
<profile>
<id>nexus</id>
<repositories>
<repository>
<id>nexus</id>
<name>local private nexus</name>
<url>http://maven.oschina.net/content/groups/public/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories> <pluginRepositories>
<pluginRepository>
<id>nexus</id>
<name>local private nexus</name>
<url>http://maven.oschina.net/content/groups/public/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</profile></profiles> </settings>

配置jdbc.properties

driver=com.mysql.jdbc.Driver
#mytest为我本地的数据库名
url=jdbc:mysql://localhost:3306/mytest?useUnicode=true&characterEncoding=utf-8
username=root
#下面输入自己数据库的密码
password=***********
#定义初始连接数
initialSize=0
#定义最大连接数
maxActive=20
#定义最大空闲
maxIdle=20
#定义最小空闲
minIdle=1
#定义最长等待时间
maxWait=60000

配置applicationContext.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:context="http://www.springframework.org/schema/context"
xmlns:beans="http://www.springframework.org/schema/beans"
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.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd" > <!-- ①:对com.springmvc包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 -->
<context:component-scan base-package="com.springmvc"/>
<mvc:annotation-driven />
<!-- 静态资源访问 -->
<!--如果webapp下你新建了文件夹,想访问里面的静态资源,那么就要在这配置一下-->
<mvc:resources location="/images/" mapping="/images/**"/>
<mvc:resources location="/css/" mapping="/css/**"/>
<mvc:resources location="/styles/" mapping="/styles/**"/>
<mvc:resources location="/js/" mapping="/js/**"/> <!-- Configures the @Controller programming model
<mvc:annotation-driven />-->
<!-- ②:启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter"/>
</list>
</property>
</bean> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean> <!-- 配置视图解析器,把控制器的逻辑视频映射为真正的视图 -->
<!-- /WEB-INF/jsp/start.jsp -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean> <!-- 配置dbcp数据库连接池 --> <!-- <context:property-placeholder location="classpath:db.properties"/> -->
<!--数据库配置 -->
<bean id = "propertyConfigurer" class = "org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property> </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="1"/>
<property name="maxActive" value="100"/>
<property name="maxIdle" value="5"/>
<property name="maxWait" value="80000"/>
</bean> <!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean> <!-- 拦截器 -->
<mvc:interceptors>
<!-- 国际化操作拦截器 如果采用基于(请求/Session/Cookie)则必需配置 -->
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
</mvc:interceptors>
<!-- 定义无Controller的path<->view直接映射 -->
<!-- <mvc:view-controller path="/" view-name="redirect:/" /> --> </beans>

配置log4j.properties

Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件,甚至是套接口服务器、NT的事件记录器、UNIX Syslog守护进程等;我们也可以控制每一条日志的输出格式;通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。最令人感兴趣的就是,这些可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。

### set log levels ###
log4j.rootLogger = INFO,D ###输出到控制台###
log4j.logger.toConsole=debug,stdout
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern =%d{yyyy-MM-dd HH\:mm\:ss} [%5p] - %c -%F(%L) -%m%n ### 输出到日志文件 ###
## 其中File 可以采用绝对路径 亦可以采用相对路径 catalina.home 是tomcat目录 如果没有logs文件夹 将会报错 ##
## 更加倾向于将日志文件放在 tomcat的日志目录下${catalina.home}/logs/salesmanb2bError.log ##
## 绝对路径如:e:/salesmanb2bError.log ##
log4j.logger.daily=INFO,D
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = ${catalina.home}/logs/helloworld/helloworld.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = INFO
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern =%d{yyyy-MM-dd HH\:mm\:ss} [%5p] - %c -%F(%L) -%m%n ##log4j.logger.org.apache.ibatis=debug,stdout
##log4j.logger.java.sql=debug,stdout

配置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>helloworld</display-name>
<!-- 配置编码方式-->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <!-- 配置springmvc的前端控制器 指向spring-mvc.xml 程序在启动的时候就加载springmvc 可以接受所有请求 load-on-startup:表示启动容器时初始化该Servlet; -->
<servlet>
<servlet-name>springServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 可以自定义servlet.xml配置文件的位置和名称, 默认为WEB-INF目录下,名称为[<servlet-name>]-servlet.xml,如spring-servlet.xml -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value> classpath:spring/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 将前端URL请求和后台处理方法controller建立对应关系-->
<servlet-mapping>
<servlet-name>springServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> <!-- Spring配置 -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!-- 取消对某一类文件的拦截-->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.md</url-pattern>
</servlet-mapping> <context-param>
<param-name>contextConfigLocation</param-name>
<param-value> classpath:spring/applicationContext.xml</param-value>
</context-param>
<!-- 欢迎页面-->
<welcome-file-list>
<welcome-file>/WEB-INF/index.jsp</welcome-file>
</welcome-file-list>
<!--404错误展示页面,可自行配置-->
<!--<error-page>-->
<!--<error-code>404</error-code>-->
<!--<location>/WEB-INF/views/404.jsp</location>-->
<!--</error-page>-->
<!--设置session失效时间为30分钟 -->
<session-config>
<session-timeout>600</session-timeout>
</session-config>
</web-app>

配置tomcat

到这一步springmvc框架就基本搭好了,我们先运行检验一下,这就需要先配置tomcat

详解intellij idea搭建SSM框架(spring+maven+mybatis+mysql+junit)(上)

详解intellij idea搭建SSM框架(spring+maven+mybatis+mysql+junit)(上)

详解intellij idea搭建SSM框架(spring+maven+mybatis+mysql+junit)(上)

详解intellij idea搭建SSM框架(spring+maven+mybatis+mysql+junit)(上)

这里我们选择war exploded模式,网上关于这两个模式的解释是

war模式—-将WEB工程以包的形式上传到服务器 
war exploded模式—-将WEB工程以当前文件夹的位置关系上传到服务器

详解intellij idea搭建SSM框架(spring+maven+mybatis+mysql+junit)(上)

on frame换成update classes and resources,这样修改了jsp页面不用重启服务器,实现热部署,然后点击OK,效果如下图

详解intellij idea搭建SSM框架(spring+maven+mybatis+mysql+junit)(上)

点击绿色的启动按钮,启动项目。

详解intellij idea搭建SSM框架(spring+maven+mybatis+mysql+junit)(上)

正常启动,这个时候springmvc已经完全配置好了.

vmybatis generato

先在spring文件里面增加SqlSessionFactory配置,将下面这个配置添加到applicationContext.xml文件里面

<!-- 配置会话工厂SqlSessionFactory -->

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据源 -->
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:sqlmap/*Mapper.xml"/>
<property name="typeAliasesPackage" value="com.springmvc.entity" /> </bean> <!-- 在spring容器中配置mapper的扫描器产生的动态代理对象在spring的容器中自动注册,bean的id就是mapper类名(首字母小写)-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 指定扫描包的路径,就是mapper接口的路径,多个包中间以 半角逗号隔开 -->
<property name="basePackage" value="com.springmvc.dao"/>
<!-- 配置sqlSessionFactoryBeanName -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>

还需要配置generatorConfig.xml文件,下面试mybatis-generator的配置文件

<?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="generator.properties"/> <classPathEntry
location="D:\server\maven\repository\mysql\mysql-connector-java\5.1.29\mysql-connector-java-5.1.29.jar" />
<context id="context1">
<!-- 注释 -->
<commentGenerator>
<property name="suppressAllComments" value="true" /><!-- 是否取消注释 -->
<property name="suppressDate" value="true" /> <!-- 是否生成注释代时间戳 -->
</commentGenerator> <jdbcConnection driverClass="${driver}"
connectionURL="${url}"
userId="${username}"
password="${password}" /> <!-- 类型转换 -->
<javaTypeResolver>
<!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
<property name="forceBigDecimals" value="false" />
</javaTypeResolver> <javaModelGenerator targetPackage="${modelPackage}"
targetProject="${modelProject}" />
<sqlMapGenerator targetPackage="${sqlPackage}" targetProject="${sqlProject}" />
<javaClientGenerator targetPackage="${mapperPackage}"
targetProject="${mapperProject}" type="XMLMAPPER" /> <!-- 如果需要通配所有表 直接用sql的通配符 %即可 -->
<table schema="" tableName="${table}" enableCountByExample="false"
enableUpdateByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" selectByExampleQueryId="false"/> </context>
</generatorConfiguration>

请注意的是上面的classPathEntry节点的location属性值是本地的mysql-connector-java.jar的位置,因为连接数据库是需要驱动的,我们用maven已经自动帮我们下好了jar包,在左边的External Libraries里面寻找JAR包的路径。

详解intellij idea搭建SSM框架(spring+maven+mybatis+mysql+junit)(上)

详解intellij idea搭建SSM框架(spring+maven+mybatis+mysql+junit)(上)

按照上面的Ctrl+c and Ctrl+v, 配置好mysql jar包的本地路径.

配置generator.properties

这里面保存的是连接数据库的相关信息,是在使用mybatis-generator这个功能的时候用到的;其实在jdbc.properties是系统运行时用到的。这两个信息差不多,图方便的话,也可以将两个合并成一个文件,分开写的话,好实现可插拔。

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mytest?useUnicode=true&characterEncoding=utf-8
username=root
password=********* #entity 包名和 java目录
modelPackage=com.springmvc.entity
modelProject=src/main/java
#sqlmap包名 和resources目录
sqlPackage=sqlmap
sqlProject=src/main/resources
#mapper包名和 java目录
mapperPackage=com.springmvc.dao
mapperProject=src/main/java table=message

modelPackage是等会连接数据库自动生成的实体类保存的位置,sqlPackage是生成xml映射文件保存的位置,mapperPackage是生成数据库接口保存的位置,table是数据库里面的表的名字

创建数据表

这样,我们需要再mytest数据库里创建一个测试用的表。

use mytest;
CREATE TABLE `message` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`command` varchar(30) NOT NULL,
`description` varchar(30) NOT NULL,
`content` varchar(30) NOT NULL,
PRIMARY KEY (`id`)
)ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; select * from message;

详解intellij idea搭建SSM框架(spring+maven+mybatis+mysql+junit)(上)

mybatis基本配置的差不多了,执行maven的mybatis-generator操作,尽管双击便是。

当日志中提示"BUILD SUCCESS"意为生成mybatis成功,成功以后会对应成圣mapper.xml、dao层和entity层的文件,具体效果见下图:

详解intellij idea搭建SSM框架(spring+maven+mybatis+mysql+junit)(上)

(更新:有朋友私信说右侧没有这些功能栏,可以通过view->tool buttons打开)

详解intellij idea搭建SSM框架(spring+maven+mybatis+mysql+junit)(上)

v配置junit

如果写完一段代码,想去验证他的正确性,并不一定需要去启动tomcat跑跑看或者debug,这时我们就会想到可以使用测试工具来验证,这儿配置junit测试。 那就来测试一下刚生成的message接口有没有用,因为spring的标签,我们先去messagemapper文件加一个@Repository标签,表明它是数据访问组件,即DAO组件

如下图:

详解intellij idea搭建SSM框架(spring+maven+mybatis+mysql+junit)(上)

接下来就可以新建测试文件开始测试,将鼠标移到MessageMapper后(箭头所指方向),然后键盘上按下快捷键alt+enter键,接着create test

如下图:

详解intellij idea搭建SSM框架(spring+maven+mybatis+mysql+junit)(上)

选中需要测试的函数方法,点击OK,

如下图:

详解intellij idea搭建SSM框架(spring+maven+mybatis+mysql+junit)(上)

之后会在test目录下生成MessageMapperTest测试文件,如下图:

详解intellij idea搭建SSM框架(spring+maven+mybatis+mysql+junit)(上)

测试就开始编写MessageMapperTest,编写测试代码。

package com.springmvc.dao;

import com.springmvc.entity.Message;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import static org.junit.Assert.*; /**
* Created by toutou on 2018/5/10.
*/
public class MessageMapperTest { private ApplicationContext applicationContext; @Autowired
private MessageMapper mapper; @Before
public void setUp() throws Exception {
// 加载spring配置文件
applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
// 导入需要测试的
mapper = applicationContext.getBean(MessageMapper.class);
} @After
public void tearDown() throws Exception {
} @Test
public void insert() throws Exception {
Message message = new Message();
message.setCommand("吃饭");
message.setContent("睡觉");
message.setDescription("打豆豆");
int result = mapper.insert(message);
System.out.println(result);
assert (result == 1);
}
}

OK,这样就完成了测试类的编码,接下来运行test,右击这个绿色的小三角,然后运行。

如下图:

详解intellij idea搭建SSM框架(spring+maven+mybatis+mysql+junit)(上)

运行之后效果图:

详解intellij idea搭建SSM框架(spring+maven+mybatis+mysql+junit)(上)

OK,运行之后,返回1,表示运行成功。

那么我们到数据库看看吃饭睡觉打豆豆有没有被插入数据库。

详解intellij idea搭建SSM框架(spring+maven+mybatis+mysql+junit)(上)

OK,大功告成。

v源码地址

https://github.com/toutouge/javademosecond/tree/master/hellobeijing

v博客总结

本篇博文只是介绍一个SSM框架搭建,本来想着一鼓作气把SSM写完的。只是很多细节的东西我还是尽量介绍到位,这就导致这边博文已经很长,加之夜深了,所以还是给标题加了个"上"集,至于引入spring mvc前后台交互的还是留到下集再说吧。

作  者:请叫我头头哥

出  处:http://www.cnblogs.com/toutou/

关于作者:专注于基础平台的项目开发。如有问题或建议,请多多赐教!

版权声明:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。

特此声明:所有评论和私信都会在第一时间回复。也欢迎园子的大大们指正错误,共同进步。或者直接私信

声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是作者坚持原创和持续写作的最大动力!