SSH框架也就是Struts2、Spring和Hibernate
在一个Web项目里面整合SSH框架,自己总结的注意点
- 在Web.xml中要配置监听器,让项目启动的时候,就在applicationContext域中加载Spring的核心配置文件
<!--Spring的核心监听器-->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!--
加载Spring的配置文件的路径的
默认加载的/WEB-INF/applicationContext.xml
-->
<context-param>
<param-name> contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
- 将Action类交给Spring管理,在struts.xml中的action的class参数就引用Spring中bean的id
<package name="struts" extends="struts-default">
<!--交给Spring管理,这里的class填写spring中bean的id-->
<action name="account_*" class="accountaction" method="{1}"/>
</package>
- 习惯使用xml配置和注解结合使用的方式完成对象的创建和属性注入,对象的创建由xml配置,属性注入用注解的方式,所以在xml中要开启注解属性注入的方式
<!--开启注解注入属性-->
<context:annotation-config/>
- 单独创建一个hibernateapplication.xml用于配置Hibernate信息,然后在applicationcontext.xml中通过import引入
<!--引入数据库配置文件-->
<import resource="hibernateapplication.xml"></import>
整合Hibernate
<!--加载数据库配置文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--配置druid连接池-->
<bean id="druid" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverclass}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--整合Hibeinate-->
<bean id="SessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<!--注入连接池-->
<property name="dataSource" ref="druid"/>
<!-- 配置Hibernate的相关属性 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<!--加载映射文件-->
<property name="mappingResources">
<list>
<value>Model/Account.hbm.xml</value>
</list>
</property>
</bean>
- Dao层实例应该继承HibernateDaoSupport,然后只要在Spring中给它注入SessionFactory属性,即会自动创建一个hibernateTemplate,hibernateTemplate可以对数据库进行一系列操作
下面是HibernateDaoSupport中的相关源码,可以看到如果hibernateTemplate==null就会自动创建一个hibernateTemplate
public final void setSessionFactory(SessionFactory sessionFactory) {
if (this.hibernateTemplate == null || sessionFactory != this.hibernateTemplate.getSessionFactory()) {
this.hibernateTemplate = this.createHibernateTemplate(sessionFactory);
}
}
- 不要忘记了打开事务哦,不然会报这个异常
org.springframework.dao.InvalidDataAccessApiUsageException
首先配置事务管理器,然后开启注解增强,最后在类上加上@Transactional
<!--配置事务管理器-->
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="SessionFactory"/>
</bean>
<!--开启注解,增强事务-->
<tx:annotation-driven transaction-manager="transactionManager"/>