Java之Spring配置事务

Spring事务

Spring中事务的管理就是通过AOP将事务的代码进行抽取

XML配置

第一步 创建c3p0连接池
将sessionFactory中的数据库相关属性替换为c3p0

<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
    <property name="jdbcUrl" value="jdbc:mysql:///MyDB"></property>
    <property name="user" value="root"></property>
    <property name="password" value="123456"></property>
</bean>

第二步 创建事务管理对象

<bean name="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
    <!-- 注入会话工厂 -->
    <property name="sessionFactory" ref="sessionFactory"></property>
</bean>

第三步 设置会话策略

<tx:advice id="advice" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="insert*" read-only="false"/>
        <tx:method name="select*" read-only="true"/>
        <tx:method name="update*" read-only="false"/>
        <tx:method name="delete*" read-only="false"/>
    </tx:attributes>
</tx:advice>

第四步 织入

<aop:config>
    <aop:pointcut expression="execution(* com.lanou.dao.impl.*.*(..))" id="point"/>
    <aop:advisor advice-ref="advice" pointcut-ref="point"/>
</aop:config>

注解配置

前两步和注解一样
第三步 启动AOP事务注解

<tx:annotation-driven/>

第四步 添加注解

@Transactional
public class UserDaoImpl extends HibernateDaoSupport implements UserDao

SSH操作数据库(HibernateDaoSupport)

为了节省代码 Spring提供模板类用于dao层操作数据库
封装了常用功能:获取session 执行查询等...
在SSH中 只要进行CRUD就继承HibernateDaoSupport 它能帮我们管理session
注意:别忘记注入sessionFactory

实现步骤:
    1.直接将Dao实现类继承自 HibernateDaoSupport类
    2.通过调用父类的getHibernateTemplate获取模板对象
    3.面向对象的  save delete update get
    4.使用hql语句/使用离线查询

使用HQL实例

public List<User> selectAllUser() {
    // 演示如何使用HQL
    return getHibernateTemplate().execute(new HibernateCallback<List<User>>() {

        // 将CRUD的操作放到这个方法中 模板对象会自动调用
        @Override
        public List<User> doInHibernate(Session session) throws HibernateException {
            String hql = "from User";
            Query query = session.createQuery(hql);
            List<User> list = query.list();
            return list;
        }
    });
}

离线查询实例

public User selectUserByName(String name) {
    // 离线查询对象
    DetachedCriteria criteria = DetachedCriteria.forClass(User.class);
    // 添加查询条件
    criteria.add(Restrictions.eq("name", name));
    List<User> list = (List<User>) getHibernateTemplate().findByCriteria(criteria);
    if (list != null && list.size() > 0) {
        return list.get(0);
    }
    return null;
}

猜你喜欢

转载自blog.csdn.net/Dzy_water/article/details/80056602
今日推荐