maven 整合spring+springmvc+mybatis+mysql

maven 环境变量配置

Maven下载

下载地址:http://maven.apache.org/download.cgi

apache-maven路径(版本是会不断更新的)

系统环境变量配置HOME_MAVEN

电脑——>属性——>高级系统设置——>环境变量

1新建环境变量(用户变量)HOME_MAVEN,变量值是apache-maven路径。

2.编辑系统变量里的path,把apache-maven里的bin路径添加到变量值的后面,我的是 ;F:\mvn\apache-maven-3.5.4\bin; 。(注意前后要有;号,也可以是%MAVEN_HOME%\bin,如何用这个报错可以试试前面的绝对路径。 )

 

3.配置本地maven仓库路径

找到文件settings.xml ,    我的在F:\mvn\apache-maven-3.5.4\conf 文件夹下

默认的本地库的路径是C盘的${user}/.m2/repository/

配置自定义仓库地址

<localRepository>F:/repository</localRepository>

maven配置阿里镜像。

 

<mirror>
<id>alimaven</id>
<name>aliyun maven</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<mirrorOf>central</mirrorOf>
</mirror>

 

4.eclipse配置maven。

Windows->preferences,配置maven的installations,点击add,点击directory,installation home是maven安装的路径,installation name自动带出。

配置maven user settins。点击Window的属性。

 

下面这个配置,解决更新项目的时候,报Dmaven.multiModuleProjectDirectory某某set的问题。

default vm处配置改为-Dmaven.multiModuleProjectDirectory=$MAVEN_HOME。(等号前面固定,等号后边是Maven配置的变量名称)。

*新建maven工程。

建好项目后会报红星错误,bulid path jdk版本换成默认的,或者和下面jdk相同版本,然后按照下面的配置,然后clean一下。

点击project里的属性。

上面错误解决方式。

1.web.xml里的

<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">的web-app的版本号改为3.0.

2.找到org.eclipse.wst.common.project.facet.core.xml文件,修改java为1.8,jst.web为3.0.

如果没有显示.settings文件夹。按照下面操作。

1.选中工程,选择Filters

2.取消.resources勾选,点击OK.显示.settings文件夹, .classpath 文件, .project文件, .gitignore文件

 

新建src/main/resources.(注意一定要是新建source Folder类型的

SSM整合。

一先整体看下项目的目录结构

未展开的目录结构。

展开后的目录结构。

 

 

二、maven需要引入的jar包,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.konglx</groupId>
  <artifactId>project_star</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <name>project_star 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.17</log4j.version>
 
  </properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <!-- 导入java ee jar包(可以去除index.jsp报错) -->
    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-api</artifactId>
        <version>7.0</version>
    </dependency>
    <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>
    <!-- 导入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>
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.4</version>
    </dependency>
    <dependency>
        <groupId>commons-codec</groupId>
        <artifactId>commons-codec</artifactId>
        <version>1.9</version>
    </dependency>
    <!-- 自动生成 -->
    <dependency>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-core</artifactId>
        <version>1.3.6</version>
    </dependency>
 
    
  </dependencies>
  <build>
    <finalName>project_star</finalName>
    <plugins>
     <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.5.1</version>
        <configuration>
            <source>1.8</source>
            <target>1.8</target>
            <encoding>UTF-8</encoding>
        </configuration>
     </plugin>
  </plugins>
  </build>
</project>

三、建立JDBC属性配置文件,jdbc.properties

 

#数据库驱动

driver=com.mysql.jdbc.Driver

#数据库连接

url=jdbc:mysql://localhost:3306/konglx?useUnicode=true&characterEncoding=UTF-8

#用户名

username=root

#用户密码

password=root

#定义初始连接数

initialSize=0

#定义最大连接数

maxActive=20

#定义最大空闲

maxIdle=20

#定义最小空闲

minIdle=1

#定义最长等待时间

maxWait=60000

 

四、log4j日志配置文件 , log4j.properties

 

# This is the configuring for logging displayed in the Application Server
log4j.rootCategory=INFO, stdout,common-default,common-warn,common-error


# project loggers
#log4j.logger.com.konglx.dao=INFO,project-dao
log4j.logger.com.konglx.service=INFO,project-service
log4j.logger.com.konglx.controller=INFO,project-web


# common appenders
#stdout configure
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.conversionPattern= %d [%X{loginUserId}/%X{req.remoteAddr}/%X{traceId} - %X{entranceMethod} - %X{req.requestURIWithQueryString}] %-5p %c - %m%n

#common-default file appender
log4j.appender.common-default=org.apache.log4j.DailyRollingFileAppender
log4j.appender.common-default.file=${user.home}/logs/common-default.log
log4j.appender.common-default.layout=org.apache.log4j.PatternLayout
log4j.appender.common-default.layout.conversionPattern= %d [%X{loginUserId}/%X{req.remoteAddr}/%X{traceId} - %X{entranceMethod} - %X{req.requestURIWithQueryString}] %-5p %c - %m%n

#common-warn file appender
log4j.appender.common-warn=org.apache.log4j.DailyRollingFileAppender
log4j.appender.common-warn.file=${user.home}/logs/common-warn.log
log4j.appender.common-warn.layout=org.apache.log4j.PatternLayout
log4j.appender.common-warn.filter.ID=org.apache.log4j.varia.LevelRangeFilter
log4j.appender.common-warn.filter.ID.levelMin=WARN
log4j.appender.common-warn.filter.ID.levelMax=WARN
log4j.appender.common-warn.layout.conversionPattern= %d [%X{loginUserId}/%X{req.remoteAddr}/%X{traceId} - %X{entranceMethod} - %X{req.requestURIWithQueryString}] %-5p %c - %m%n

#common-error file appender
log4j.appender.common-error=org.apache.log4j.DailyRollingFileAppender
log4j.appender.common-error.file=${user.home}/logs/common-error.log
log4j.appender.common-error.layout=org.apache.log4j.PatternLayout
log4j.appender.common-error.threshold=ERROR
log4j.appender.common-error.layout.conversionPattern= %d [%X{loginUserId}/%X{req.remoteAddr}/%X{traceId} - %X{entranceMethod} - %X{req.requestURIWithQueryString}] %-5p %c - %m%n

#common-dao file appender
log4j.appender.common-dao=org.apache.log4j.DailyRollingFileAppender
log4j.appender.common-dao.file=${user.home}/logs/common-dao.log
log4j.appender.common-dao.layout=org.apache.log4j.PatternLayout
log4j.appender.common-dao.layout.conversionPattern= %d [%X{loginUserId}/%X{req.remoteAddr}/%X{traceId} - %X{entranceMethod} - %X{req.requestURIWithQueryString}] %-5p %c - %m%n

#common-web file appender
log4j.appender.common-web=org.apache.log4j.DailyRollingFileAppender
log4j.appender.common-web.file=${user.home}/logs/common-web.log
log4j.appender.common-web.layout=org.apache.log4j.PatternLayout
log4j.appender.common-web.layout.conversionPattern= %d [%X{loginUserId}/%X{req.remoteAddr}/%X{traceId} - %X{entranceMethod} - %X{req.requestURIWithQueryString}] %-5p %c - %m%n

#common-pageNotFound file appender
log4j.appender.common-pageNotFound=org.apache.log4j.DailyRollingFileAppender
log4j.appender.common-pageNotFound.file=${user.home}/logs/common-pageNotFound.log
log4j.appender.common-pageNotFound.layout=org.apache.log4j.PatternLayout
log4j.appender.common-pageNotFound.layout.conversionPattern= %d [%X{loginUserId}/%X{req.remoteAddr}/%X{traceId} - %X{entranceMethod} - %X{req.requestURIWithQueryString}] %-5p %c - %m%n


# project appenders

#project-dao file appender
#log4j.appender.project-dao=org.apache.log4j.DailyRollingFileAppender
#log4j.appender.project-dao.file=${user.home}/logs/project-dao.log
#log4j.appender.project-dao.layout=org.apache.log4j.PatternLayout
#log4j.appender.project-dao.threshold=INFO
#log4j.appender.project-dao.layout.conversionPattern= %d [%X{loginUserId}/%X{req.remoteAddr}/%X{traceId} - %X{entranceMethod} - %X{req.requestURIWithQueryString}] %-5p %c - %m%n

#project-web file appender
log4j.appender.project-web=org.apache.log4j.DailyRollingFileAppender
log4j.appender.project-web.file=${user.home}/logs/project-web.log
log4j.appender.project-web.layout=org.apache.log4j.PatternLayout
log4j.appender.project-web.threshold=INFO
log4j.appender.project-web.layout.conversionPattern= %d [%X{loginUserId}/%X{req.remoteAddr}/%X{traceId} - %X{entranceMethod} - %X{req.requestURIWithQueryString}] %-5p %c - %m%n

#project-service file appender
log4j.appender.project-service=org.apache.log4j.DailyRollingFileAppender
log4j.appender.project-service.file=${user.home}/logs/project-service.log
log4j.appender.project-service.layout=org.apache.log4j.PatternLayout
log4j.appender.project-service.threshold=INFO
log4j.appender.project-service.layout.conversionPattern= %d [%X{loginUserId}/%X{req.remoteAddr}/%X{traceId} - %X{entranceMethod} - %X{req.requestURIWithQueryString}] %-5p %c - %m%n


# open source framework loggers

#spring
log4j.logger.org.springframework=INFO
log4j.logger.org.springframework.jdbc=DEBUG,common-dao

# debug log for ibatis2.3
#log4j.logger.java.sql.Connection=DEBUG,common-dao
#log4j.logger.java.sql.Statement=INFO,common-dao
#log4j.logger.java.sql.PreparedStatement=INFO,common-dao
#log4j.logger.java.sql.ResultSet=INFO,common-dao

# debug log for mybatis
log4j.logger.java.sql.Connection=DEBUG,common-dao
log4j.logger.java.sql.Statement=DEBUG,common-dao
log4j.logger.java.sql.PreparedStatement=DEBUG,common-dao
log4j.logger.java.sql.ResultSet=DEBUG,common-dao
log4j.logger.org.mybatis.spring=DEBUG,common-dao
log4j.logger.com.springframework=DEBUG

 


# hibernate: Changing the log level to DEBUG will display SQL Hibernate generated
#log4j.logger.org.hibernate=INFO,common-dao
#log4j.logger.org.hibernate.SQL=ERROR
#log4j.logger.org.hibernate.cache=ERROR
#log4j.logger.net.sf.ehcache=ERROR

#springmvc pageNotFound
log4j.logger.org.springframework.web.servlet.PageNotFound=INFO,common-pageNotFound

#HibernateValidator
log4j.logger.org.apache.commons.validator.ValidatorResources=INFO

#log4jdbc,
log4j.logger.jdbc.sqlonly=ON
log4j.logger.jdbc.sqltiming=INFO,common-dao
log4j.logger.jdbc.audit=ON
log4j.logger.jdbc.resultset=ON
log4j.logger.jdbc.connection=ON


#====add==
### direct messages to file hibernate.log ###
#log4j.appender.file=org.apache.log4j.FileAppender
#log4j.appender.file.File=hibernate.log
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###

log4j.rootLogger = debug , stdout

#log4j.logger.org.hibernate=info
#log4j.logger.org.hibernate=debug

### log HQL query parser activity
#log4j.logger.org.hibernate.hql.ast.AST=debug

### log just the SQL
#log4j.logger.org.hibernate.SQL=debug

### log JDBC bind parameters ###
#log4j.logger.org.hibernate.type=trace
#log4j.logger.org.hibernate.type=debug

### log schema export/update ###
#log4j.logger.org.hibernate.tool.hbm2ddl=debug

### log HQL parse trees
#log4j.logger.org.hibernate.hql=debug

### log cache activity ###
#log4j.logger.org.hibernate.cache=debug

### log transaction activity
#log4j.logger.org.hibernate.transaction=debug

### log JDBC resource acquisition
#log4j.logger.org.hibernate.jdbc=debug

### enable the following line if you want to track down connection ###
### leakages when using DriverManagerConnectionProvider ###
#log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace

 

五、建立spring-mybatis.xml配置文件

这个文件就是用来完成spring和mybatis的整合的,包含spring和mybatis的配置,包括自动扫描,自动注入,配置数据库;

<?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">
    <!-- 自动扫描 -->
    <context:component-scan base-package="com.konglx" />
 
    <!-- 引入配置文件 -->
    <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:com/konglx/mapper/*.xml"></property>
    </bean>
 
    <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.konglx.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>

六、整合springMVC,spring-mvc.xml

上面已经完成了2大框架的整合,SpringMVC的配置文件单独放,然后在web.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的注解功能,完成请求和注解POJO的映射 -->
    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <!-- JSON转换器 -->
                <ref bean="mappingJacksonHttpMessageConverter" />    
            </list>
        </property>
    </bean>
    <!-- 对静态资源的访问 -->
    <!-- <mvc:resources mapping="/js/**" location="/js/" /> 
        <mvc:resources mapping="/css/**" location="/css/" /> -->
    <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
    <context:component-scan base-package="com.konglx.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/jsp/" />
        <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>

七、配置web.xml

这里面是对spring-mybatis.xml的引入以及配置的spring-mvc的Servlet就是为了完成SSM整合,之前2框架整合不需要在此处进行任何配置。

<?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-*.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>

到目前为止,所有的整合已经完成,配置文件也搞好了,接下来就利用mybatis来自动生成一些java代码:

首先,我们建立数据库:下面是建库建表的语句

CREATE DATABASE `konglx` 

DROP TABLE IF EXISTS `user_t`;
CREATE TABLE `user_t` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(40) NOT NULL,
  `password` varchar(255) NOT NULL,
  `age` int(4) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;


INSERT INTO `user_t` VALUES (1,'project_star-konglx','123',24);

逆向工程的2种方式。

1.利用MyBatis Generator自动创建代码

在f盘上建立一个文件夹(本文用到的文件夹不包含中文字符),然后在里面建个src文件夹,里面的东西如下图:

 

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>
    <!-- 数据库驱动 -->
    <classPathEntry location="mysql-connector-java-5.1.45-bin.jar" />
    <context id="DB2Tables" targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true" />
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true" />
        </commentGenerator>
        <!--数据库链接URL,用户名、密码 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/konglx" userId="root" password="root">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>
        <!-- 生成模型的包名和位置 -->
        <javaModelGenerator targetPackage="com.konglx.bean"
            targetProject="src">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- 生成映射文件的包名和位置 -->
        <sqlMapGenerator targetPackage="com.konglx.mapping"
            targetProject="src">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>
        <!-- 生成DAO的包名和位置 -->
        <javaClientGenerator type="XMLMAPPER"
            targetPackage="com.konglx.dao" targetProject="src">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>
        <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名 -->
        <table tableName="user_t" domainObjectName="User"
            enableCountByExample="false" enableUpdateByExample="false"
            enableDeleteByExample="false" enableSelectByExample="false"
            selectByExampleQueryId="false"></table>
    </context>
</generatorConfiguration>

最后,打开cmd,进入该文件夹(也可以在这个文件夹中按住 shift + 右击,选择"在此处打开命令窗口"),复制粘贴以下代码+回车

Java -jar mybatis-generator-core-1.3.6.jar -configfile generatorConfig.xml -overwrite

完成后,到该文件夹下打开src,如下

2.利用java自动创建代码

利用java生成代码,只要在generatorTemp.java文件运行main方法就可以了。run as ->java applicatoin.F5刷新整个项目,会在下面目录生成目录文件。

 generatorTemp.java文件和generator.xml文件的目录。

generatorTemp.java文件内容。

package generator;

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.exception.XMLParserException;
import org.mybatis.generator.internal.DefaultShellCallback;
import org.springframework.core.io.DefaultResourceLoader;

public class generatorTemp {

    public void generator() throws Exception {

        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        
        
     // 获取文件分隔符
             //String separator = File.separator;
             
             // 获取工程路径
             //File projectPath = new DefaultResourceLoader().getResource("").getFile();
             //while(!new File(projectPath.getPath()+separator+"src"+separator+"main").exists()){
                 //projectPath = projectPath.getParentFile();
             //}
             
             
             // 模板文件路径  F:\workspace\project_star\src\main\java\generator\generator.xml
             //String tplPath = StringUtils.replace(projectPath+"/src/main/java/com/thinkgem/jeesite/generate/template", "/", separator);
        //指定 逆向工程配置文件
        File configFile = new File("./src/main/java/generator/generator.xml");
        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);

    }

    public static void main(String[] args) throws Exception {
        try {
            generatorTemp generatorSqlmap = new generatorTemp();
            generatorSqlmap.generator();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

generator.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="testTables" targetRuntime="MyBatis3">
        <commentGenerator>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true" />
        </commentGenerator>
        <!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/konglx" userId="root"
                        password="root">
        </jdbcConnection>
        <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
            NUMERIC 类型解析为java.math.BigDecimal -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!-- targetProject:生成PO类的位置 -->
        <javaModelGenerator targetPackage="com.konglx.bean"
                            targetProject="./src">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
            <!-- 从数据库返回的值被清理前后的空格 -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- targetProject:mapper映射文件生成的位置 -->
        <sqlMapGenerator targetPackage="com.konglx.mapper"
                         targetProject="./src">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>
        <!-- targetPackage:mapper接口生成的位置 -->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.konglx.mapper"
                             targetProject="./src">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>
        <!-- 指定数据库表 -->
        <table schema="" tableName="user_t"></table>


    </context>
</generatorConfiguration>
 

service接口

package com.konglx.service;

import com.konglx.bean.User;

public interface UserService {
    
     public User getUserById(int userId);
    
}

serviceImpl实现类

package com.konglx.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.konglx.bean.User;
import com.konglx.dao.UserMapper;
import com.konglx.service.UserService;

@Service("userService")
public class UserServiceImpl implements UserService{
    
    @Autowired
    private UserMapper userDao;
    
    @Override
    public User getUserById(int userId) {

        return this.userDao.selectByPrimaryKey(userId);

    }

}

手动创建jsp页面 

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>project_star</title>
</head>
<body>
    <h1>${user.userName}</h1>
</body>
</html>

手动创建controller

package com.konglx.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.konglx.bean.User;
import com.konglx.service.impl.UserServiceImpl;

@Controller
@RequestMapping(value = "/user")
public class UserController {
    
    @Autowired
    private UserServiceImpl userServiceImpl;
    
    @RequestMapping(value = "/test")
    public String Index(HttpServletRequest request, Model model){
        int userId = Integer.parseInt(request.getParameter("id"));
        User user = userServiceImpl.getUserById(userId);
        model.addAttribute("user",user);
         return "User";
    }

}

至此,所有的代码已经完成了

最后,项目右键-maven-update project。然后maven-maven install。然后部署项目到Tomcat。

启动服务,访问url。     http://localhost:8080/project_star/user/test?id=1

启动成功,没有报错如下图。

  

 

作者:
出处:https://www.cnblogs.com/konglxblog//
版权:本文版权归作者和博客园共有
转载:欢迎转载,文章中请给出原文连接,此文章仅为个人知识学习分享,否则必究法律责任

 

posted @ 2019-08-12 19:20  程序员小明1024  阅读(2689)  评论(0编辑  收藏  举报