宗旨:hibernate 里面的东西都要交给spring 去托管,去除hibernate.cfg.xml,然后为了项目的轻量级,我们采用注解的形式替代hibernate 映射文件
核心就是在applicationContext.xml
// 1: ssh 都是注解,所以开启spring 扫描注解
<context:component-scan base-package="com.lanou" />
2:因为我们的连接数据库的信息都在jdbc.properties
Src/main/resource
里面所以
<!-- 读取jdbc property -->
<context:property-placeholder location="classpath:jdbc.properties" />
3:配置数据库连接池(c3p0,druid,dbcp)注意 jdbc.properties 里面的key 一定要有前缀
例如 jdbc.url jdbc.driverName
<!-- 配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${jdbc.driverName}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.userName}" />
<property name="password" value="${jdbc.password}" />
</bean>
${jdbc.driverName} 取jdbc.properties 里面的key 为jdbc.driverName 的value 值
Property 里面 name 为driverClass 驱动全类名属性
Property 里面 name 为 jdbcUrl 连接数据库的url
Property 里面 name 为 user 数据库的用户名
Property 里面 name 为 password 数据库的密码
4:配置sessionFactory
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<!-- 注入sessionFactory -->
<property name="dataSource" ref="dataSource" />
<!-- 实体的 packagesToScan 扫描包 -->
<property name="packagesToScan">
<list>
<!-- 可以加多个包 -->
<value>com.lanou.entity</value>
</list>
</property>
<!-- hibernate 一些配置 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.Dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
<!-- <prop key="hibernate.current_session_context_class">thread</prop> -->
<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop>
</props>
</property>
</bean>
注意:
org.springframework.orm.hibernate4.LocalSessionFactoryBean
Spring +hibernate4 配置sessionFactory class 路径 bean id sessionFactory
1:将 bean id 为dataSource 注入 sessionFacotry 属性为dataSource 例如
<property name="dataSource" ref="dataSource" />
2:扫描 注解的实体类
3:配置hibernate 的一些属性
<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop>
这一点的配置,我们可以在代码中使用getCurrentSession
一定要配合
<!-- 事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
4:注解方式使用事务 也要依赖于 事务管理器
<!-- 注解实现事务管理 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
Spring + struts2
必须要有
XXXXAction 这个类中,添加一个注解 @Controller
Struts.xml <action class=”spring beanid ” beanid 一般都是XXXXAction 首字母小写
在web.xml
<!-- 指定spring 配置文件的位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
1: spring 监听
2:openSessionInViewFilter
3: struts 核心过滤器