项目下载地址:链接:https://pan.baidu.com/s/1dlEA0e 密码:0pry
项目最终的结构图:
数据库:
/* Navicat MySQL Data Transfer Source Server : WuGongVmLinux Source Server Version : 50711 Source Host : 192.168.1.148:3306 Source Database : vip Target Server Type : MYSQL Target Server Version : 50711 File Encoding : 65001 Date: 2018-02-26 09:38:45 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for t_phone -- ---------------------------- DROP TABLE IF EXISTS `t_phone`; CREATE TABLE `t_phone` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `user_id` bigint(20) DEFAULT NULL, `add_user_id` bigint(20) DEFAULT NULL, `add_time` datetime DEFAULT NULL, `delete_flag` int(1) DEFAULT '0', `phone` varchar(20) DEFAULT NULL COMMENT '手机号', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of t_phone -- ---------------------------- INSERT INTO `t_phone` VALUES ('1', '1', '1', '2018-02-23 14:49:26', '0', '18353131182'); INSERT INTO `t_phone` VALUES ('2', '1', '1', '2018-02-23 15:27:14', '0', '18765413758'); -- ---------------------------- -- Table structure for t_user -- ---------------------------- DROP TABLE IF EXISTS `t_user`; CREATE TABLE `t_user` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `name` varchar(100) DEFAULT NULL COMMENT '用户名', `nick_name` varchar(100) DEFAULT NULL COMMENT '昵称', `add_time` datetime DEFAULT NULL COMMENT '添加时间', `add_user_id` bigint(20) DEFAULT NULL COMMENT '添加人', `delete_flag` int(1) DEFAULT '0' COMMENT '删除标识', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of t_user -- ---------------------------- INSERT INTO `t_user` VALUES ('1', '吴工', 'wugong', '2018-02-23 14:14:29', '1', '0'); INSERT INTO `t_user` VALUES ('2', '管理员', 'admin', '2018-02-23 14:43:02', '1', '0'); INSERT INTO `t_user` VALUES ('3', '平台账号-000', 'plat', '2018-02-23 16:09:07', null, '1'); INSERT INTO `t_user` VALUES ('4', '平台账号-001', 'plat', '2018-02-23 16:10:57', null, '0'); INSERT INTO `t_user` VALUES ('5', '平台账号', 'plat', '2018-02-23 16:11:33', null, '0'); INSERT INTO `t_user` VALUES ('6', '平台账号', 'plat', '2018-02-23 16:11:50', null, '0'); INSERT INTO `t_user` VALUES ('7', '事务1', 'plat', '2018-02-23 16:49:58', null, '0'); INSERT INTO `t_user` VALUES ('8', '事务2', 'plat', '2018-02-23 16:56:54', null, '0'); INSERT INTO `t_user` VALUES ('11', '事务3', 'plat', '2018-02-23 17:05:59', null, '0'); -- ---------------------------- -- Table structure for users -- ---------------------------- DROP TABLE IF EXISTS `users`; CREATE TABLE `users` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `userName` varchar(200) DEFAULT NULL, `password` varchar(100) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='shiro权限验证演示users表,因为shiro读取的指定表名称、字段名称'; -- ---------------------------- -- Records of users -- ---------------------------- INSERT INTO `users` VALUES ('1', 'wugong', '123456');
1.1、创建project
接着下一步,这里需要注在Properties中添加一个参数 archetypeCatalog=internal,不加这个参数,在maven生成骨架的时候将会非常慢,有时候直接卡住。来自网上的解释:
archetypeCatalog表示插件使用的archetype元数据,不加这个参数时默认为remote,local,即中央仓库archetype元数据,由于中央仓库的archetype太多了所以导致很慢,指定internal来表示仅使用内部元数据。
整个mavn项目就算创建完毕
2、创建两个directoy--->java test
2.1、标记新创建的目录为Sources Tests
设置idea编译jdk环境为1.8或者1.7+
在po.xml中添加ssm依赖
2、通过mybatis genernator逆向生成dao pojo
首先通过mybatis的逆向配置文件
创建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>
<!-- mysql-jdbc驱动地址 -->
<classPathEntry location="D:\my_project\generator-ssm\mysql-connector-java-5.1.45-bin.jar"/>
<context id="context" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressAllComments" value="true"/>
<property name="suppressDate" value="true"/>
</commentGenerator>
<!-- 数据库配置 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://192.168.1.131:3306/vip"
userId="root" password="root"/>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- !!!! Model Configurations !!!! -->
<!-- 模型配置 -->
<javaModelGenerator targetPackage="com.jie.bean" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- !!!! Mapper XML Configurations !!!! -->
<!-- 生成表xml配置 -->
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- !!!! Mapper Interface Configurations !!!! -->
<!-- dao配置 -->
<javaClientGenerator targetPackage="com.jie.dao" targetProject="src/main/java" type="XMLMAPPER">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- !!!! Table Configurations !!!! -->
<!-- 数据表配置 -->
<table tableName="t_phone" domainObjectName="Phone" enableCountByExample="false" enableDeleteByExample="false"
enableSelectByExample="false"
enableUpdateByExample="false">
<!-- 主键自增的设置 -->
<generatedKey column="ID" sqlStatement="MySql" identity="true"/>
</table>
</context>
</generatorConfiguration>
<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>4.12</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 依赖的 插件,如果使用配置方式aop事务处理,则需要依赖当前的jar -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.4</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>druid</artifactId>
<version>1.0.12</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-xml-provider</artifactId>
<version>2.4.1</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.5</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- log end -->
<!-- 上传组件包 -->
<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>
<!-- mybatis分页插件依赖 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.0.0</version>
</dependency>
<!-- mybatis分页插件依赖 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.0.0</version>
</dependency>
<!-- shiro权限控制的依赖 -->
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.2.3</version>
</dependency>
<!-- shiro jdbcRealm 测试使用 -->
<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<finalName>ssm</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>
配置idea创建mavn执行逆向
mybatis-generator:generate -e
保证pom.xml中已经配置
<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>
然后执行逆向
结果:
然后创建web项目的基本文件目录
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>Archetype Created Web Application</display-name>
<context-param> <!--全局范围内环境参数初始化-->
<param-name>contextConfigLocation</param-name> <!--参数名称-->
<param-value>classpath:spring-mybatis.xml</param-value> <!--参数取值-->
</context-param>
<!--以下配置的加载顺序:先 ServletContext >> context-param >> listener >> filter >> servlet >> spring-->
<!-- -过滤器配置 -->
<!--例:编码过滤器-->
<filter> <!-- 用来声明filter的相关设定,过滤器可以截取和修改一个Servlet或JSP页面的请求或从一个Servlet或JSP页面发出的响应-->
<filter-name>encodingFilter</filter-name> <!--指定filter的名字-->
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <!--定义filter的类的名称-->
<async-supported>true</async-supported> <!--设置是否启用异步支持-->
<init-param><!--用来定义参数,若在Servlet可以使用下列方法来获得:String param_name=getServletContext().getInitParamter("param-name里面的值");-->
<param-name>encoding</param-name> <!--参数名称-->
<param-value>UTF-8</param-value> <!--参数值-->
</init-param>
</filter>
<filter-mapping><!--用来定义filter所对应的URL-->
<filter-name>encodingFilter</filter-name> <!--指定对应filter的名字-->
<url-pattern>/*</url-pattern> <!--指定filter所对应的URL-->
</filter-mapping>
<!-- -监听器配置 -->
<!--例:spring监听器-->
<listener> <!--用来设定Listener接口-->
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class><!--定义Listener的类名称-->
</listener>
<!-- 防止Spring内存溢出监听器 -->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<!--servlet配置 -->
<servlet> <!--用来声明一个servlet的数据 -->
<servlet-name>SpringMVC</servlet-name> <!--指定servlet的名称-->
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--指定servlet的类名称,这里配置了前端控制器-->
<init-param><!--用来定义参数,可有多个init-param。在servlet类中通过getInitParamenter(String name)方法访问初始化参数 -->
<param-name>contextConfigLocation</param-name> <!--参数名称-->
<param-value>classpath:spring-mvc.xml</param-value> <!--参数值-->
</init-param>
<load-on-startup>1</load-on-startup><!--当值为正数或零时:Servlet容器先加载数值小的servlet,再依次加载其他数值大的servlet.-->
<async-supported>true</async-supported><!--设置是否启用异步支持-->
</servlet>
<servlet-mapping><!--用来定义servlet所对应的URL-->
<servlet-name>SpringMVC</servlet-name> <!--指定servlet的名称-->
<url-pattern>/</url-pattern> <!--指定servlet所对应的URL-->
</servlet-mapping>
<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>
</web-app>
jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.1.148:3306/vip?characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
jdbc.username=root
jdbc.password=root
#定义初始连接数
initialSize=0
#定义最大连接数
maxActive=20
#定义最大空闲
maxIdle=20
#定义最小空闲
minIdle=1
#定义最长等待时间
maxWait=60000
log4j.properties
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/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
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:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
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/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 启动对@AspectJ注解的支持 自定义注解拦截的controller的配置需要启动当前的配置 -->
<!--<aop:aspectj-autoproxy proxy-target-class="true"/>-->
<!-- aop -->
<!--<bean id="logService" class="com.jie.common.SysLogAspect"></bean>-->
<!-- 1、配置映射器与适配器 -->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
<!--<context:component-scan base-package="com.jie.controller" />-->
<context:component-scan base-package="com.jie.controller" use-default-filters="false" >
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!--避免IE执行AJAX时,返回JSON出现下载文件 -->
<!-- 输出对象转JSON支持 -->
<bean id="stringConverter" class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
</list>
</property>
</bean>
<bean id="jsonConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
<!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="stringConverter"/>
<ref bean="jsonConverter" />
</list>
</property>
</bean>
<!-- 定义跳转的文件的前后缀 ,视图模式配置-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="contentType" value="text/html"/>
<!-- 视图页面的存放目录 -->
<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>
<!-- 配置静态资源,防止被springmvc过滤 -->
<mvc:resources mapping="/js/**" location="/WEB-INF/resource/js/"/>
<mvc:resources mapping="/css/**" location="/WEB-INF/resource/css/"/>
</beans>
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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 自动扫描 -->
<context:component-scan base-package="com.jie.service" />
<!-- 引入配置文件 -->
<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="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.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:mapper/*.xml"></property>
</bean>
<!-- DAO接口所在包名,Spring会自动查找其下的类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.jie.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>
<!-- 使用annotation注解方式配置事务 -->
<!--<tx:annotation-driven transaction-manager="transactionManager"/>-->
<aop:config>
<aop:pointcut id="fooServiceMethods"
expression="execution(* com.jie.service.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="fooServiceMethods"/>
</aop:config>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="select*" read-only="true"/>
<tx:method name="get*" read-only="true"/>
<!--事务的传播属性使用默认值:propagation="REQUIRED"-->
<tx:method name="insert*" propagation="REQUIRED" rollback-for="CustomException"/>
<tx:method name="update*" rollback-for="CustomException"/>
<tx:method name="save*" rollback-for="CustomException"/>
<tx:method name="add*" rollback-for="CustomException"/>
</tx:attributes>
</tx:advice>
</beans>
4、创建controller、service与jsp页面
UserController
package com.jie.controller; import com.jie.service.spi.IUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; /** * \* Created with IntelliJ IDEA. * \* User: wugong.jie * \* Date: 2018/2/26 14:09 * \* To change this template use File | Settings | File Templates. * \* Description: * \ */ @Controller @RequestMapping("manage/user") public class UserController { @Autowired private IUserService userService; @RequestMapping("{id}") public String user(@PathVariable("id")Long id,Model model){ try { model.addAttribute("user",userService.getUser(id)); } catch (Exception e) { e.printStackTrace(); } return "user"; } }
package com.jie.service.spi; import com.jie.bean.User; /** * @author wugong.jie * @date 2018/2/26 */ public interface IUserService { Integer saveUser(User user); Integer updateUser(User user); User getUser(Long id); Integer transferSaveUpdate(Long id); }
package com.jie.service; import com.jie.bean.User; import com.jie.dao.UserMapper; import com.jie.service.spi.IUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Random; /** * \* Created with IntelliJ IDEA. * \* User: wugong.jie * \* Date: 2018/2/26 14:10 * \* To change this template use File | Settings | File Templates. * \* Description: * \ */ @Service public class UserServiceImpl implements IUserService { @Autowired private UserMapper userMapper; @Override @Transactional public Integer saveUser(User user){ userMapper.insert(user); return 1; } @Override public Integer updateUser(User user){ return userMapper.updateByPrimaryKeySelective(user); } @Override public User getUser(Long id){ return userMapper.selectByPrimaryKey(id); } @Override public Integer transferSaveUpdate(Long id){ User oldUser = this.getUser(id); User user = new User(); user.setName("游客"+new Random().nextInt(100)); user.setAddUserId(id); // int i=1/0; this.saveUser(user); oldUser.setName(oldUser.getName()+"-"+user.getName()); this.updateUser(oldUser); return 1; } }
user.jsp
<%@page contentType="text/html;charset=UTF-8" isELIgnored="false" %> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> <%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <html> <head> <title>Title</title> </head> <body> 欢迎你:${user.name} </body> </html>
5、项目发布到tomcat上,
注意如果没有找到当前的tomcat local 可能是你没有绑定tomcat,自己百度一下tomcat idea绑定
编译项目并且启动
事务的测试:
创建测试类:UserTransferTest
com/jie/UserTransferTest.java:27
项目下载地址:链接:https://pan.baidu.com/s/1dlEA0e 密码:0pry