在spring配置DataSource数据源进行数据库操作及spring结合hibernate操作

本文深入探讨了如何在Spring MVC框架中整合使用Hibernate作为持久层,包括配置数据源、SessionFactory,实现声明式和注解式事务管理,并通过示例展示了如何在业务方法中使用事务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <!-- 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"/>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值