SSH整合
1、导入所需要的pom依赖
1.1 hibernate相关(5.2.12.Final)
hibernate-core
hibernate-c3p0(数据库连接池)
hibernate-ehcache
mysql-connector-java(5.1.44)
1.2 spring相关(5.0.1.RELEASE)
spring-context
spring-orm
spring-web
spring-aspects
注:创建spring的XML文件时,需要添加beans/aop/tx/context标签支持
各依赖说明:
spring-context
创建spring上下文
spring-orm
org.springframework.orm.hibernate5.LocalSessionFactoryBean
dataSource:指定数据源
hibernateProperties:指定hibernate相关属性,如:dialect/show_sql/format_sql
mappingResources:指定实体映射文件
注1:本章采用将hibernate配置全部交给spring管理,因此项目中不再有hibernate.cfg.xml文件
org.springframework.orm.hibernate5.HibernateTemplate
org.springframework.orm.hibernate5.support.HibernateDaoSupport
测试一:运行测试类Test1,测试hibernate与spring的集成
spring-web
org.springframework.web.context.ContextLoaderListener
contextConfigLocation:classpath:applicationContext-*.xml
org.springframework.web.context.support.WebApplicationContextUtils
测试二:访问test2.jsp,测试spring与WEB项目的集成
1.3 struts2相关(2.5.13)
struts2-core
struts2-spring-plugin
struts2与spring集成的插件
将action配置到spring中,struts的action标签的class属性填写spring中bean的名字或id
1.4 log配置
1.4.1 log4j(1.X版)
不建议使用
1.4.2 log4j2(2.9.1)
log4j-core
log4j-api
log4j-web
不建议使用
1.4.3 log4j2 + slf4j(使用ehcache开启hibernate二级缓存必须使用第二种方式配置日志)
注1:本章使用第三种方式配置日志,即log4j2 + slf4j
1.5 other
junit(4.12)
javax.servlet-api(4.0.0)
1.6 jstl
jstl(1.2)
standard(1.1.2)
1.7 jsp自定义标签依赖(必须与tomcat的版本一致)
tomcat-jsp-api
注1:如何解决项目中不支持EL表达式的问题?将web.xml的DTD的版本由2.3升级到3.0即可。因为web2.3是不支持EL表达式的
导入pom.xml依赖(分开导入,不要一次性全导,以免丢失)
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 3 <modelVersion>4.0.0</modelVersion> 4 <groupId>Maven_Spring_SSH</groupId> 5 <artifactId>Spring_SSH</artifactId> 6 <packaging>war</packaging> 7 <version>0.0.1-SNAPSHOT</version> 8 <name>Spring_SSH Maven Webapp</name> 9 <url>http://maven.apache.org</url> 10 <properties> 11 <hibernate.version>5.2.12.Final</hibernate.version> 12 <mysql.version>5.1.44</mysql.version> 13 <spring.version>5.0.1.RELEASE</spring.version> 14 <struts2.version>2.5.13</struts2.version> 15 <slf4j.version>1.7.7</slf4j.version> 16 <log4j2.version>2.9.1</log4j2.version> 17 <disruptor.version>3.2.0</disruptor.version> 18 <junit.version>4.12</junit.version> 19 <javax.servlet.version>4.0.0</javax.servlet.version> 20 <jstl.version>1.2</jstl.version> 21 <standard.version>1.1.2</standard.version> 22 <tomcat-jsp-api.version>8.0.47</tomcat-jsp-api.version> 23 </properties> 24 <dependencies> 25 <!-- 1、导入hibernate依赖 --> 26 <dependency> 27 <groupId>org.hibernate</groupId> 28 <artifactId>hibernate-core</artifactId> 29 <version>${hibernate.version}</version> 30 </dependency> 31 <dependency> 32 <groupId>org.hibernate</groupId> 33 <artifactId>hibernate-c3p0</artifactId> 34 <version>${hibernate.version}</version> 35 </dependency> 36 <dependency> 37 <groupId>org.hibernate</groupId> 38 <artifactId>hibernate-ehcache</artifactId> 39 <version>${hibernate.version}</version> 40 </dependency> 41 <dependency> 42 <groupId>mysql</groupId> 43 <artifactId>mysql-connector-java</artifactId> 44 <version>${mysql.version}</version> 45 </dependency> 46 47 <!-- 2、导入spring依赖 --> 48 <dependency> 49 <groupId>org.springframework</groupId> 50 <artifactId>spring-context</artifactId> 51 <version>${spring.version}</version> 52 </dependency> 53 <dependency> 54 <groupId>org.springframework</groupId> 55 <artifactId>spring-orm</artifactId> 56 <version>${spring.version}</version> 57 </dependency> 58 <dependency> 59 <groupId>org.springframework</groupId> 60 <artifactId>spring-web</artifactId> 61 <version>${spring.version}</version> 62 </dependency> 63 <dependency> 64 <groupId>org.springframework</groupId> 65 <artifactId>spring-aspects</artifactId> 66 <version>${spring.version}</version> 67 </dependency> 68 69 <!-- 3、导入struts2依赖 --> 70 <dependency> 71 <groupId>org.apache.struts</groupId> 72 <artifactId>struts2-core</artifactId> 73 <version>${struts2.version}</version> 74 </dependency> 75 <dependency> 76 <groupId>org.apache.struts</groupId> 77 <artifactId>struts2-spring-plugin</artifactId> 78 <version>${struts2.version}</version> 79 </dependency> 80 81 <!-- 4、导入日志系统依赖 --> 82 <!-- log配置:Log4j2 + Slf4j --> 83 <!-- slf4j核心包 --> 84 <dependency> 85 <groupId>org.slf4j</groupId> 86 <artifactId>slf4j-api</artifactId> 87 <version>${slf4j.version}</version> 88 </dependency> 89 <dependency> 90 <groupId>org.slf4j</groupId> 91 <artifactId>jcl-over-slf4j</artifactId> 92 <version>${slf4j.version}</version> 93 <scope>runtime</scope> 94 </dependency> 95 96 <!--用于与slf4j保持桥接 --> 97 <dependency> 98 <groupId>org.apache.logging.log4j</groupId> 99 <artifactId>log4j-slf4j-impl</artifactId> 100 <version>${log4j2.version}</version> 101 </dependency> 102 103 <!--核心log4j2jar包 --> 104 <dependency> 105 <groupId>org.apache.logging.log4j</groupId> 106 <artifactId>log4j-api</artifactId> 107 <version>${log4j2.version}</version> 108 </dependency> 109 <dependency> 110 <groupId>org.apache.logging.log4j</groupId> 111 <artifactId>log4j-core</artifactId> 112 <version>${log4j2.version}</version> 113 </dependency> 114 115 <!--web工程需要包含log4j-web,非web工程不需要 --> 116 <dependency> 117 <groupId>org.apache.logging.log4j</groupId> 118 <artifactId>log4j-web</artifactId> 119 <version>${log4j2.version}</version> 120 <scope>runtime</scope> 121 </dependency> 122 <!--需要使用log4j2的AsyncLogger需要包含disruptor --> 123 <dependency> 124 <groupId>com.lmax</groupId> 125 <artifactId>disruptor</artifactId> 126 <version>${disruptor.version}</version> 127 </dependency> 128 129 <!-- 5、other --> 130 <!-- 5.1、junit --> 131 <dependency> 132 <groupId>junit</groupId> 133 <artifactId>junit</artifactId> 134 <version>${junit.version}</version> 135 <scope>test</scope> 136 </dependency> 137 138 <!-- 5.2、servlet --> 139 <dependency> 140 <groupId>javax.servlet</groupId> 141 <artifactId>javax.servlet-api</artifactId> 142 <version>${javax.servlet.version}</version> 143 <scope>provided</scope> 144 </dependency> 145 146 <!-- 5.3、jstl、standard --> 147 <dependency> 148 <groupId>jstl</groupId> 149 <artifactId>jstl</artifactId> 150 <version>${jstl.version}</version> 151 </dependency> 152 <dependency> 153 <groupId>taglibs</groupId> 154 <artifactId>standard</artifactId> 155 <version>${standard.version}</version> 156 </dependency> 157 158 <!-- 5.4、tomcat-jsp-api --> 159 <dependency> 160 <groupId>org.apache.tomcat</groupId> 161 <artifactId>tomcat-jsp-api</artifactId> 162 <version>${tomcat-jsp-api.version}</version> 163 </dependency> 164 </dependencies> 165 <build> 166 <finalName>Spring_SSH</finalName> 167 <plugins> 168 <plugin> 169 <groupId>org.apache.maven.plugins</groupId> 170 <artifactId>maven-compiler-plugin</artifactId> 171 <version>3.7.0</version> 172 <configuration> 173 <source>1.8</source> 174 <target>1.8</target> 175 <encoding>UTF-8</encoding> 176 </configuration> 177 </plugin> 178 </plugins> 179 </build> 180 </project>
配置web.xml
1 <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" 2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" 4 version="3.1"> 5 <display-name>Archetype Created Web Application</display-name> 6 7 </web-app>
2. SSH集成
2.1 导入ehcache.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" 4 updateCheck="false"> 5 <!--磁盘存储:将缓存中暂时不使用的对象,转移到硬盘,类似于Windows系统的虚拟内存--> 6 <!--path:指定在硬盘上存储对象的路径--> 7 <!--java.io.tmpdir 是默认的临时文件路径。 可以通过如下方式打印出具体的文件路径 System.out.println(System.getProperty("java.io.tmpdir"));--> 8 <diskStore path="java.io.tmpdir"/> 9 10 11 <!--defaultCache:默认的管理策略--> 12 <!--eternal:设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断--> 13 <!--maxElementsInMemory:在内存中缓存的element的最大数目--> 14 <!--overflowToDisk:如果内存中数据超过内存限制,是否要缓存到磁盘上--> 15 <!--diskPersistent:是否在磁盘上持久化。指重启jvm后,数据是否有效。默认为false--> 16 <!--timeToIdleSeconds:对象空闲时间(单位:秒),指对象在多长时间没有被访问就会失效。只对eternal为false的有效。默认值0,表示一直可以访问--> 17 <!--timeToLiveSeconds:对象存活时间(单位:秒),指对象从创建到失效所需要的时间。只对eternal为false的有效。默认值0,表示一直可以访问--> 18 <!--memoryStoreEvictionPolicy:缓存的3 种清空策略--> 19 <!--FIFO:first in first out (先进先出)--> 20 <!--LFU:Less Frequently Used (最少使用).意思是一直以来最少被使用的。缓存的元素有一个hit 属性,hit 值最小的将会被清出缓存--> 21 <!--LRU:Least Recently Used(最近最少使用). (ehcache 默认值).缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存--> 22 <defaultCache eternal="false" maxElementsInMemory="1000" overflowToDisk="false" diskPersistent="false" 23 timeToIdleSeconds="0" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU"/> 24 25 26 <!--name: Cache的名称,必须是唯一的(ehcache会把这个cache放到HashMap里)--> 27 <cache name="stuCache" eternal="false" maxElementsInMemory="100" 28 overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0" 29 timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU"/> 30 </ehcache>
2.2 导入log4j2.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 3 <!-- status : 指定log4j本身的打印日志的级别.ALL< Trace < DEBUG < INFO < WARN < ERROR 4 < FATAL < OFF。 monitorInterval : 用于指定log4j自动重新配置的监测间隔时间,单位是s,最小是5s. --> 5 <Configuration status="WARN" monitorInterval="30"> 6 <Properties> 7 <!-- 配置日志文件输出目录 ${sys:user.home} --> 8 <Property name="LOG_HOME">/root/workspace/lucenedemo/logs</Property> 9 <property name="ERROR_LOG_FILE_NAME">/root/workspace/lucenedemo/logs/error</property> 10 <property name="WARN_LOG_FILE_NAME">/root/workspace/lucenedemo/logs/warn</property> 11 <property name="PATTERN">%d{yyyy-MM-dd HH:mm:ss.SSS} [%t-%L] %-5level %logger{36} - %msg%n</property> 12 </Properties> 13 14 <Appenders> 15 <!--这个输出控制台的配置 --> 16 <Console name="Console" target="SYSTEM_OUT"> 17 <!-- 控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch) --> 18 <ThresholdFilter level="trace" onMatch="ACCEPT" 19 onMismatch="DENY" /> 20 <!-- 输出日志的格式 --> 21 <!-- %d{yyyy-MM-dd HH:mm:ss, SSS} : 日志生产时间 %p : 日志输出格式 %c : logger的名称 22 %m : 日志内容,即 logger.info("message") %n : 换行符 %C : Java类名 %L : 日志输出所在行数 %M 23 : 日志输出所在方法名 hostName : 本地机器名 hostAddress : 本地ip地址 --> 24 <PatternLayout pattern="${PATTERN}" /> 25 </Console> 26 27 <!--文件会打印出所有信息,这个log每次运行程序会自动清空,由append属性决定,这个也挺有用的,适合临时测试用 --> 28 <!--append为TRUE表示消息增加到指定文件中,false表示消息覆盖指定的文件内容,默认值是true --> 29 <File name="log" fileName="logs/test.log" append="false"> 30 <PatternLayout 31 pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" /> 32 </File> 33 <!-- 这个会打印出所有的info及以下级别的信息,每次大小超过size, 则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档 --> 34 <RollingFile name="RollingFileInfo" fileName="${LOG_HOME}/info.log" 35 filePattern="${LOG_HOME}/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log"> 36 <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch) --> 37 <ThresholdFilter level="info" onMatch="ACCEPT" 38 onMismatch="DENY" /> 39 <PatternLayout 40 pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" /> 41 <Policies> 42 <!-- 基于时间的滚动策略,interval属性用来指定多久滚动一次,默认是1 hour。 modulate=true用来调整时间:比如现在是早上3am,interval是4,那么第一次滚动是在4am,接着是8am,12am...而不是7am. --> 43 <!-- 关键点在于 filePattern后的日期格式,以及TimeBasedTriggeringPolicy的interval, 日期格式精确到哪一位,interval也精确到哪一个单位 --> 44 <!-- log4j2的按天分日志文件 : info-%d{yyyy-MM-dd}-%i.log --> 45 <TimeBasedTriggeringPolicy interval="1" 46 modulate="true" /> 47 <!-- SizeBasedTriggeringPolicy:Policies子节点, 基于指定文件大小的滚动策略,size属性用来定义每个日志文件的大小. --> 48 <!-- <SizeBasedTriggeringPolicy size="2 kB" /> --> 49 </Policies> 50 </RollingFile> 51 52 <RollingFile name="RollingFileWarn" fileName="${WARN_LOG_FILE_NAME}/warn.log" 53 filePattern="${WARN_LOG_FILE_NAME}/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log"> 54 <ThresholdFilter level="warn" onMatch="ACCEPT" 55 onMismatch="DENY" /> 56 <PatternLayout 57 pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" /> 58 <Policies> 59 <TimeBasedTriggeringPolicy /> 60 <SizeBasedTriggeringPolicy size="2 kB" /> 61 </Policies> 62 <!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件,这里设置了20 --> 63 <DefaultRolloverStrategy max="20" /> 64 </RollingFile> 65 66 <RollingFile name="RollingFileError" fileName="${ERROR_LOG_FILE_NAME}/error.log" 67 filePattern="${ERROR_LOG_FILE_NAME}/$${date:yyyy-MM}/error-%d{yyyy-MM-dd-HH-mm}-%i.log"> 68 <ThresholdFilter level="error" onMatch="ACCEPT" 69 onMismatch="DENY" /> 70 <PatternLayout 71 pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" /> 72 <Policies> 73 <!-- log4j2的按分钟 分日志文件 : warn-%d{yyyy-MM-dd-HH-mm}-%i.log --> 74 <TimeBasedTriggeringPolicy interval="1" 75 modulate="true" /> 76 <!-- <SizeBasedTriggeringPolicy size="10 MB" /> --> 77 </Policies> 78 </RollingFile> 79 80 </Appenders> 81 82 <!--然后定义logger,只有定义了logger并引入的appender,appender才会生效 --> 83 <Loggers> 84 <!--过滤掉spring和mybatis的一些无用的DEBUG信息 --> 85 <logger name="org.springframework" level="INFO"></logger> 86 <logger name="org.mybatis" level="INFO"></logger> 87 88 <!-- 第三方日志系统 --> 89 <logger name="org.springframework" level="ERROR" /> 90 <logger name="org.hibernate" level="ERROR" /> 91 <logger name="org.apache.struts2" level="ERROR" /> 92 <logger name="com.opensymphony.xwork2" level="ERROR" /> 93 <logger name="org.jboss" level="ERROR" /> 94 95 96 <!-- 配置日志的根节点 --> 97 <root level="all"> 98 <appender-ref ref="Console" /> 99 <appender-ref ref="RollingFileInfo" /> 100 <appender-ref ref="RollingFileWarn" /> 101 <appender-ref ref="RollingFileError" /> 102 </root> 103 104 </Loggers> 105 106 </Configuration>
2.3 集成hibernate
2.3.2 配置c3p0连接池
2.3.3 注册LocalSessionFactoryBean
2.3.4 spring声明式事物
声明式事务配置
必须先修改spring配置文件的声明部分,添加对aop标签和tx标签的支持
配置SessionFactory(spring和hibernate集成时已完成)
配置事务管理器
HibernateTransactionManager
配置事务的传播特性(tx)
add
edit
del
load|list
事务传播特性(PROPAGATION_REQUIRED|readOnly)
配置自动代理
引用环绕通知txAdvice
定义一个切入点
execution(* *..*Biz.*(..))
a:返回值不限 b:包名不限 c:接口名以Biz结尾 d:方法名及参数不限
c) 自动代理的原理
在spring上下文初始化完成以后,自动代理会逐个检查spring上下文中JavaBean实现的接口是否满足自动代理的条件,如果满足条件,则将此bean和通知结合生成一个代理对象,并以此代理对象替换spring上下文中的bean,之后你访问的就是代理对象了
2.3.5 注册HibernateTemplate
2.3.6 注册Base模块
spring-hibernate.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" 4 xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 6 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd 7 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd 8 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"> 9 <!-- 10 1 注册数据库连接信息文件 11 2 配置连接池 12 3 配置sessionFactory 13 4 配置事物 14 5 配置切面 15 6 配置通用模板 16 17 --> 18 19 <!-- 1、注册jdbc相关的配置文件 --> 20 <context:property-placeholder location="classpath:db.properties" /> 21 22 <!-- 配置c3p0连接池 --> 23 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> 24 <property name="user" value="${db.username}"></property> 25 <property name="password" value="${db.password}"></property> 26 <property name="driverClass" value="${db.driverClass}"></property> 27 <property name="jdbcUrl" value="${db.jdbcUrl}"></property> 28 29 <!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 --> 30 <property name="initialPoolSize" value="${db.initialPoolSize}"></property> 31 <!--连接池中保留的最大连接数。Default: 15 --> 32 <property name="maxPoolSize" value="${db.maxPoolSize}"></property> 33 <!--连接池中保留的最小连接数。 --> 34 <property name="minPoolSize" value="${db.minPoolSize}" /> 35 <!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 --> 36 <property name="maxIdleTime" value="${db.maxIdleTime}" /> 37 38 <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 --> 39 <property name="acquireIncrement" value="${db.acquireIncrement}" /> 40 41 <!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements 属于单个connection而不是整个连接池。 42 所以设置这个参数需要考虑到多方面的因素。如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 43 0 --> 44 <property name="maxStatements" value="${db.maxStatements}" /> 45 46 <!--每60秒检查所有连接池中的空闲连接。Default: 0 --> 47 <property name="idleConnectionTestPeriod" value="${db.idleConnectionTestPeriod}" /> 48 49 <!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 --> 50 <property name="acquireRetryAttempts" value="${db.acquireRetryAttempts}" /> 51 52 <!--获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效 保留,并在下次调用getConnection()的时候继续尝试获取连接。 53 如果设为true,那么在尝试 获取连接失败后该数据源将申明已断开并永久关闭。Default: false --> 54 <property name="breakAfterAcquireFailure" value="${db.breakAfterAcquireFailure}" /> 55 56 <!--因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的 时候都将校验其有效性。建议使用idleConnectionTestPeriod 57 或automaticTestTable 等方法来提升连接测试的性能。Default: false --> 58 <property name="testConnectionOnCheckout" value="${db.breakAfterAcquireFailure}" /> 59 </bean> 60 61 <!-- 3、配置sessionfactory相关信息 --> 62 <bean id="sessionFactory" 63 class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> 64 <!-- 数据源 --> 65 <property name="dataSource"> 66 <ref bean="dataSource" /> 67 </property> 68 <!-- hibernate相关属性 --> 69 <property name="hibernateProperties"> 70 <props> 71 <prop key="dialect">org.hibernate.dialect.MySQLDialect</prop> 72 <!--spring与Hibernate集成无法显示sql语句问题,请见集成后hibernate无法显示sql语句.txt --> 73 <prop key="hibernate.show_sql">true</prop> 74 <prop key="hibernate.format_sql">true</prop> 75 </props> 76 </property> 77 <!-- 实体映射文件 --> 78 <property name="mappingResources"> 79 <list> 80 81 <value>com/spring/ssh/book/entity/book.hbm.xml</value> 82 </list> 83 </property> 84 </bean> 85 86 <!-- 4、配置事务 --> 87 <!--声明式事务配置开始 --> 88 <!-- 89 静态代理: 90 一个代理对象->一个目标对象 91 BookProxy(BookBizImpl+myMethodBeforeAdvice)->bookBiz 92 OrderProxy(OrderBizImpl+myMethodBeforeAdvice2)-> OrderBiz 93 94 动态代理: 95 一个代理对象->多个目标对象 96 --> 97 98 <!--1) 开启自动代理 --> 99 <aop:aspectj-autoproxy /> 100 101 <!--2) 事务管理器 --> 102 <bean id="transactionManager" 103 class="org.springframework.orm.hibernate5.HibernateTransactionManager"> 104 <property name="sessionFactory" ref="sessionFactory" /> 105 </bean> 106 107 <!--3) 定义事务特性 --> 108 <tx:advice id="txAdvice" transaction-manager="transactionManager"> 109 <tx:attributes> 110 <tx:method name="add*" propagation="REQUIRED" /> 111 <tx:method name="save*" propagation="REQUIRED" /> 112 <tx:method name="insert*" propagation="REQUIRED" /> 113 114 <tx:method name="edit*" propagation="REQUIRED" /> 115 <tx:method name="update*" propagation="REQUIRED" /> 116 117 <tx:method name="del*" propagation="REQUIRED" /> 118 <tx:method name="remove*" propagation="REQUIRED" /> 119 120 <tx:method name="load*" propagation="REQUIRED" read-only="true" /> 121 <tx:method name="list*" propagation="REQUIRED" read-only="true" /> 122 <tx:method name="select*" propagation="REQUIRED" read-only="true" /> 123 <tx:method name="query*" propagation="REQUIRED" read-only="true" /> 124 125 <tx:method name="do*" propagation="REQUIRED" /> 126 </tx:attributes> 127 </tx:advice> 128 129 <!--4) 定义切入点 --> 130 <aop:config> 131 <!-- pointcut属性用来定义一个切入点,分成四个部分理解 [* ][*..][*Biz][.*(..)] --> 132 <!-- A: 返回类型,*表示返回类型不限 --> 133 <!-- B: 包名,*..表示包名不限 --> 134 <!-- C: 类或接口名,*Biz表示类或接口必须以Biz结尾 --> 135 <!-- D: 方法名和参数,*(..)表示方法名不限,参数类型和个数不限 --> 136 <aop:advisor advice-ref="txAdvice" pointcut="execution(* *..*Biz.*(..))" /> 137 </aop:config> 138 <!-- 声明式事务配置结束 --> 139 140 <!-- 5、配置HibernateTemplate 可以看出session--> 141 <bean class="org.springframework.orm.hibernate5.HibernateTemplate" id="hibernateTemplate"> 142 <property name="sessionFactory" ref="sessionFactory"></property> 143 </bean> 144 <!-- 6、分模块开发(只配置base模块) --> 145 <bean class="com.spring.ssh.base.entity.BaseEntity" abstract="true" id="baseEntity"></bean> 146 <bean class="com.spring.ssh.base.dao.BaseDao" abstract="true" id="baseDao" > 147 <property name="hibernateTemplate" ref="hibernateTemplate"></property> 148 </bean> 149 <bean class="com.spring.ssh.base.biz.BaseBiz" abstract="true" id="baseBiz"></bean> 150 <bean class="com.spring.ssh.base.web.BaseAction" abstract="true" id="baseAction"></bean> 151 </beans>
3. 程序代码的分层
base层
util工具层
PageBean
1 package com.spring.ssh.base.util; 2 3 import java.util.Map; 4 5 import javax.servlet.http.HttpServletRequest; 6 7 /** 8 * 分页工具类 9 * 10 */ 11 public class PageBean { 12 13 private int page = 1;// 页码 14 15 private int rows = 3;// 页大小 16 17 private int total = 0;// 总记录数 18 19 private boolean pagination = true;// 是否分页 20 // 获取前台向后台提交的所有参数 21 private Map<String, String[]> parameterMap; 22 // 获取上一次访问后台的url 23 private String url; 24 25 /** 26 * 初始化pagebean 27 * 28 * @param req 29 */ 30 public void setRequest(HttpServletRequest req) { 31 this.setPage(req.getParameter("page")); 32 this.setRows(req.getParameter("rows")); 33 // 只有jsp页面上填写pagination=false才是不分页 34 this.setPagination(!"fasle".equals(req.getParameter("pagination"))); 35 this.setParameterMap(req.getParameterMap()); 36 this.setUrl(req.getRequestURL().toString()); 37 } 38 39 public int getMaxPage() { 40 return this.total % this.rows == 0 ? this.total / this.rows : this.total / this.rows + 1; 41 } 42 43 public int nextPage() { 44 return this.page < this.getMaxPage() ? this.page + 1 : this.getMaxPage(); 45 } 46 47 public int previousPage() { 48 return this.page > 1 ? this.page - 1 : 1; 49 } 50 51 public PageBean() { 52 super(); 53 } 54 55 public int getPage() { 56 return page; 57 } 58 59 public void setPage(int page) { 60 this.page = page; 61 } 62 63 public void setPage(String page) { 64 this.page = StringUtils.isBlank(page) ? this.page : Integer.valueOf(page); 65 } 66 67 public int getRows() { 68 return rows; 69 } 70 71 public void setRows(int rows) { 72 this.rows = rows; 73 } 74 75 public void setRows(String rows) { 76 this.rows = StringUtils.isBlank(rows) ? this.rows : Integer.valueOf(rows); 77 } 78 79 public int getTotal() { 80 return total; 81 } 82 83 public void setTotal(int total) { 84 this.total = total; 85 } 86 87 public void setTotal(String total) { 88 this.total = Integer.parseInt(total); 89 } 90 91 public boolean isPagination() { 92 return pagination; 93 } 94 95 public void setPagination(boolean pagination) { 96 this.pagination = pagination; 97 } 98 99 public Map<String, String[]> getParameterMap() { 100 return parameterMap; 101 } 102 103 public void setParameterMap(Map<String, String[]> parameterMap) { 104 this.parameterMap = parameterMap; 105 } 106 107 public String getUrl() { 108 return url; 109 } 110 111 public void setUrl(String url) { 112 this.url = url; 113 } 114 115 /** 116 * 获得起始记录的下标 117 * 118 * @return 119 */ 120 public int getStartIndex() { 121 return (this.page - 1) * this.rows; 122 } 123 124 @Override 125 public String toString() { 126 return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination 127 + ", parameterMap=" + parameterMap + ", url=" + url + "]"; 128 } 129 130 }
StringUtils
1 package com.spring.ssh.base.util; 2 3 public class StringUtils { 4 // 私有的构造方法,保护此类不能在外部实例化 5 private StringUtils() { 6 } 7 8 /** 9 * 如果字符串等于null或去空格后等于"",则返回true,否则返回false 10 * 11 * @param s 12 * @return 13 */ 14 public static boolean isBlank(String s) { 15 boolean b = false; 16 if (null == s || s.trim().equals("")) { 17 b = true; 18 } 19 return b; 20 } 21 22 /** 23 * 如果字符串不等于null或去空格后不等于"",则返回true,否则返回false 24 * 25 * @param s 26 * @return 27 */ 28 public static boolean isNotBlank(String s) { 29 return !isBlank(s); 30 } 31 32 }
eneity
BaseEntity
1 package com.spring.ssh.base.entity; 2 3 import java.io.Serializable; 4 /** 5 * 存放所以实体类的共性属性 6 * jsp传递到后台的参数 7 * 非数据与表的映射关系字段属性 8 * @author Administrator 9 * 10 */ 11 public class BaseEntity implements Serializable{ 12 13 }
Dao层
BaseDao
1 package com.spring.ssh.base.dao; 2 3 import java.io.Serializable; 4 import java.util.Collection; 5 import java.util.List; 6 import java.util.Map; 7 8 import org.hibernate.Session; 9 import org.hibernate.query.Query; 10 import org.springframework.orm.hibernate5.support.HibernateDaoSupport; 11 12 import com.spring.ssh.base.util.PageBean; 13 14 public class BaseDao extends HibernateDaoSupport implements Serializable{ 15 16 public void setParam(Query query,Map<String, Object> map) { 17 if(map == null || map.size() < 1) { 18 return; 19 } 20 Object value = null; 21 for(Map.Entry<String, Object> entry:map.entrySet()) { 22 value = entry.getValue(); 23 if(value instanceof Collection) { 24 query.setParameterList(entry.getKey(), (Collection) value); 25 }else if(value instanceof Object[]) { 26 query.setParameterList(entry.getKey(), (Object[]) value); 27 }else { 28 query.setParameter(entry.getKey(), value); 29 } 30 } 31 } 32 33 public String getCountHql(String hql) { 34 int index = hql.toUpperCase().indexOf("FROM"); 35 return "select count(*) "+hql.substring(index); 36 } 37 38 /** 39 * 40 * @param hql 已经拼装好的 41 * @param map 42 * @param pageBean 43 * @return 44 */ 45 public List executeQuery(Session session, String hql,Map<String, Object> map,PageBean pageBean) { 46 if(pageBean !=null && pageBean.isPagination()) { 47 String countHql = getCountHql(hql); 48 Query countQuery = session.createQuery(countHql); 49 this.setParam(countQuery, map); 50 pageBean.setTotal(countQuery.getSingleResult().toString()); 51 52 Query query = session.createQuery(hql); 53 this.setParam(query, map); 54 query.setFirstResult(pageBean.getStartIndex()); 55 query.setMaxResults(pageBean.getRows()); 56 List list = query.list(); 57 58 return list; 59 }else { 60 Query query = session.createQuery(hql); 61 this.setParam(query, map); 62 List list = query.list(); 63 64 return list; 65 } 66 } 67 }
Biz
BaseBiz
1 package com.spring.ssh.base.biz; 2 3 public interface BaseBiz { 4 5 }
web层
BaseAction
1 package com.spring.ssh.base.web; 2 3 import java.io.Serializable; 4 5 import javax.servlet.ServletContext; 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 import javax.servlet.http.HttpSession; 9 10 import org.apache.struts2.interceptor.ServletRequestAware; 11 import org.apache.struts2.interceptor.ServletResponseAware; 12 13 public class BaseAction implements ServletRequestAware, ServletResponseAware,Serializable{ 14 private static final long serialVersionUID = -7110462505161900879L; 15 /** 16 * 为了传值使用 17 */ 18 protected HttpServletResponse response; 19 protected HttpServletRequest request; 20 protected HttpSession session; 21 protected ServletContext application; 22 23 /** 24 * 为了配置跳转页面所用 25 */ 26 protected final static String SUCCESS = "success"; 27 protected final static String FAIL = "fail"; 28 protected final static String LIST = "list"; 29 protected final static String ADD = "add"; 30 protected final static String EDIT = "edit"; 31 protected final static String DETAIL = "detail"; 32 33 /** 34 * 具体传值字段 后端向jsp页面传值所用字段 35 */ 36 protected Object result; 37 protected Object msg; 38 protected int code; 39 40 public Object getResult() { 41 return result; 42 } 43 44 public Object getMsg() { 45 return msg; 46 } 47 48 public int getCode() { 49 return code; 50 } 51 52 @Override 53 public void setServletResponse(HttpServletResponse arg0) { 54 this.response = arg0; 55 56 } 57 58 @Override 59 public void setServletRequest(HttpServletRequest arg0) { 60 this.request = arg0; 61 this.session = arg0.getSession(); 62 this.application = arg0.getServletContext(); 63 } 64 65 }
Book层
entity
Book
1 package com.spring.ssh.book.entity; 2 3 import java.io.Serializable; 4 import java.util.HashSet; 5 import java.util.Locale.Category; 6 import java.util.Set; 7 8 public class Book implements Serializable{ 9 // book_id int primary key auto_increment, 10 // book_name varchar(50) not null, 11 // price float not null 12 private Integer bookId; 13 private String bookName; 14 private Float price; 15 16 private Set<Category> categories = new HashSet<Category>(); 17 private Integer initCategories = 0; 18 19 public Integer getInitCategories() { 20 return initCategories; 21 } 22 23 public void setInitCategories(Integer initCategories) { 24 this.initCategories = initCategories; 25 } 26 27 public Integer getBookId() { 28 return bookId; 29 } 30 31 public void setBookId(Integer bookId) { 32 this.bookId = bookId; 33 } 34 35 public String getBookName() { 36 return bookName; 37 } 38 39 public void setBookName(String bookName) { 40 this.bookName = bookName; 41 } 42 43 public Float getPrice() { 44 return price; 45 } 46 47 public void setPrice(Float price) { 48 this.price = price; 49 } 50 51 public Set<Category> getCategories() { 52 return categories; 53 } 54 55 public void setCategories(Set<Category> categories) { 56 this.categories = categories; 57 } 58 59 @Override 60 public String toString() { 61 return "Book [bookId=" + bookId + ", bookName=" + bookName + ", price=" + price + "]"; 62 } 63 64 public Book(Integer bookId, String bookName) { 65 super(); 66 this.bookId = bookId; 67 this.bookName = bookName; 68 } 69 70 public Book() { 71 super(); 72 } 73 74 75 }
book.hbm.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-mapping PUBLIC 3 "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 4 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 5 <hibernate-mapping> 6 <class name="com.spring.ssh.book.entity.Book" table="t_hibernate_book"> 7 <id name="bookId" type="java.lang.Integer" column="book_id"> 8 <generator class="increment" /> 9 </id> 10 <property name="bookName" type="java.lang.String" 11 column="book_name"> 12 </property> 13 <property name="price" type="java.lang.Float" 14 column="price"> 15 </property> 16 17 <!-- 18 set标签 19 table:对应的是中间表,没有实体类的,意味着靠两张主表对应的映射文件联合管理数据 20 name:当前映射文件对应的实体类对应的属性 21 cascade:级联新增修改,说白了就是当前实体类对应的表删除能否影响到关联表的数据 22 inberse:中间表的数据维护的权利交给对方 23 key标签 24 column:当前表t_hibernate_book_category的主键book_id在中间表的列段bid 25 many-to-many: 26 column:代表中间表对应的除去当前表t_hibernate_book的非主键的中间列段cid 27 class:cid对应的类 28 29 <set table="t_hibernate_book_category" name="categories" cascade="save-update" inverse="true"> 30 one 31 <key column="bid"></key> 32 many 33 <many-to-many column="cid" class="com.jt4.entity.Category"></many-to-many> 34 </set> --> 35 </class> 36 </hibernate-mapping>
Dao方法层
BookDao
1 package com.spring.ssh.book.dao; 2 3 import java.util.List; 4 5 import org.hibernate.HibernateException; 6 import org.hibernate.Session; 7 import org.springframework.orm.hibernate5.HibernateCallback; 8 9 import com.spring.ssh.base.dao.BaseDao; 10 import com.spring.ssh.book.entity.Book; 11 /** 12 * 注意: 13 * 1.一定要继承BaseDao(是为了获取hibernateTemplete) 14 * 2.方法命名有讲究(一定符合声明式事务所定义的规则) 15 * 若不遵循规则,那么数据不会提交得到数据库 16 * 3.hibernateTemplete模板在执行查询的时候比较特殊 17 * @author Administrator 18 * 19 */ 20 public class BookDao extends BaseDao{ 21 22 //增 23 public int add(Book book) { 24 return (int) getHibernateTemplate().save(book); 25 26 } 27 28 //删 29 public void edit(Book book) { 30 getHibernateTemplate().update(book); 31 } 32 33 //改 34 public void del(Book book) { 35 getHibernateTemplate().delete(book); 36 } 37 38 //查 39 public List<Book> list(){ 40 return (List<Book>) getHibernateTemplate().execute(new HibernateCallback<List<Book>>() { 41 42 @Override 43 public List<Book> doInHibernate(Session session) throws HibernateException { 44 // TODO Auto-generated method stub 45 return session.createQuery("from Book").list(); 46 } 47 }); 48 } 49 50 }
web层
BookAction
1 package com.spring.ssh.book.web; 2 3 import java.util.List; 4 5 import com.opensymphony.xwork2.ModelDriven; 6 import com.spring.ssh.base.web.BaseAction; 7 import com.spring.ssh.book.biz.BookBiz; 8 import com.spring.ssh.book.entity.Book; 9 10 public class BookAction extends BaseAction implements ModelDriven<Book>{ 11 12 private Book book = new Book(); 13 14 private BookBiz bookBiz; 15 16 17 public BookBiz getBookBiz() { 18 return bookBiz; 19 } 20 21 22 public void setBookBiz(BookBiz bookBiz) { 23 this.bookBiz = bookBiz; 24 } 25 26 27 @Override 28 public Book getModel() { 29 // TODO Auto-generated method stub 30 return book; 31 } 32 33 //增 34 public String add() { 35 System.out.println(book); 36 this.bookBiz.add(book); 37 return null; 38 } 39 40 //改 41 public String edit() { 42 System.out.println(book); 43 this.bookBiz.edit(book); 44 return null; 45 } 46 47 //删 48 public String del() { 49 System.out.println(book); 50 this.bookBiz.del(book); 51 return null; 52 } 53 54 //查 55 public String list() { 56 List<Book> list2 = this.bookBiz.list(); 57 for (Book b : list2) { 58 System.out.println(b); 59 } 60 return null; 61 } 62 63 }
Biz
BookBiz
1 package com.spring.ssh.book.biz; 2 3 import java.util.List; 4 5 import com.spring.ssh.book.entity.Book; 6 7 public interface BookBiz { 8 //增 9 public int add(Book book); 10 11 //删 12 public void edit(Book book); 13 14 //改 15 public void del(Book book); 16 17 //查 18 public List<Book> list(); 19 }
Impl
BookBizImpl
1 package com.spring.ssh.book.biz.impl; 2 3 import java.util.List; 4 5 import com.spring.ssh.book.biz.BookBiz; 6 import com.spring.ssh.book.dao.BookDao; 7 import com.spring.ssh.book.entity.Book; 8 9 public class BookBizImpl implements BookBiz { 10 11 private BookDao bookDao; 12 13 public BookDao getBookDao() { 14 return bookDao; 15 } 16 17 public void setBookDao(BookDao bookDao) { 18 this.bookDao = bookDao; 19 } 20 21 @Override 22 public int add(Book book) { 23 // TODO Auto-generated method stub 24 return bookDao.add(book); 25 } 26 27 @Override 28 public void edit(Book book) { 29 // TODO Auto-generated method stub 30 bookDao.edit(book); 31 } 32 33 @Override 34 public void del(Book book) { 35 // TODO Auto-generated method stub 36 bookDao.del(book); 37 } 38 39 @Override 40 public List<Book> list() { 41 // TODO Auto-generated method stub 42 return bookDao.list(); 43 } 44 45 }
4. 整合案例演示
.1 entity
*.hbm.xml
4.2 dao
IXxxDAO
XxxDAOImpl(继承HibernateDaoSupport类,方便注入HibernateTemplate)
applicationContext-Xxx.xml
查询
this.getHibernateTemplate().execute(
4.3 biz
IXxxBiz
XxxBizImpl
applicationContext-Xxx.xml
4.4 test(junit4)
4.5 action
将action配置到applicationContext-Xxx.xml,
注:必须为多例模式(重要)
struts.xml配置注意事项:
1)
<!-- 将action创建交由spring容器来管理 -->
<constant name="struts.objectFactory" value="spring"></constant>
2)struts-Xxx.xml文件中的action的class属性类型填写spring中的id。
stuts.xml配置
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE struts PUBLIC 3 "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" 4 "http://struts.apache.org/dtds/struts-2.5.dtd"> 5 <struts> 6 <include file="struts-default.xml"></include> 7 <include file="struts-base.xml"></include> 8 <include file="struts-book.xml"></include> 9 </struts>
stuts-base.xml配置
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE struts PUBLIC 3 "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" 4 "http://struts.apache.org/dtds/struts-2.5.dtd"> 5 <struts> 6 <constant name="struts.i18n.encoding" value="UTF-8" /> 7 <constant name="struts.devMode" value="true" /> 8 <constant name="struts.configuration.xml.reload" value="true" /> 9 <constant name="struts.i18n.reload" value="true" /> 10 <constant name="struts.enable.DynamicMethodInvocation" value="true" /> 11 12 <package name="base" extends="struts-default" abstract="true"> 13 <global-allowed-methods>regex:.*</global-allowed-methods> 14 </package> 15 </struts>
stuts-book.xml配置
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE struts PUBLIC 3 "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" 4 "http://struts.apache.org/dtds/struts-2.5.dtd"> 5 <struts> 6 <package name="book" extends="base" namespace="/book"> 7 <action name="/book_*" class="bookAction" method="{1}"> 8 </action> 9 </package> 10 </struts>
5. web.xml配置
1 <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" 2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" 4 version="3.1"> 5 <display-name>Archetype Created Web Application</display-name> 6 <!-- 1、整合spring --> 7 <context-param> 8 <param-name>contextConfigLocation</param-name> 9 <param-value>classpath:spring-context.xml</param-value> 10 </context-param> 11 <listener> 12 <listener-class> 13 org.springframework.web.context.ContextLoaderListener 14 </listener-class> 15 </listener> 16 <!-- 2、整合struts2 --> 17 <filter> 18 <filter-name>struts2</filter-name> 19 <filter-class> 20 org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter 21 </filter-class> 22 </filter> 23 <filter-mapping> 24 <filter-name>struts2</filter-name> 25 <url-pattern>*.action</url-pattern> 26 </filter-mapping> 27 28 <!-- 3、添加过滤器 --> 29 <filter> 30 <filter-name>encodingFilter</filter-name> 31 <filter-class> 32 org.springframework.web.filter.CharacterEncodingFilter 33 </filter-class> 34 <async-supported>true</async-supported> 35 <init-param> 36 <param-name>encoding</param-name> 37 <param-value>UTF-8</param-value> 38 </init-param> 39 </filter> 40 <filter-mapping> 41 <filter-name>encodingFilter</filter-name> 42 <url-pattern>/*</url-pattern> 43 </filter-mapping> 44 45 </web-app>
Spring-context.xml配置
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:tx="http://www.springframework.org/schema/tx" 6 xmlns:aop="http://www.springframework.org/schema/aop" 7 xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 8 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 9 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd 10 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> 11 12 <import resource="spring-hibernate.xml"/> 13 <import resource="spring-book.xml"/> 14 15 </beans>
Spring-book.xml配置
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:tx="http://www.springframework.org/schema/tx" 6 xmlns:aop="http://www.springframework.org/schema/aop" 7 xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 8 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 9 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd 10 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> 11 12 <bean class="com.spring.ssh.book.dao.BookDao" parent="baseDao" id="bookDao"></bean> 13 <bean class="com.spring.ssh.book.biz.impl.BookBizImpl" parent="baseBiz" id="bookBiz"> 14 <property name="bookDao" ref="bookDao"></property> 15 </bean> 16 17 <bean class="com.spring.ssh.book.web.BookAction" parent="baseAction" id="bookAction"> 18 <property name="bookBiz" ref="bookBiz"></property> 19 </bean> 20 21 </beans>
数据库连接
db.properties
1 db.username=root 2 db.password=123 3 db.driverClass=com.mysql.jdbc.Driver 4 db.jdbcUrl=jdbc:mysql://127.0.0.1:3306/mysql?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT 5 db.initialPoolSize=10 6 db.maxPoolSize=20 7 db.minPoolSize=5 8 db.maxIdleTime=60 9 db.acquireIncrement=5 10 db.maxStatements=0 11 db.idleConnectionTestPeriod=60 12 db.acquireRetryAttempts=30 13 db.breakAfterAcquireFailure=true 14 db.testConnectionOnCheckout=false
测试:
查询
新增
book_id是自增
修改
删除