Spring hibernate事务 - 捕获22

时间:2012-01-26 15:18:11

标签: hibernate spring transactions

我正在使用Spring和Hibernate以及注释驱动的事务。 运行我的应用程序时,我收到一个异常“createCriteria在没有活动事务的情况下无效”。根据此Spring/Hibernate Exception: createCriteria is not valid without active transaction,解决方案是从sessionFactory配置中删除行<property name="current_session_context_class">thread</property>

但是,我还需要在@PostConstruct方法中进行一些事务性工作(从DB初始化)。 @PostConstruct方法不能是事务性的,所以我打开一个手动事务 - 但是当我删除上面的行(获得异常org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here)时这不起作用。根据几个来源,解决方案是将<property name="current_session_context_class">thread</property>添加到配置...

这是我的代码(我知道它不太好和干净 - 我一直在摆弄它以了解问题是什么):

`@Transactional 公共类TaskControllerImpl实现TaskController {

@Autowired
TaskDAO taskDAO;

@Autowired
MethodDAO methodDAO;

@Autowired
SessionFactory sessionFactory;

ExecutorService threadPool = Executors.newCachedThreadPool();


/**
 * Map of method name to TaskExecutor for all defined methods
 */
private Map<String, TaskExecutor> executorsByMethod;

final Logger logger = LoggerFactory.getLogger(TaskControllerImpl.class);

/**
 * Initializes the mapping of method name to TaskExecutor
 */
@PostConstruct
public void init() {
    // @Transactional has no effect in @Postconstruct methods so must do this manually
    Transaction t = sessionFactory.getCurrentSession().beginTransaction();
    executorsByMethod = new HashMap<String, TaskExecutor>();
    List<Method> methods = methodDAO.findAll();
    for (Method method : methods) {         
        if (method.getExecutorClassName() != null) {
            try {
                TaskExecutor executor = createTaskExecutor(method);
                executorsByMethod.put(method.getName(), executor);
            } catch (Throwable e) {
                logger.error("Coud not create/instantiate executor " + method.getExecutorClassName());
                e.printStackTrace();
            }
        }       
    }

    t.commit();
}

@Override
public void run() {
    Collection<Task> tasksToExecute = fetchTasksToExecute();
    for (Task task : tasksToExecute) {
        String method = task.getMethod().getName();
        executorsByMethod.get(method).addTask(task);
    }
}

/**
 * Fetches all tasks which need to be executed at the current time
 * 
 * @return
 */
private Collection<Task> fetchTasksToExecute() {
    try {
        Search search = new Search();
        search.addFilterLessThan("actionDate", DateUtil.now());
        search.addFilterEqual("status", TaskStatus.PENDING.getCode());
        search.addSort("actionDate", false);
        return taskDAO.search(search);
    } catch (Throwable e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }
}

`

配置:

`

<!-- Configure a JDBC datasource for Hibernate to connect with -->
<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="${connection.url}" />
    <property name="username" value="${connection.username}" />
    <property name="password" value="${connection.password}" />
</bean>

<!-- Configure a Hibernate SessionFactory -->
<bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan" value="com.grroo.model" />
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.show_sql">false</prop>
            <!-- prop key="hibernate.current_session_context_class">thread</prop-->
            <prop key="hibernate.connection.zeroDateTimeBehavior">convertToNull</prop>
        </props>
    </property>
</bean>

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

<tx:annotation-driven/> 

`

所以我在这里有一个关于如何使init()和run()工作的方法。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您只需要从postconstruct中提取您的事务方法,然后调用它。例如:

@PostConstruct
public void postConstruct(){
    init();
}

@Transactional
public void init(){
    ...
}