<!-- results in a setDriverClassName(String) call -->
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/spring"/>
<property name="username" value="root"/>
<property name="password" value="527425"/>
</bean>
@Resource
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}使用setter注入datasource;通过Connection conn = dataSource.getConnection();获得连接
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">//主义使用的是hibernate4而不是3
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan">
<list>
<value>com.gxk.model</value>//扫描此包下的所有的注解的实体并加载
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
</value>
</property>
</bean>
使用xml进行声明式事务管理
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager"/>
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="add*" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="uService" expression="execution(public * com.gxk.service..*(..))"/>//在 com.gxk.service路径下的所有的public方法都会进行事务处理(省去了写事务begin和事务commit)
<aop:advisor advice-ref="txAdvice" pointcut-ref="uService"/>
</aop:config>
使用annotation进行事务管理
@Transactional//(readOnly=true)(readOnly表示只读)默认为required(当前有session则使用当前的,没有则创建一个session)
public void add(User u){
this.userDAO.save(u);
save.log()
}任何一个出错会同时事务回滚
同时在xml中加上 <tx:annotation-driven transaction-manager="txManager"/>