0

I have a project that uses the following tools and frameworks: Spring mvc 5, hibernate 5, junit 5 and maven. I wrote a simple test class as the following:

@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes=DBConfig.class)
public class TestCustomDaoImpl()
{
    @Test
    public void simpleTest()
    {
        String s = new String();
        assertNotNull(s);
    }
}

Now when I try to run this in eclipse as a unit test, a lot (and I mean a lot of hibernate) queries are being generated and tested automatically (seems for all entities defined in model package which is included in component scan annotation in DBConfig class). I don't know why or where all these queries and tests are coming from, and the worst thing that exceptions are thrown so my simple test class is never reached. Any idea why? and if anyone one could provide a good example Spring mvc 5 testing with junit 5 and hibernate 5 I would be grateful.

DBConfig class

package com.tc.gs.config;

import java.beans.PropertyVetoException;
import java.util.Properties;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.jndi.JndiObjectFactoryBean;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.tc.gs.config.condition.CoreDataSourceBeanCondition;
import com.tc.gs.config.condition.JNDIDataSourceBeanCondition;

@Configuration
@EnableTransactionManagement
@PropertySource("dbConfig.properties")
public class DBConfig {

    @Bean(name = "tcDataSource")
    @Conditional(JNDIDataSourceBeanCondition.class)
    public JndiObjectFactoryBean tcJNDIDataSource() {
        JndiObjectFactoryBean jndiObjectFB = new JndiObjectFactoryBean();
        jndiObjectFB.setJndiName("jdbc/TcDB");
        jndiObjectFB.setResourceRef(true);
        jndiObjectFB.setProxyInterface(javax.sql.DataSource.class);
        return jndiObjectFB;
    }

    @Bean(name = "tcDataSource", destroyMethod = "close")
    @Conditional(CoreDataSourceBeanCondition.class)
    public ComboPooledDataSource tcDataSource(@Value("${ip}") String ip, @Value("${port}") String port, @Value("${schema}") String schema,
            @Value("${user}") String user, @Value("${password}") String password, @Value("${maxPoolSize}") String maxPoolSize,
            @Value("${maxStatements}") String maxStatements, @Value("${minPoolSize}") String minPoolSize, @Value("${driver}") String driver,
            @Value("${databaseType}") String databaseType)
    {
        ComboPooledDataSource tcDataSource = new ComboPooledDataSource();
        try {
            tcDataSource.setDriverClass(driver);
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
        tcDataSource
                .setJdbcUrl("jdbc:mysql://" + ip + ":" + port + "/" + schema + "?useUnicode=true&characterEncoding=utf-8&max_allowed_packet=32M");
        tcDataSource.setUser(user);
        tcDataSource.setPassword(password);
        tcDataSource.setMaxPoolSize(Integer.parseInt(maxPoolSize));
        tcDataSource.setMaxStatements(Integer.parseInt(maxStatements));
        tcDataSource.setMinPoolSize(Integer.parseInt(minPoolSize));
        tcDataSource.setPreferredTestQuery("SELECT 1;");
        tcDataSource.setTestConnectionOnCheckout(true);
        tcDataSource.setIdleConnectionTestPeriod(1800);
        return tcDataSource;
    }


    @Bean
    LocalContainerEntityManagerFactoryBean tcEntityManagerFactoryBean(DataSource tcDataSource) {
        LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactory.setDataSource(tcDataSource);
        entityManagerFactory.setPackagesToScan("com.tc.gs.model");
        entityManagerFactory.setJpaVendorAdapter(new HibernateJpaVendorAdapter());

        Properties jpaProperties = new Properties();
        jpaProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
         jpaProperties.setProperty("hibernate.hbm2ddl.auto", "update");
        // jpaProperties.setProperty("hibernate.hbm2ddl.auto", "create");
        //jpaProperties.setProperty("hibernate.hbm2ddl.auto", "validate");
        jpaProperties.setProperty("hibernate.connection.characterEncoding", "utf8");
        jpaProperties.setProperty("hibernate.show_sql", "true");
        jpaProperties.setProperty("hibernate.use_sql_comments", "false");
        jpaProperties.setProperty("hibernate.format_sql", "false");
        jpaProperties.setProperty("hibernate.generate_statistics", "true");
        jpaProperties.setProperty("hibernate.jdbc.batch_size", "100");

        entityManagerFactory.setJpaProperties(jpaProperties);
        entityManagerFactory.setPersistenceUnitName("TC-JPA");

        return entityManagerFactory;
    }

    @Bean
    PlatformTransactionManager tcTrxManger(EntityManagerFactory tcEntityManagerFactoryBean) {
        return new JpaTransactionManager(tcEntityManagerFactoryBean);
    }

    @Bean
    PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor() {
        return new PersistenceExceptionTranslationPostProcessor();
    }
}

Note: The current project is not a spring boot project which is making things much more difficult since almost all the examples and configs I find online uses spring boot.

A snapshot of the result (couldn't include it all cause it is tooo long). However, my actual problem is why in the first place is it running such queries:

14:01:08.899 [main] DEBUG o.h.loader.entity.plan.EntityLoader - Static select for entity com.tc.gs.model.Product [OPTIMISTIC]: select product0_.ID as ID1_29_0_, product0_.CREATE_DATE as CREATE_D2_29_0_, product0_.UPDATE_DATE as UPDATE_D3_29_0_, product0_.STATUS as STATUS4_29_0_, product0_.USER_ID as USER_ID5_29_0_, product0_.DESCRIPTION_AR as DESCRIPT6_29_0_, product0_.DESCRIPTION_EN as DESCRIPT7_29_0_, product0_.NAME_AR as NAME_AR8_29_0_, product0_.NAME_EN as NAME_EN9_29_0_, product0_.PRICE as PRICE10_29_0_, product0_.PRODUCT_NODE_ID as PRODUCT12_29_0_, product0_.SERVICE_CODE as SERVICE11_29_0_ from product product0_ where product0_.ID=?
14:01:08.899 [main] DEBUG o.h.l.p.b.i.spaces.QuerySpacesImpl - Adding QuerySpace : uid = <gen:0> -> org.hibernate.loader.plan.build.internal.spaces.EntityQuerySpaceImpl@511da44f]
14:01:08.899 [main] DEBUG o.h.p.w.spi.MetamodelGraphWalker - Visiting attribute path : createDate

                                .
                                .
                                .

14:01:08.899 [main] DEBUG o.h.p.w.spi.MetamodelGraphWalker - Visiting attribute path : productNode
14:01:08.900 [main] DEBUG o.h.l.p.b.i.spaces.QuerySpacesImpl - Adding QuerySpace : uid = <gen:1> -> org.hibernate.loader.plan.build.internal.spaces.EntityQuerySpaceImpl@3a0b6a]
14:01:08.900 [main] DEBUG o.h.p.w.spi.MetamodelGraphWalker - Visiting attribute path : serviceCode
14:01:08.900 [main] DEBUG o.h.l.p.b.i.FetchStyleLoadPlanBuildingAssociationVisitationStrategy - Building LoadPlan...
14:01:08.900 [main] DEBUG o.h.l.p.e.i.LoadQueryJoinAndFetchProcessor - processing queryspace <gen:0>
14:01:08.900 [main] DEBUG o.h.l.p.b.spi.LoadPlanTreePrinter - LoadPlan(entity=com.tc.gs.model.Product)
    - Returns
       - EntityReturnImpl(entity=com.tc.gs.model.Product, querySpaceUid=<gen:0>, path=com.tc.gs.model.Product)
          - EntityAttributeFetchImpl(entity=com.tc.gs.model.ProductNode, querySpaceUid=<gen:1>, path=com.tc.gs.model.Product.productNode)
    - QuerySpaces
       - EntityQuerySpaceImpl(uid=<gen:0>, entity=com.tc.gs.model.Product)
          - SQL table alias mapping - product0_
          - alias suffix - 0_
          - suffixed key columns - {ID1_29_0_}

14:01:08.900 [main] DEBUG o.h.loader.entity.plan.EntityLoader - Static select for entity com.tc.gs.model.Product [OPTIMISTIC_FORCE_INCREMENT]: select product0_.ID as ID1_29_0_, product0_.CREATE_DATE as CREATE_D2_29_0_, product0_.UPDATE_DATE as UPDATE_D3_29_0_, product0_.STATUS as STATUS4_29_0_, product0_.USER_ID as USER_ID5_29_0_, product0_.DESCRIPTION_AR as DESCRIPT6_29_0_, product0_.DESCRIPTION_EN as DESCRIPT7_29_0_, product0_.NAME_AR as NAME_AR8_29_0_, product0_.NAME_EN as NAME_EN9_29_0_, product0_.PRICE as PRICE10_29_0_, product0_.PRODUCT_NODE_ID as PRODUCT12_29_0_, product0_.SERVICE_CODE as SERVICE11_29_0_ from product product0_ where product0_.ID=?
14:01:08.900 [main] DEBUG org.hibernate.loader.Loader - Static select for action ACTION_MERGE on entity com.tc.gs.model.Product: select product0_.ID as ID1_29_0_, product0_.CREATE_DATE as CREATE_D2_29_0_, product0_.UPDATE_DATE as UPDATE_D3_29_0_, product0_.STATUS as STATUS4_29_0_, product0_.USER_ID as USER_ID5_29_0_, product0_.DESCRIPTION_AR as DESCRIPT6_29_0_, product0_.DESCRIPTION_EN as DESCRIPT7_29_0_, product0_.NAME_AR as NAME_AR8_29_0_, product0_.NAME_EN as NAME_EN9_29_0_, product0_.PRICE as PRICE10_29_0_, product0_.PRODUCT_NODE_ID as PRODUCT12_29_0_, product0_.SERVICE_CODE as SERVICE11_29_0_ from product product0_ where product0_.ID=?
14:01:08.900 [main] DEBUG org.hibernate.loader.Loader - Static select for action ACTION_REFRESH on entity com.tc.gs.model.Product: select product0_.ID as ID1_29_0_, product0_.CREATE_DATE as CREATE_D2_29_0_, product0_.UPDATE_DATE as UPDATE_D3_29_0_, product0_.STATUS as STATUS4_29_0_, product0_.USER_ID as USER_ID5_29_0_, product0_.DESCRIPTION_AR as DESCRIPT6_29_0_, product0_.DESCRIPTION_EN as DESCRIPT7_29_0_, product0_.NAME_AR as NAME_AR8_29_0_, product0_.NAME_EN as NAME_EN9_29_0_, product0_.PRICE as PRICE10_29_0_, product0_.PRODUCT_NODE_ID as PRODUCT12_29_0_, product0_.SERVICE_CODE as SERVICE11_29_0_ from product product0_ where product0_.ID=?
14:01:08.900 [main] DEBUG o.h.p.entity.AbstractEntityPersister - Static SQL for entity: com.tc.gs.model.fb.FBUser
14:01:08.900 [main] DEBUG o.h.p.entity.AbstractEntityPersister -  Version select: select ID from fb_user where ID =?
14:01:08.900 [main] DEBUG o.h.p.entity.AbstractEntityPersister -  Snapshot select: select fbuser_.ID, fbuser_.CREATE_DATE as CREATE_D2_12_, fbuser_.UPDATE_DATE as UPDATE_D3_12_, fbuser_.STATUS as STATUS4_12_, fbuser_.BIRTHDAY as BIRTHDAY5_12_, fbuser_.BOT_LANGUAGE as BOT_LANG6_12_, fbuser_.EMAIL as EMAIL7_12_, fbuser_.FB_ID as FB_ID8_12_, fbuser_.FIRST_NAME as FIRST_NA9_12_, fbuser_.GENDER as GENDER10_12_, fbuser_.HOMETOWN as HOMETOW11_12_, fbuser_.LAST_LOGIN as LAST_LO12_12_, fbuser_.LAST_NAME as LAST_NA13_12_, fbuser_.MOBILE_NO as MOBILE_14_12_, fbuser_.mobile_No_Verified as mobile_15_12_, fbuser_.PROFILE_PICTURE_URL as PROFILE16_12_, fbuser_.SEND_PASS_CODE as SEND_PA17_12_, fbuser_.USER_LANGUAGE as USER_LA18_12_, fbuser_.USERNAME as USERNAM19_12_ from fb_user fbuser_ where fbuser_.ID=?
14:01:08.900 [main] DEBUG o.h.p.entity.AbstractEntityPersister -  Insert 0: insert into fb_user (CREATE_DATE, UPDATE_DATE, STATUS, BIRTHDAY, BOT_LANGUAGE, EMAIL, FB_ID, FIRST_NAME, GENDER, HOMETOWN, LAST_LOGIN, LAST_NAME, MOBILE_NO, mobile_No_Verified, PROFILE_PICTURE_URL, SEND_PASS_CODE, USER_LANGUAGE, USERNAME, ID) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
14:01:08.900 [main] DEBUG o.h.p.entity.AbstractEntityPersister -  Update 0: update fb_user set CREATE_DATE=?, UPDATE_DATE=?, STATUS=?, BIRTHDAY=?, BOT_LANGUAGE=?, EMAIL=?, FB_ID=?, FIRST_NAME=?, GENDER=?, HOMETOWN=?, LAST_LOGIN=?, LAST_NAME=?, MOBILE_NO=?, mobile_No_Verified=?, PROFILE_PICTURE_URL=?, SEND_PASS_CODE=?, USER_LANGUAGE=?, USERNAME=? where ID=?
14:01:08.900 [main] DEBUG o.h.p.entity.AbstractEntityPersister -  Delete 0: delete from fb_user where ID=?
14:01:08.900 [main] DEBUG o.h.p.entity.AbstractEntityPersister -  Identity insert: insert into fb_user (CREATE_DATE, UPDATE_DATE, STATUS, BIRTHDAY, BOT_LANGUAGE, EMAIL, FB_ID, FIRST_NAME, GENDER, HOMETOWN, LAST_LOGIN, LAST_NAME, MOBILE_NO, mobile_No_Verified, PROFILE_PICTURE_URL, SEND_PASS_CODE, USER_LANGUAGE, USERNAME) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
14:01:08.900 [main] DEBUG o.h.l.p.b.i.spaces.QuerySpacesImpl - Adding QuerySpace : uid = <gen:0> -> org.hibernate.loader.plan.build.internal.spaces.EntityQuerySpaceImpl@539c4830]

                                .
                                .
                                .

14:01:08.902 [main] DEBUG o.h.p.w.spi.MetamodelGraphWalker - Visiting attribute path : username
14:01:08.902 [main] DEBUG o.h.l.p.b.i.FetchStyleLoadPlanBuildingAssociationVisitationStrategy - Building LoadPlan...
14:01:08.902 [main] DEBUG o.h.l.p.e.i.LoadQueryJoinAndFetchProcessor - processing queryspace <gen:0>
14:01:08.903 [main] DEBUG o.hibernate.engine.spi.CascadeStyles - External cascade style registration [persist : STYLE_PERSIST] overrode base registration [STYLE_PERSIST_SKIPLAZY]
14:01:08.903 [main] DEBUG o.h.s.i.AbstractServiceRegistryImpl - Implicitly destroying ServiceRegistry on de-registration of all child ServiceRegistries
14:01:08.903 [main] DEBUG o.h.b.r.i.BootstrapServiceRegistryImpl - Implicitly destroying Boot-strap registry on de-registration of all child ServiceRegistries
14:01:08.903 [main] WARN  o.s.w.c.s.GenericWebApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tcEntityManagerFactoryBean' defined in class path resource [com/tc/gs/config/DBConfig.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: tc-JPA] Unable to build Hibernate SessionFactory
14:01:08.903 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@45c9b3: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,nlpMainConfig,NLPConfig,nlpLookups,nlpAppManagementDao,NlpAppSettingsDao,nlpEntityKeywordManagementDao,nlpEntityKeywordSynonymsManagementDao,nlpEntityManagementDao,nlpIntentManagementDao,nlpUtteranceManagementDao,entityGroupService,googleTranslationApiService,intentGroupService,languageLookupService,microsoftTranslationApiService,nlpAppGroupService,nlpAppManagementService,nlpAppMessageManagementService,nlpAppSetttingsService,nlpEntityChildManagementService,nlpEntityKeywordManagementService,nlpEntityKeywordSynonymsManagementServiceImpl,nlpEntityManagementService,nlpIntentManagementService,nlpUtteranceManagementService,prebuiltEntityLookupService,witApiClientService,witLookupStrategyLookupService,mailConfig,mainConfig,SMSConfig,dashboardDAO,dashboardBotDAO,faqDao,fbLikeDao,fbCategoryDao,fbUserDao,hashTagDAO,productsDao,userPrivilegeDAO,sequenceDAO,userDao,wordDAO,advertisementService,dashboardBotService,dashboardService,faqDetailService,faqService,fbLikeService,fbCategoryService,fbEventService,fbUserService,fbUserTypeService,lookupService,mailService,planService,productCategoryService,productNodeService,productService,productsService,profileFunctionService,profileModuleService,profileService,userPrivilegeService,storeService,sysAreaService,sysCityService,sysConfigurationService,sysFaqCategoryService,actionService,excelColumnService,feedKeyService,hashTagService,roleEngineService,roleIgnoreWordService,roleTermService,sequenceService,tweepsService,tweetService,wordService,userAccountService,userAuthService,userService,smsSender,preLoadData,DBConfig,filterDao,genericDAO,filterService,validation,fileExtensionValidator,fileSizeValidator,patternValidator,requiredValidator,uniqueValidator,mailSenderTelephoenic,mailSender,org.springframework.scheduling.annotation.SchedulingConfiguration,org.springframework.context.annotation.internalScheduledAnnotationProcessor,org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration,org.springframework.transaction.config.internalTransactionAdvisor,transactionAttributeSource,transactionInterceptor,org.springframework.transaction.config.internalTransactionalEventListenerFactory,propertySourcesPlaceholderConfigurer,smsConfigWrapper,tcDataSource,tcEntityManagerFactoryBean,tcTrxManger,persistenceExceptionTranslationPostProcessor,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy
14:01:08.903 [main] DEBUG o.s.b.f.s.DisposableBeanAdapter - Invoking destroy method 'close' on bean with name 'tcDataSource'
14:01:08.903 [main] DEBUG c.m.v.c.m.ActiveManagementCoordinator - MBean: com.mchange.v2.c3p0:type=PooledDataSource,identityToken=1hge16s9ur8q2q0krsro1|4087c7fc,name=1hge16s9ur8q2q0krsro1|4087c7fc unregistered.
14:01:08.904 [main] DEBUG c.m.v.c.m.ActiveManagementCoordinator - C3P0Registry mbean unregistered.
14:01:08.904 [main] DEBUG o.s.b.f.s.DisposableBeanAdapter - Invoking destroy() on bean with name 'org.springframework.context.annotation.internalScheduledAnnotationProcessor'
14:01:08.905 [main] ERROR o.s.test.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener@c33b74f] to prepare test instance [com.tc.gs.dao.impl.TestNlpEntitySKeyowrdSynonymDaoImpl@4cc12db2]
java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125) ~[spring-test-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:107) ~[spring-test-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190) ~[spring-test-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132) ~[spring-test-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:242) ~[spring-test-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:97) [spring-test-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$invokeTestInstancePostProcessors$3(ClassTestDescriptor.java:215) [junit-jupiter-engine-5.1.0.jar:5.1.0]
    at org.junit.jupiter.engine.descriptor.JupiterTestDescriptor.executeAndMaskThrowable(JupiterTestDescriptor.java:141) ~[junit-jupiter-engine-5.1.0.jar:5.1.0]
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$invokeTestInstancePostProcessors$4(ClassTestDescriptor.java:215) [junit-jupiter-engine-5.1.0.jar:5.1.0]
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193) ~[na:1.8.0_151]
    at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175) ~[na:1.8.0_151]
    at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1380) ~[na:1.8.0_151]
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481) ~[na:1.8.0_151]
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471) ~[na:1.8.0_151]
    at java.util.stream.StreamSpliterators$WrappingSpliterator.forEachRemaining(StreamSpliterators.java:312) ~[na:1.8.0_151]
    at java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:743) ~[na:1.8.0_151]
    at java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:742) ~[na:1.8.0_151]
    at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:580) ~[na:1.8.0_151]
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.invokeTestInstancePostProcessors(ClassTestDescriptor.java:214) [junit-jupiter-engine-5.1.0.jar:5.1.0]
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.instantiateAndPostProcessTestInstance(ClassTestDescriptor.java:196) [junit-jupiter-engine-5.1.0.jar:5.1.0]
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$testInstanceProvider$0(ClassTestDescriptor.java:185) [junit-jupiter-engine-5.1.0.jar:5.1.0]
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$testInstanceProvider$1(ClassTestDescriptor.java:189) [junit-jupiter-engine-5.1.0.jar:5.1.0]
    at java.util.Optional.orElseGet(Optional.java:267) ~[na:1.8.0_151]

                                        .
                                        .
                                        .

    at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174) ~[na:1.8.0_151]
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:1.8.0_151]
    at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418) ~[na:1.8.0_151]
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:120) ~[junit-platform-engine-1.1.0.jar:1.1.0]
    at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66) ~[junit-platform-engine-1.1.0.jar:1.1.0]
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108) ~[junit-platform-engine-1.1.0.jar:1.1.0]
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79) ~[junit-platform-engine-1.1.0.jar:1.1.0]
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:55) ~[junit-platform-engine-1.1.0.jar:1.1.0]
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:43) ~[junit-platform-engine-1.1.0.jar:1.1.0]
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:170) ~[junit-platform-launcher-1.1.0.jar:1.1.0]

                                        .
                                        .

    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) ~[.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538) ~[.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760) ~[.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460) ~[.cp/:na]
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206) ~[.cp/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tcEntityManagerFactoryBean' defined in class path resource [com/tc/gs/config/DBConfig.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: tc-JPA] Unable to build Hibernate SessionFactory
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1710) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:583) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]

                                        .
                                        .
                                        .

    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99) ~[spring-test-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117) ~[spring-test-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    ... 68 common frames omitted
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: tc-JPA] Unable to build Hibernate SessionFactory
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:970) ~[hibernate-core-5.2.16.Final.jar:5.2.16.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:895) ~[hibernate-core-5.2.16.Final.jar:5.2.16.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:57) ~[spring-orm-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:388) ~[spring-orm-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:377) ~[spring-orm-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1769) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1706) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    ... 81 common frames omitted
Caused by: org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags: [com.tc.gs.model.fb.FBUser.fbEvents, com.tc.gs.model.fb.FBUser.fbUserLikes, com.tc.gs.model.fb.FBUser.fbFriends, com.tc.gs.model.fb.FBUser.fbUserTypes]
    at org.hibernate.loader.plan.exec.internal.AbstractLoadQueryDetails.generate(AbstractLoadQueryDetails.java:178) ~[hibernate-core-5.2.16.Final.jar:5.2.16.Final]
    at org.hibernate.loader.plan.exec.internal.EntityLoadQueryDetails.<init>(EntityLoadQueryDetails.java:90) ~[hibernate-core-5.2.16.Final.jar:5.2.16.Final]
    at org.hibernate.loader.plan.exec.internal.BatchingLoadQueryDetailsFactory.makeEntityLoadQueryDetails(BatchingLoadQueryDetailsFactory.java:61) ~[hibernate-core-5.2.16.Final.jar:5.2.16.Final]

                                    .
                                    .
                                    .

    at org.hibernate.metamodel.internal.MetamodelImpl.initialize(MetamodelImpl.java:203) ~[hibernate-core-5.2.16.Final.jar:5.2.16.Final]
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:300) ~[hibernate-core-5.2.16.Final.jar:5.2.16.Final]
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:460) ~[hibernate-core-5.2.16.Final.jar:5.2.16.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:892) ~[hibernate-core-5.2.16.Final.jar:5.2.16.Final]
    ... 88 common frames omitted
14:01:08.909 [main] DEBUG o.s.t.c.s.AbstractDirtiesContextTestExecutionListener - After test class: context [DefaultTestContext@61df66b6 testClass = TestNlpEntitySKeyowrdSynonymDaoImpl, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@50eac852 testClass = TestNlpEntitySKeyowrdSynonymDaoImpl, locations = '{}', classes = '{class com.tc.gs.config.NlpMainConfig}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[org.springframework.test.context.web.socket.MockServerContainerContextCustomizer@4690b489], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.test.context.web.AnnotationConfigWebContextLoader', parent = [null]], attributes = map[[empty]]], class annotated with @DirtiesContext [false] with mode [null].
14:01:08.917 [Resource Destroyer in BasicResourcePool.close()] DEBUG c.m.v.resourcepool.BasicResourcePool - Preparing to destroy resource: com.mchange.v2.c3p0.impl.NewPooledConnection@2ecac883
M.R.M
  • 540
  • 1
  • 13
  • 30

1 Answers1

0

These lines:

@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes=DBConfig.class)

mean that your test will start the Spring context defined by DBConfig before running any of the actual tests in the class. If starting the context somehow fails, no tests will run.

This line:

 jpaProperties.setProperty("hibernate.hbm2ddl.auto", "update");

Will make Hibernate try to update your database to the current schema found in the Hibernate mappings. If the database you are connecting to is far from the schema definition, it will result in loads of queries being run (to create tables, etc).

I will need to see an actual exception/error message to pinpoint exactly what's wrong, but I'm fairly certain it's within what's mentioned above.

Tobb
  • 11,850
  • 6
  • 52
  • 77
  • I tried to comment the hibernate update statement but didn't work. I edited my question and added a snapshot of the generated things when I try any test – M.R.M Mar 26 '18 at 12:02
  • It looks like initialization of Hibernate, it looks OK. But there is no actual error message there, could you show that? – Tobb Mar 26 '18 at 12:08
  • I modified the snapshot to show the error .. however, my real problem is why in the first place these queries are being generated automatically and executed every time I run any DAO test – M.R.M Mar 26 '18 at 12:41
  • Note: I couldn't include a full snapshot for a test plan for an entity with the exception .. I know the cause of exception (Multiple bags) .. but the problem is that this is one of the auto generated queries – M.R.M Mar 26 '18 at 12:43