org.springframework.transaction.CannotCreateTransactionException,无法打开Hibernate Session进行事务处理

时间:2018-04-08 17:10:43

标签: spring hibernate spring-mvc

HibernateConfig

@Configuration
@ComponentScan(basePackages = { "com.app.EcommerceBackend.dto" })
@EnableTransactionManagement
public class HibernateConfig {

    // Change the below based on the DBMS you choose
    private final static String DATABASE_URL = "jdbc:h2:tcp://localhost/~/ecommerce";
    private final static String DATABASE_DRIVER = "org.h2.Driver";
    private final static String DATABASE_DIALECT = "org.hibernate.dialect.H2Dialect";
    private final static String DATABASE_USERNAME = "sa";
    private final static String DATABASE_PASSWORD = "";

    // dataSource bean will be available
    @Bean
    public DataSource getDataSource() {
        BasicDataSource dataSource = new BasicDataSource();

        // Providing the database connection information
        dataSource.setDriverClassName(DATABASE_DRIVER);
        dataSource.setUrl(DATABASE_URL);
        dataSource.setUsername(DATABASE_USERNAME);
        dataSource.setPassword(DATABASE_PASSWORD);

        return dataSource;
    }
    // sessionFactory bean will be available
    @Bean
    public SessionFactory getSessionFactory(DataSource dataSource) {
        LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource);
        builder.addProperties(getHibernateProperties());
        builder.scanPackages("com.app.EcommerceBackend.dto");
        return builder.buildSessionFactory();
    }

    // All the hibernate properties will be returned in this method
    private Properties getHibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", DATABASE_DIALECT);
        properties.put("hibernate.show_sql", "true");
        properties.put("hibernate.format_sql", "true");
        // properties.put("hibernate.hbm2ddl.auto", "create");
        return properties;
    }

    // transactionManager bean
    @Bean
    public HibernateTransactionManager getTransactionManager(SessionFactory sessionFactory) {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager(sessionFactory);
        return transactionManager;
    }
}

CategoryDAOImpl

@Repository("categoryDAO")
@Transactional
public class CategoryDAOImpl implements CategoryDAO {

    @Autowired
    private SessionFactory sessionFactory;
    private static List<Category> categories = new ArrayList<>();

    static {
        Category category = new Category();
        // Add First Element
        category.setId(1);
        category.setName("Television");
        category.setDescription("this is some desc for television");
        category.setImageURL("img1.jpg");
        categories.add(category);

        // Add Second Element
        category = new Category();
        category.setId(2);
        category.setName("Mobile");
        category.setDescription("this is some desc for Mobile");
        category.setImageURL("img2.jpg");
        categories.add(category);

        // Add Third Element
        category = new Category();
        category.setId(3);
        category.setName("Laptop");
        category.setDescription("this is some desc for Laptop");
        category.setImageURL("img3.jpg");
        categories.add(category);
    }

    @Override
    public List<Category> list() {
        return categories;

    }

    @Override
    public Category get(int id) {
        for (Category category : categories) {
            if (category.getId() == id)
                return category;
        }
        return null;
    }

    @Override
    public boolean add(Category category) {
        // add the category to the databse table
        try {
            sessionFactory.getCurrentSession().persist(category);
            return true;
        } catch(Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}

分类

@Entity
public class Category implements Serializable{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String name;
    private String description;

    @Column(name = "image_url")
    private String imageURL;

    @Column(name = "is_active")
    private boolean active = true;

    @Override
    public String toString() {
        return "Category [id=" + id + ", name=" + name + ", description=" + description + ", imageURL=" + imageURL
                + ", active=" + active + "]";
    }
}

CategoryTestClass

public class CategoryTestCase {

    private static AnnotationConfigApplicationContext context;

    private static CategoryDAO categoryDAO;

    private Category category;

    @BeforeClass
    public static void init() throws Exception {
        org.h2.tools.Server.createTcpServer().start();
        context = new AnnotationConfigApplicationContext();
        context.scan("com.app.EcommerceBackend");
        context.refresh();
        categoryDAO = (CategoryDAO) context.getBean("categoryDAO");
    }

    @Test
    public void testAddCategory() {

        category = new Category();

        category.setName("Laptop");
        category.setDescription("This is some description for laptop!");
        category.setImageURL("CAT_105.png");

        assertEquals("Successfully added a category inside the table!", true, categoryDAO.add(category));

    }
}

出现此错误

org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection
    at org.springframework.orm.hibernate5.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:542)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:447)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:277)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy29.add(Unknown Source)
    at com.app.EcommerceBackend.test.CategoryTestCase.testAddCategory(CategoryTestCase.java:40)

为什么我会获得嵌套异常

  

无法打开Hibernate会话进行交易

似乎一切都很好,为什么会出现这个错误?

您也可以检查github代码

1 个答案:

答案 0 :(得分:0)

默认情况下,事务管理器bean名称是transactionManager,因此将返回HibernateTransactionManager的方法重命名为transactionManager