无法解决错误"没有活动交易,保存无效"

时间:2017-10-06 15:47:19

标签: java hibernate jpa

我无法解决错误

  如果没有活动交易,

保存无效

我的代码:

hibernate.current_session_context_class

在很多博客上我都知道从JPA属性中删除once将解决这个问题。但当我删除它时,我得到以下错误

  

没有配置CurrentSessionContext!

1 个答案:

答案 0 :(得分:1)

您正在配置SessionFactory和EntityManagerFactory。删除所有Hibernate特定的东西:

@Configuration
public class PersistenceJPAConfig {

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource());
        em.setPackagesToScan(new String[] { "self.experiment.dto" });

        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        em.setJpaProperties(additionalProperties());

        return em;
    }

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/test?autoReconnect=true&useSSL=false");
        dataSource.setUsername("root");
        dataSource.setPassword("root");

        return dataSource;
    }

    @Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(emf);

        return transactionManager;
    }

    Properties additionalProperties() {
        Properties properties = new Properties();
        properties.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
        properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
        properties.setProperty("hibernate.show_sql", "false");
        return properties;
    }
}

服务

public class UserBL {

@Autowired
UserDAO userDao;

@Transactional
public void saveUsers(){
    User user = new User();
    user.setName("Bob");

    userDao.insert(user);
}
}

DAO

public class UserDAO {
    @PersistenceContext
    private EntityManager em;
}