【问题标题】:Transactions not working unless inside DAO除非在 DAO 内部,否则事务无法正常工作
【发布时间】:2011-04-09 20:49:43
【问题描述】:

我的事务有一个问题,即使用 @Transactional 注释调用 DAO 的服务会引发异常,指出会话未打开。我可以让它工作的唯一方法是使用 @Transactional 注释 DAO。到底会发生什么?

这是我想做但不起作用的:

class CustomerService {
    private CustomerDao dao;

    @Transactional
    public void foo() {
        int customerId = dao.getCustomer("fred");
    }
}

class CustomerDao {
    private HibernateTemplate hibernateTemplate;

    public int getCustomer(String name) {
        String sql = "SELECT {m.*} from Customers {m} where name=:name";
        Query qry = getSession().createSQLQuery(sql).addEntity("m", Customer.class);
        qry.setParameter("name", name);
        qry.setCacheable(false);
        List<Customer> list = qry.list();
        return list.iterator().next().getId();
    }

    private Session getSession() {
        return hibernateTemplate.getSessionFactory().getCurrentSession();
    }
}

这是我正在做的,但我不想这样做:

class CustomerService {
    private CustomerDao dao;

    public Customer(CustomerDao dao) {
        this.dao = dao;
    }

    public void foo() {
        int customerId = dao.getCustomer("fred");
    }
}

class CustomerDao {
    private HibernateTemplate hibernateTemplate;

    @Transactional
    public int getCustomer(String name) {
        String sql = "SELECT {m.*} from Customers {m} where name=:name";
        Query qry = getSession().createSQLQuery(sql).addEntity("m", Customer.class);
        qry.setParameter("name", name);
        qry.setCacheable(false);
        List<Customer> list = qry.list();
        return list.iterator().next().getId();
    }

    private Session getSession() {
        return hibernateTemplate.getSessionFactory().getCurrentSession();
    }
}

问题似乎是由于 CustomerService 在包装类的构造函数中实例化引起的,其中包装类是在 Spring xml 上下文文件中声明的:

class AllServices {
    private final CustomerService customerService;
    private final OrderService orderService;

    @Autowired
    public AllServices(CustomerDao customerDao, OrderDao orderDao) {
        this.customerService = new CustomerService(customerDao);
        this.orderService = new OrderService(orderDao);
    }

    public CustomerService getCustomerService() {
        return this.customerService;
    }

    public OrderService getOrderService() {
        return this.orderService;
    }
}

spring 文件长这样:

<context:annotation-config />
<import resource="classpath:db-spring-conf.xml"/>
<bean id="allServices" class="myPackage.AllServices" />

和 db-spring-conf:

<bean id="editorDatasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="${versioning.db}" />
    <property name="username" value="${versioning.user}" />
    <property name="password" value="${versioning.pass}" />
</bean>

<tx:annotation-driven transaction-manager="editorTransactionManager"/>

<bean id="editorSessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="editorDatasource"/>
    <property name="exposeTransactionAwareSessionFactory">
        <value>true</value>
    </property>
    <property name="annotatedClasses">
        <list>
            <value>myPackage.Order</value>
        </list>
    </property> 
    <property name="mappingResources">
        <list>
            <value>mappings/customer.hbm.xml</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.hbm2ddl.auto">validate</prop>
            <!-- Enable Query Cache -->
            <prop key="hibernate.cache.use_query_cache">false</prop>
            <!-- Enable 2nd Level Cache -->
            <prop key="hibernate.cache.use_second_level_cache">false</prop>
            <prop key="hibernate.connection.autocommit">false</prop>
            <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate3.SpringSessionContext</prop>
        </props>
    </property>
</bean>

<bean id="editorHibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
    <property name="sessionFactory" ref="editorSessionFactory"/>
</bean>

<bean id="editorTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="editorSessionFactory" />
</bean>

<!-- DAOs -->
<bean id="customerDao" class="myPackage.CustomerHibernateDao" />
<bean id="orderDao" class="myPackage.OrderHibernateDao" />

我现在已经将 CustomerService 的实例化移到 Spring 配置文件中,并且一切正常。所有使用@Transactional 的类都必须在上下文文件中吗?此外,为了使其工作,我必须为 CustomerService 创建一个接口,以防止在加载上下文文件时出现异常 - Could not generate CGLIB subclass of class

【问题讨论】:

  • 也许事务方面不适用于CustomerService。显示它的配置方式。
  • 请显示您的 spring xml 配置

标签: java spring transactions annotations dao


【解决方案1】:

所以,您确定了问题的原因 - Spring 的 @Transactional 支持是一个方面,Spring 中的方面仅适用于由 Spring 容器管理的组件(虽然它是 can be changed,但它是复杂的高级功能例)。

如果你不喜欢在 XML 中声明服务,你可以看看其他选项来删除 Spring 管理的组件:

关于 CGLIB 代理的问题,请参阅 7.6 Proxying mechanisms - 可能您的类路径中没有 CGLIB 实现。

【讨论】:

    猜你喜欢
    • 2018-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-19
    • 2021-04-09
    相关资源
    最近更新 更多