HibernateException:没有活动事务,createQuery无效

时间:2016-11-27 07:05:55

标签: java spring hibernate

程序化配置似乎已经到位但由于某种原因应用程序抛出异常:

org.springframework.orm.jpa.JpaSystemException: createQuery is not valid without active transaction; nested exception is org.hibernate.HibernateException: createQuery is not valid without active transaction

代码:

@Repository
public class FilmDAOImpl implements FilmDAO {
@Autowired
    private HibernateUtil hibernateUtil;

    @Autowired
    private SessionFactory sessionFactory;
@Override
    public List<Film> findFilms(int actorId, int categoryId, int languageId, int releaseYear) {

        Query searchQuery = sessionFactory.getCurrentSession().createQuery("from Film " +
                "join Actor " +
                "join Category " +
                "where Category.categoryId=:categoryId " +
                "and Film.language.id=:languageId " +
                "and Film.releaseYear=:releaseYear " +
                "and Actor.actorId=:actorId");
        searchQuery.setParameter("categoryId", categoryId);
        searchQuery.setParameter("languageId", languageId);
        searchQuery.setParameter("releaseYear", releaseYear);
        searchQuery.setParameter("actorId", actorId);
        return (List<Film>)searchQuery.list();
    }

}

配置:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories (basePackages = { "com.hibernate.query.performance.persistence" }, transactionManagerRef = "jpaTransactionManager")
@EnableJpaAuditing
@PropertySource({ "classpath:persistence-postgresql.properties" })
@ComponentScan(basePackages = { "com.hibernate.query.performance" })
public class ApplicationConfig {

    @Autowired
    private Environment env;

    public ApplicationConfig() {
        super();
    }

    @Bean
    public LocalSessionFactoryBean sessionFactory() {
        final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(applicationDataSource());
        sessionFactory.setPackagesToScan(new String[] { "com.hibernate.query.performance.persistence.model" });
        sessionFactory.setHibernateProperties(hibernateProperties());

        return sessionFactory;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        final LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
        emf.setDataSource(applicationDataSource());
        emf.setPackagesToScan(new String[] { "com.hibernate.query.performance.persistence.model" });

        final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        emf.setJpaVendorAdapter(vendorAdapter);
        emf.setJpaProperties(hibernateProperties());

        return emf;
    }

    @Primary
    @Bean
    public DriverManagerDataSource applicationDataSource() {
        final DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
        dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
        dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
        dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
        return dataSource;
    }



    @Bean
    @Primary
    public PlatformTransactionManager hibernateTransactionManager() {
        final HibernateTransactionManager transactionManager = new HibernateTransactionManager();
        transactionManager.setSessionFactory(sessionFactory().getObject());
        transactionManager.setDataSource(applicationDataSource());
        return transactionManager;
    }

    @Bean
    public PlatformTransactionManager jpaTransactionManager() {
        final JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
        return transactionManager;
    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
        return new PersistenceExceptionTranslationPostProcessor();
    }

    private final Properties hibernateProperties() {
        final Properties hibernateProperties = new Properties();
        hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
        hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
        hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
        hibernateProperties.setProperty("hibernate.format_sql", env.getProperty("hibernate.format_sql"));
        hibernateProperties.setProperty("hibernate.generate_statistics", env.getProperty("hibernate.generate_statistics"));
        hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache"));
        hibernateProperties.setProperty("hibernate.cache.region.factory_class", env.getProperty("hibernate.cache.region.factory_class"));
        hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache"));
        hibernateProperties.setProperty("hibernate.current_session_context_class", "managed");
        hibernateProperties.setProperty("hibernate.current_session_context_class", "org.hibernate.context.internal.ThreadLocalSessionContext");

        return hibernateProperties;
    }
}

更新

@Service
@Transactional
public class FilmServiceImpl implements FilmService {

    @Autowired
    private FilmDAO filmDAO;

    @Override
    public int createFilm(Film film) {
        return filmDAO.createFilm(film);
    }

    @Override
    public Film updateFilm(Film film) {
        return filmDAO.updateFilm(film);
    }

    @Override
    public void deleteFilm(int id) {
        filmDAO.deleteFilm(id);
    }

    @Override
    public List<Film> getAllFilms() {
        return filmDAO.getAllFilms();
    }

    @Override
    public Film getFilm(int id) {
        return filmDAO.getFilm(id);
    }

    @Override
    public List<Film> findFilms(int actorId, int categoryId, int languageId, int releaseYear) {
        return filmDAO.findFilms(actorId, categoryId, languageId, releaseYear);
    }
}

1 个答案:

答案 0 :(得分:0)

尝试使用 openSession(),如下所示,因为getCurrentSession()只是附加到当前会话:

Query searchQuery = sessionFactory.openSession().createQuery(...

此外,您需要使用正确的try..catch ...最终阻止代码并最终使用session.close()

关闭会话