Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type - spring-boot

I am trying to create JPA repository with Driver class, but getting "Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type" Please find below code.
package org.codejudge.sb.config;
#Configuration
public class WebConfiguration {
#Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
};
}
#Bean
public JpaTransactionManager transactionManager(EntityManagerFactory emf, DataSource dataSource){
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
transactionManager.setDataSource(dataSource);
return transactionManager;
}
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/db?useSSL=false&serverTimezone=UTC&useLegacyDatetimeCode=false");
dataSource.setUsername("root");
dataSource.setPassword("admin");
return dataSource;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource);
// em.setPersistenceUnitName("org.hibernate.jpa.HibernatePersistenceProvider");
em.setPackagesToScan("data");
em.setJpaVendorAdapter(jpaVendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
return properties;
}
#Bean
public JpaVendorAdapter jpaVendorAdapter(){
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
//adapter.setDatabase();
adapter.setShowSql(true);
adapter.setGenerateDdl(false);
adapter.setDatabasePlatform("org.hibernate.dialect.HSQLDialect");
return adapter;
}
}
package org.codejudge.sb.model;
#Data
#AllArgsConstructor
#NoArgsConstructor
#DynamicUpdate
//#Table(name = "driver")
#Entity
public class Driver {
#Id
#GeneratedValue
#Column(name = "id")
private Integer id;
#Column(name = "name", nullable = false)
private String name;
#Column(name = "email", unique = true, nullable = false)
private String email;
#Digits(integer = 10, fraction = 2)
#Column(name = "phone_number", unique = true, nullable = false)
private Integer phoneNumber;
#Column(name = "license_number", unique = true, nullable = false)
private String licenseNumber;
#Column(name = "car_number", unique = true, nullable = false)
private String carNumber;
}
package org.codejudge.sb.repository;
import org.codejudge.sb.model.Driver;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface DriverRepo extends JpaRepository<Driver, Integer> {
}
package org.codejudge.sb;
#SpringBootApplication
#ComponentScan(basePackages = {"org.codejudge.sb", "org.codejudge.sb.model"})
#EnableJpaRepositories(basePackages={"org.codejudge.sb.repository"})
#EntityScan(basePackages = {"org.codejudge.sb.model"})
#EnableAutoConfiguration
#Slf4j
public class Application {
public static void main(String[] args) {
log.info("Starting Application...");
SpringApplication.run(Application.class, args);
}
}
ERROR LOG TRACE
2021-01-21 19:12:11.103 INFO 54796 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2021-01-21 19:12:11.323 WARN 54796 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'driverRepo': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class org.codejudge.sb.model.Driver
2021-01-21 19:12:11.324 INFO 54796 --- [ main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2021-01-21 19:12:11.324 INFO 54796 --- [ main] .SchemaDropperImpl$DelayedDropActionImpl : HHH000477: Starting delayed evictData of schema as part of SessionFactory shut-down'
2021-01-21 19:12:11.330 INFO 54796 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2021-01-21 19:12:11.345 INFO 54796 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-01-21 19:12:11.352 ERROR 54796 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'driverRepo': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class org.codejudge.sb.model.Driver
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1778) ~[spring-beans-5.1.8.RELEASE.jar!/:5.1.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593) ~[spring-beans-5.1.8.RELEASE.jar!/:5.1.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.8.RELEASE.jar!/:5.1.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.8.RELEASE.jar!/:5.1.8.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.8.RELEASE.jar!/:5.1.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.8.RELEASE.jar!/:5.1.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.8.RELEASE.jar!/:5.1.8.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:826) ~[spring-beans-5.1.8.RELEASE.jar!/:5.1.8.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877) ~[spring-context-5.1.8.RELEASE.jar!/:5.1.8.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.1.8.RELEASE.jar!/:5.1.8.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.1.6.RELEASE.jar!/:2.1.6.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:742) ~[spring-boot-2.1.6.RELEASE.jar!/:2.1.6.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:389) ~[spring-boot-2.1.6.RELEASE.jar!/:2.1.6.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:311) ~[spring-boot-2.1.6.RELEASE.jar!/:2.1.6.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1213) ~[spring-boot-2.1.6.RELEASE.jar!/:2.1.6.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1202) ~[spring-boot-2.1.6.RELEASE.jar!/:2.1.6.RELEASE]
at org.codejudge.sb.Application.main(Application.java:21) ~[classes!/:0.0.1-SNAPSHOT]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:567) ~[na:na]
at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:47) ~[spring-boot-in-docker.jar:0.0.1-SNAPSHOT]
at org.springframework.boot.loader.Launcher.launch(Launcher.java:86) ~[spring-boot-in-docker.jar:0.0.1-SNAPSHOT]
at org.springframework.boot.loader.Launcher.launch(Launcher.java:50) ~[spring-boot-in-docker.jar:0.0.1-SNAPSHOT]
at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:51) ~[spring-boot-in-docker.jar:0.0.1-SNAPSHOT]
Caused by: java.lang.IllegalArgumentException: Not a managed type: class org.codejudge.sb.model.Driver
at org.hibernate.metamodel.internal.MetamodelImpl.managedType(MetamodelImpl.java:552) ~[hibernate-core-5.3.10.Final.jar!/:5.3.10.Final]
at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.<init>(JpaMetamodelEntityInformation.java:74) ~[spring-data-jpa-2.1.9.RELEASE.jar!/:2.1.9.RELEASE]
at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getEntityInformation(JpaEntityInformationSupport.java:66) ~[spring-data-jpa-2.1.9.RELEASE.jar

Related

How to fix The injection point has the following annotations: - #org.springframework.beans.factory.annotation.Autowired(required=true)

I am new to spring boot, i am getting this error since a while, unfortunately can't fix it. I am googling since then but still not find what i did wrong. Find below my code:
Entity
#Entity
#Table(name="compagnie")
public class Compagnie implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id_compagnie")
private int idCompagnie;
#Column(name="nom_compagnie")
private String nomCompagnie;
#Column(name="nom_court_compagnie")
private String nomCourtCompagnie;
#Column(name="logo_compagnie")
private String logoCompagnie;
public int getIdCompagnie() {
return idCompagnie;
}
public void setIdCompagnie(int idCompagnie) {
this.idCompagnie = idCompagnie;
}
public String getNomCompagnie() {
return nomCompagnie;
}
public void setNomCompagnie(String nomCompagnie) {
this.nomCompagnie = nomCompagnie;
}
public String getNomCourtCompagnie() {
return nomCourtCompagnie;
}
public void setNomCourtCompagnie(String nomCourtCompagnie) {
this.nomCourtCompagnie = nomCourtCompagnie;
}
public String getLogoCompagnie() {
return logoCompagnie;
}
public void setLogoCompagnie(String logoCompagnie) {
this.logoCompagnie = logoCompagnie;
}
}
Dao
#Component
public interface CompagnieDao extends JpaRepository<Compagnie, Integer> {
#Query("select c from Compagnie c where idCompagnie != :idCompagnie")
List<Compagnie> getAllCompagnieNonAssurAstuce(#Param("idCompagnie") int idCompagnie);
#Query("select c from Compagnie c where nomCompagnie = :nomCompagnie")
Compagnie getCompagnieByNom(#Param("nomCompagnie") String nomCompagnie);
}
Main
#SpringBootApplication
public class Application implements CommandLineRunner {
#Autowired
private CompagnieDao compagnieDao;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Override
public void run(String... args) throws Exception {
System.out.println("tic toc");
List<Compagnie> compagnies = compagnieDao.findAll();
compagnies.forEach(compagnie -> System.out.println(compagnie.getNomCompagnie()));
}
}
Error
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-12-30 11:54:42.817 ERROR 10136 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter :
APPLICATION FAILED TO START
Description:
Field compagnieDao in com.assurastuce.Application required a bean of type 'com.dao.CompagnieDao' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.dao.CompagnieDao' in your configuration.
Thank you for your help
I changed the spring version from 2.4.1 to 2.3.4.RELEASE and now getting this error
java.lang.IllegalStateException: Failed to execute CommandLineRunner
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:798) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:779) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:322) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at com.assurastuce.Application.main(Application.java:20) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_271]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_271]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_271]
at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_271]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.3.4.RELEASE.jar:2.3.4.RELEASE]
Caused by: java.lang.NullPointerException: null
at com.assurastuce.Application.run(Application.java:26) [classes/:na]
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:795) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
... 10 common frames omitted
2020-12-31 08:26:45.401 INFO 11520 --- [ restartedMain] o.e.jetty.server.AbstractConnector : Stopped ServerConnector#19b4bd36{HTTP/1.1, (http/1.1)}{0.0.0.0:8080}
2020-12-31 08:26:45.401 INFO 11520 --- [ restartedMain] org.eclipse.jetty.server.session : node0 Stopped scavenging
2020-12-31 08:26:45.405 INFO 11520 --- [ restartedMain] o.e.j.s.h.ContextHandler.application : Destroying Spring FrameworkServlet 'dispatcherServlet'
2020-12-31 08:26:45.407 INFO 11520 --- [ restartedMain] o.e.jetty.server.handler.ContextHandler : Stopped o.s.b.w.e.j.JettyEmbeddedWebAppContext#4bfa6d74{application,/,[file:///C:/Users/LAKATAN%20Adebayo%20G.%20W/AppData/Local/Temp/jetty-docbase.8010039629830210588.8080/],UNAVAILABLE}
2020-12-31 08:26:45.430 INFO 11520 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2020-12-31 08:26:45.434 INFO 11520 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
2020-12-31 08:26:45.438 INFO 11520 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2020-12-31 08:26:45.465 INFO 11520 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
Probably the folder structure is not correct.
Could you please add this line of code and check if this works for you.
#SpringBootApplication
#ComponentScan(value = "com.dao.CompagnieDao")
public class Application implements CommandLineRunner {
Also, I think it would be more correct if you replace the #Component with the #Repository annotation.
#Repository
public interface CompagnieDao extends JpaRepository<Compagnie, Integer> {

Pagination and criteria for spring feign client

I'm stuck on setting up a feignclient of one of my microservices.
I use criteria (for filtering) and pagination.
On one of my microservices I have a service rest and the other use a feignclient to request it.
AccountCriteria (criteria interface from jhipster)
public class AccountCriteria implements Serializable, Criteria {
private LongFilter id;
private StringFilter user;
private LongFilter bankWebId;
private LongFilter bankApiId;
private LongFilter deactivationReasonId;
public AccountCriteria() {
}
public AccountCriteria(AccountCriteria other) {
this.id = other.id == null ? null : other.id.copy();
this.user = other.user == null ? null : other.user.copy();
this.bankWebId = other.bankWebId == null ? null : other.bankWebId.copy();
this.bankApiId = other.bankApiId == null ? null : other.bankApiId.copy();
this.deactivationReasonId = other.deactivationReasonId == null ? null : other.deactivationReasonId.copy();
}
#Override
public Criteria copy() {
return new AccountCriteria(this);
}
}
AccountIdentifierResource (Rest resource)
#RestController
#RequestMapping(value = "/api", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class AccountIdentifierResource {
log.debug("REST request to get AccountIdentifiers by criteria: {}", criteria);
Page<AccountIdentifier> page = accountIdentifierQueryService.findByCriteria(criteria, pageable);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(uriBuilder.queryParams(queryParams), page);
return ResponseEntity.ok().headers(headers).body(page.getContent());
}
IdentityProviderFeignClient (feign client)
#AuthorizedFeignClient(name = "identityprovider")
public interface IdentityProviderFeignClient {
#GetMapping("/api/account-identifiers")
List<AccountIdentifier> getAllAccountIdentifiers(AccountCriteria criteria,
Pageable pageable, #RequestParam("queryParams") MultiValueMap<String, String> queryParams, UriComponentsBuilder uriBuilder);
}
IdentityProviderService (the service interface)
public interface IdentityProviderService {
List<AccountIdentifier> getAllAccountIdentifiers(AccountCriteria criteria, Pageable pageable, MultiValueMap<String, String> queryParams, UriComponentsBuilder uriBuilder);
}
IdentityProviderServiceImpl (the service implementation)
#Service
public class IdentityProviderServiceImpl implements IdentityProviderService {
private final Logger log =
LoggerFactory.getLogger(IdentityProviderServiceImpl.class);
private final IdentityProviderFeignClient identityProviderFeignClient;
public IdentityProviderServiceImpl(IdentityProviderFeignClient identityProviderFeignClient) {
this.identityProviderFeignClient = identityProviderFeignClient;
}
#Override
public List<AccountIdentifier> getAllAccountIdentifiers(AccountCriteria criteria, Pageable pageable, MultiValueMap<String, String> queryParams, UriComponentsBuilder uriBuilder) {
log.debug("Request to get all AccountIdentifier from IdentityProvider with criteria : {}", criteria);
return this.identityProviderFeignClient.getAllAccountIdentifiers(criteria, pageable, queryParams, uriBuilder);
}
}
FeignConfiguration
#Configuration
#EnableFeignClients(basePackages = "com.soft.jobstrategy")
#Import(FeignClientsConfiguration.class)
public class FeignConfiguration {
/**
* Set the Feign specific log level to log client REST requests.
*/
#Bean
feign.Logger.Level feignLoggerLevel() {
return feign.Logger.Level.BASIC;
}
}
For now it's impossible to run the application.
I get the following traceback:
[INFO] Running com.soft.jobstrategy.config.timezone.HibernateTimeZoneIT
:: JHipster ? :: Running Spring Boot 2.1.6.RELEASE ::
:: https://www.jhipster.tech ::
2019-10-04 16:07:44.465 WARN 2736 --- [ main] kafka.server.BrokerMetadataCheckpoint : No meta.properties file under dir C:\Users\maktouf\AppData\Local\Temp\kafka-6358187594718130765\meta.properties
2019-10-04 16:07:45.097 WARN 2736 --- [ main] kafka.server.BrokerMetadataCheckpoint : No meta.properties file under dir C:\Users\maktouf\AppData\Local\Temp\kafka-6358187594718130765\meta.properties
2019-10-04 16:07:45.343 INFO 2736 --- [ main] c.b.j.c.timezone.HibernateTimeZoneIT : No active profile set, falling back to default profiles: default
2019-10-04 16:07:49.628 WARN 2736 --- [ main] c.b.j.config.CacheConfiguration : No discovery service is set up, Hazelcast cannot create a cluster.
2019-10-04 16:07:51.266 WARN 2736 --- [ main] com.hazelcast.instance.Node : [192.168.1.21]:5701 [dev] [3.11.4] No join method is enabled! Starting standalone.
2019-10-04 16:07:57.509 WARN 2736 --- [ main] c.n.c.sources.URLConfigurationSource : No URLs will be polled as dynamic configuration sources.
2019-10-04 16:07:57.918 WARN 2736 --- [ main] o.s.w.c.s.GenericWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creatin
g bean with name 'identityProviderServiceImpl' defined in file [C:\developpement\javaenv\workspace\job_strategy\target\classes\com\soft\jobstrategy\service\impl\IdentityProviderServiceImpl.class]: Unsatisfied dependency expressed through constructor par
ameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.soft.jobstrategy.client.IdentityProviderFeignClient': FactoryBean threw exception on object creation; nested exception is java.lang
.IllegalStateException: Method has too many Body parameters: public abstract java.util.List com.soft.jobstrategy.client.IdentityProviderFeignClient.getAllAccountIdentifiers(com.soft.jobstrategy.service.dto.AccountCriteria,org.springframework.dat
a.domain.Pageable,org.springframework.util.MultiValueMap,org.springframework.web.util.UriComponentsBuilder)
2019-10-04 16:07:57.965 INFO 2736 --- [ main] c.b.j.config.CacheConfiguration : Closing Cache Manager
2019-10-04 16:08:01.744 ERROR 2736 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'identityProviderServiceImpl' defined in file [C:\developpement\javaenv\workspace\job_strategy\target\classes\com\soft\jobstrategy\service\impl\IdentityProvi
derServiceImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.soft.jobstrategy.client.IdentityProviderFeignClient'
: FactoryBean threw exception on object creation; nested exception is java.lang.IllegalStateException: Method has too many Body parameters: public abstract java.util.List com.soft.jobstrategy.client.IdentityProviderFeignClient.getAllAccountIdentifiers(c
om.soft.jobstrategy.service.dto.AccountCriteria,org.springframework.data.domain.Pageable,org.springframework.util.MultiValueMap,org.springframework.web.util.UriComponentsBuilder)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:769)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:218)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1341)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1187)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:845)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:742)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:389)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:311)
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:119)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108)
at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190)
at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246)
at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:97)
at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$invokeTestInstancePostProcessors$5(ClassTestDescriptor.java:349)
at org.junit.jupiter.engine.descriptor.JupiterTestDescriptor.executeAndMaskThrowable(JupiterTestDescriptor.java:215)
at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$invokeTestInstancePostProcessors$6(ClassTestDescriptor.java:349)
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175)
at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.StreamSpliterators$WrappingSpliterator.forEachRemaining(StreamSpliterators.java:312)
at java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:743)
at java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:742)
at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:580)
at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.invokeTestInstancePostProcessors(ClassTestDescriptor.java:348)
at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.instantiateAndPostProcessTestInstance(ClassTestDescriptor.java:270)
at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$testInstanceProvider$2(ClassTestDescriptor.java:259)
at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$testInstanceProvider$3(ClassTestDescriptor.java:263)
at java.util.Optional.orElseGet(Optional.java:267)
at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$testInstanceProvider$4(ClassTestDescriptor.java:262)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:82)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:59)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$prepare$0(NodeTestTask.java:83)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.prepare(NodeTestTask.java:83)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:69)
at java.util.ArrayList.forEach(ArrayList.java:1257)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$4(NodeTestTask.java:112)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:98)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:74)
at java.util.ArrayList.forEach(ArrayList.java:1257)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$4(NodeTestTask.java:112)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:98)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:74)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:220)
at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:188)
at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:202)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:181)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
at org.apache.maven.surefire.junitplatform.JUnitPlatformProvider.invokeAllTests(JUnitPlatformProvider.java:150)
at org.apache.maven.surefire.junitplatform.JUnitPlatformProvider.invoke(JUnitPlatformProvider.java:124)
at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:384)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:345)
at org.apache.maven.surefire.booter.ForkedBooter.execute(ForkedBooter.java:126)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:418)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.soft.jobstrategy.client.IdentityProviderFeignClient': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalStateExcept
ion: Method has too many Body parameters: public abstract java.util.List com.soft.jobstrategy.client.IdentityProviderFeignClient.getAllAccountIdentifiers(com.soft.jobstrategy.service.dto.AccountCriteria,org.springframework.data.domain.Pageable,o
rg.springframework.util.MultiValueMap,org.springframework.web.util.UriComponentsBuilder)
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:178)
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:101)
at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanInstance(AbstractBeanFactory.java:1674)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.getObjectForBeanInstance(AbstractAutowireCapableBeanFactory.java:1249)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:257)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.addCandidateEntry(DefaultListableBeanFactory.java:1474)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1431)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1214)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1171)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:857)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:760)
... 73 common frames omitted
Thanks everyone for your help.
Edit :
Finally the answer of Murilo Prado resolved the issue.
I also edited the code of the feign client :
IdentityProviderFeignClient (feign client)
#AuthorizedFeignClient(name = "identityprovider")
public interface IdentityProviderFeignClient {
#GetMapping("/api/account-identifiers")
List<AccountIdentifier> getAllAccountIdentifiers(#QueryParam("search") String criteria,
Pageable pageable, #RequestParam("queryParams") MultiValueMap<String, String> queryParams);
}
Try this
public class FeignConfig {
#Autowired
private ObjectFactory<HttpMessageConverters> messageConverters;
#Bean
#ConditionalOnMissingBean
public Decoder feignDecoder() {
return new OptionalDecoder(new ResponseEntityDecoder(new SpringDecoder(this.messageConverters)));
}
#Bean
#ConditionalOnMissingBean
public Encoder feignEncoder() {
return new SpringFormEncoder(new SpringEncoder(messageConverters));
}
}

Spring boot JUNIT test fails for service test

I am trying to perform a Junit 4 test from a service in a spring boot application and I keep getting an entityManagerFactory its with init.
I also want connect using my application.properties file, but it wants to connect using the embedded hsqldb.
Can someone point me in the right direction?
Below is the pertinent code:
APPLICATION.PROPERTIES:
# ===============================
# = DATA SOURCE
# ===============================
# Set here configurations for the database connection
# Connection url for the database "netgloo_blog"
spring.datasource.url = jdbc:mysql://localhost:3306/finra?useSSL=false
# Username and password
spring.datasource.username = finra
spring.datasource.password = finra
# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
# ===============================
# = JPA / HIBERNATE
# ===============================
# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager).
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update): with "update" the database
# schema will be automatically updated accordingly to java entities found in
# the project
spring.jpa.hibernate.ddl-auto = update
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# Allows Hibernate to generate SQL optimized for a particular DBMS
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
MAIN:
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#SpringBootApplication
#EnableTransactionManagement
#ComponentScan(basePackages = {"com.example"})
#EntityScan(basePackages = {"com.example.entity"})
//#ImportResource("classpath:application.properties")
//#Configuration
//#EnableAutoConfiguration
//#ComponentScan
//#EnableScheduling
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
ENTITY:
package com.example.entity;
import java.io.Serializable;
public interface UserInterface extends Serializable{
public long getId();
public long setId(long value);
public String getEMail();
public void setEmail( String value );
public String getName();
public void setName(String value);
}
package com.example.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
//import javax.persistence.Table;
import javax.validation.constraints.NotNull;
#Entity
//#Table(name = "users")
#Table(
uniqueConstraints = {
#UniqueConstraint(columnNames = {"email"})
}
)
public class User implements UserInterface {
/**
*
*/
private static final long serialVersionUID = -507606192667894785L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#NotNull
private String email;
#NotNull
private String name;
#Override
public long getId() {
// TODO Auto-generated method stub
return id;
}
#Override
public long setId(long value) {
// TODO Auto-generated method stub
return id = value;
}
#Override
public String getEMail() {
// TODO Auto-generated method stub
return email;
}
#Override
public void setEmail(String value) {
// TODO Auto-generated method stub
email = value;
}
#Override
public String getName() {
// TODO Auto-generated method stub
return name;
}
#Override
public void setName(String value) {
// TODO Auto-generated method stub
name = value;
}
}
DAO/REPOSITORY:
package com.example.dao;
import javax.transaction.Transactional;
import org.springframework.data.repository.CrudRepository;
import com.example.entity.User;
#Transactional
public interface UserDao extends CrudRepository<User, Long> {
public User findByEmail( String email );
public void setUserDao(UserDao userDao);
}
SERVICE:
package com.example.service;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.dao.UserDao;
import com.example.entity.User;
#Service("userService")
public class UserService {
private final Logger log = Logger.getLogger (this.getClass());
#Autowired UserDao userDao;
public void setUserDao( UserDao userDao ){
this.userDao = userDao;
}
public List<User> findAll(){
return (List<User>) userDao.findAll();
}
public User findOne( long id ){
return userDao.findOne(id);
}
public User getByEmail(String email) throws Exception{
String userId = null;
User user = null;
try{
user = userDao.findByEmail(email);
userId = String.valueOf(user.getId());
}catch(Exception e){
log.error("User not found");
e.printStackTrace();
throw new Exception(e);
}
log.info("The user id is: " + userId);
return user;
}
public User create( String email, String name ){
User user = null;
try{
user = new User();
user.setEmail(email);
user.setName(name);
userDao.save(user);
}catch( Exception e ){
log.error("Error creating the user: " + e.getMessage());
}
log.info("User id: " + user.getId() + " saved.");
return user;
}
public User updateUser(long id, String email, String name ){
User user = null;
try{
user = userDao.findOne(id);
user.setEmail(email);
user.setName(name);
userDao.save(user);
}catch( Exception e ){
log.error("Error updating the user: " + e.getMessage());
}
return user;
}
public User delete( long id ) throws Exception{
User user = null;
user = userDao.findOne(id);
userDao.delete(user);
return user;
}
}
TEST:
/**
*
*/
package com.example.service;
import static org.junit.Assert.*;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.Assert;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import com.example.DemoApplication;
import com.example.dao.UserDao;
import com.example.entity.User;
/**
* #author denisputnam
*
*/
#RunWith(SpringRunner.class)
#SpringBootTest(classes = DemoApplication.class)
//#SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
//#SpringBootConfiguration
#DataJpaTest
#Transactional
public class UserServiceTest {
#Autowired
private UserDao userDao;
private UserService userService;
// #Autowired
// public void setUserService( UserService userService ){
// this.userService = userService;
// }
/**
* #throws java.lang.Exception
*/
#Before
public void setUp() throws Exception {
// userDao = EasyMock.createMock(UserDao.class);
//
userService = new UserService();
userService.setUserDao(userDao);
// testEntityManager = new TestEntityManager(emf);
// this.testContextManager = new TestContextManager(getClass());
// this.testContextManager.prepareTestInstance(this);
}
/**
* Test method for {#link com.example.service.UserService#findAll()}.
*/
#Test
public void testFindAll() {
// EasyMock.reset(userDao);
// final List<User> users = new ArrayList<User>();
// EasyMock.expect(userDao.findAll()).andReturn(users);
// EasyMock.replay(userDao);
// EasyMock.verify(userDao);
// Assert.notEmpty(users, "findAll() failed.");
// User user = new User();
// user.setEmail("bogus#bogus.com");
// user.setName("bogus");
// UserService userService = new UserService();
// this.setUserService(userService);
User user = this.userService.create("bogus#bogus.com", "bogus");
final List<User> users = (List<User>) this.userDao.findAll();
Assert.notEmpty(users, "Found no users.");
}
/**
* Test method for {#link com.example.service.UserService#findOne(long)}.
*/
#Test
public void testFindOne() {
fail("Not yet implemented");
}
/**
* Test method for {#link com.example.service.UserService#getByEmail(java.lang.String)}.
*/
#Test
public void testGetByEmail() {
fail("Not yet implemented");
}
/**
* Test method for {#link com.example.service.UserService#create(java.lang.String, java.lang.String)}.
*/
#Test
public void testCreate() {
fail("Not yet implemented");
}
/**
* Test method for {#link com.example.service.UserService#updateUser(long, java.lang.String, java.lang.String)}.
*/
#Test
public void testUpdateUser() {
fail("Not yet implemented");
}
/**
* Test method for {#link com.example.service.UserService#delete(long)}.
*/
#Test
public void testDelete() {
fail("Not yet implemented");
}
}
SHOULD HAVE INCLUDED THIS:
2017-04-02 16:30:00.627 INFO 93661 --- [ main] com.example.service.UserServiceTest : Starting UserServiceTest on Deniss-IMAC.home with PID 93661 (started by denisputnam in /Users/denisputnam/git/springboot/demo)
2017-04-02 16:30:00.627 INFO 93661 --- [ main] com.example.service.UserServiceTest : No active profile set, falling back to default profiles: default
2017-04-02 16:30:00.630 INFO 93661 --- [ main] o.s.w.c.s.GenericWebApplicationContext : Refreshing org.springframework.web.context.support.GenericWebApplicationContext#3111631d: startup date [Sun Apr 02 16:30:00 EDT 2017]; root of context hierarchy
2017-04-02 16:30:00.694 INFO 93661 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'userService' with a different definition: replacing [Generic bean: class [com.example.service.UserService]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [/Users/denisputnam/git/springboot/demo/target/classes/com/example/service/UserService.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=userServiceTest.Config; factoryMethodName=userService; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [com/example/service/UserServiceTest$Config.class]]
2017-04-02 16:30:00.705 INFO 93661 --- [ main] beddedDataSourceBeanFactoryPostProcessor : Replacing 'dataSource' DataSource bean with embedded version
2017-04-02 16:30:00.705 INFO 93661 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'dataSource' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Tomcat; factoryMethodName=dataSource; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]] with [Root bean: class [org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration$EmbeddedDataSourceFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
2017-04-02 16:30:00.705 WARN 93661 --- [ main] o.s.c.a.ConfigurationClassPostProcessor : Cannot enhance #Configuration bean definition 'embeddedDataSourceBeanFactoryPostProcessor' since its singleton instance has been created too early. The typical cause is a non-static #Bean method with a BeanDefinitionRegistryPostProcessor return type: Consider declaring such methods as 'static'.
2017-04-02 16:30:00.740 INFO 93661 --- [ main] o.s.j.d.e.EmbeddedDatabaseFactory : Starting embedded database: url='jdbc:hsqldb:mem:77b77b83-0034-41be-ab58-3f5d9490ea80', username='sa'
2017-04-02 16:30:00.805 INFO 93661 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2017-04-02 16:30:00.805 INFO 93661 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2017-04-02 16:30:00.810 INFO 93661 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2017-04-02 16:30:00.825 INFO 93661 --- [ main] org.hibernate.tool.hbm2ddl.SchemaUpdate : HHH000228: Running hbm2ddl schema update
2017-04-02 16:30:00.827 INFO 93661 --- [ main] rmationExtractorJdbcDatabaseMetaDataImpl : HHH000262: Table not found: user
2017-04-02 16:30:00.828 INFO 93661 --- [ main] rmationExtractorJdbcDatabaseMetaDataImpl : HHH000262: Table not found: user
2017-04-02 16:30:00.829 WARN 93661 --- [ main] o.s.w.c.s.GenericWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
2017-04-02 16:30:00.829 INFO 93661 --- [ main] utoConfigurationReportLoggingInitializer :
STACK:
2017-04-02 16:05:44.625 ERROR 92739 --- [ main] o.s.boot.SpringApplication : Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120) [spring-boot-test-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:189) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:131) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191) [spring-test-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) [.cp/:na]
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:459) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) [.cp/:na]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
I found the solution here:
spring boot configuration example

Spring jpa Unable to build Hibernate SessionFactory error while trying to configure datasource

I have a repository of username/passwords which I am trying to configure into spring web security using a customUserDetailsService. My base package is called 'showcase'.
I have a WebSecurityConfiguration as:
#Configuration
#EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
private DataSource datasource;
#Autowired
private CustomUserDetailsService customUserDetailsService;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(datasource)
.and()
.userDetailsService(customUserDetailsService);
// #formatter:on
}
I am trying to configure this datasource as follows:
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(basePackages = {
"showcase"
})
public class DatabaseConfig {
//#Resource
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String PROPERTY_NAME_HIBERNATE_FORMAT_SQL = "hibernate.format_sql";
private static final String PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO = "hibernate.hbm2ddl.auto";
private static final String PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY = "hibernate.ejb.naming_strategy";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
#Bean
public DataSource dataSource(Environment env) {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("java.sql.DriverManager");
dataSource.setUrl("jdbc:mysql://localhost:3306/mutibodb");
dataSource.setUsername("db");
dataSource.setPassword("");
return dataSource;
}
#Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, Environment env) {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource);
entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
entityManagerFactoryBean.setPackagesToScan("showcase");
Properties jpaProperties = new Properties();
jpaProperties.put(PROPERTY_NAME_HIBERNATE_DIALECT,"showcase.MySQLDialect");
jpaProperties.put(PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO,"create-drop");
jpaProperties.put(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY,"org.hibernate.cfg.ImprovedNamingStrategy");
jpaProperties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL,false);
jpaProperties.put(PROPERTY_NAME_HIBERNATE_FORMAT_SQL,true);
entityManagerFactoryBean.setJpaProperties(jpaProperties);
return entityManagerFactoryBean;
}
#Bean
public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
}
The SQLDialect configuration is as follows:
public class MySQLDialect extends MySQL5InnoDBDialect {
#Override
public String getDropSequenceString(String sequenceName) {
return "drop sequence if exists " + sequenceName;
}
#Override
public boolean dropConstraints() {
return false;
}
I get an error which primarily says that: Unable to build Hibernate SessionFactory.
I am new to Spring and must be missing something. I am not using any xml based config and wish to stick to only java config. I can share details of the rest of my code if required.
Update:
Here is my CustomUserDetailsService:
#Service("userDetailsService")
public class CustomUserDetailsService implements UserDetailsService {
#Autowired
AppUserRepository repository;
#Autowired
private UserService userService;
private static final Logger logger = LoggerFactory.getLogger(CustomUserDetailsService.class);
#Override
public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
logger.info("username:"+name);
AppUser u = repository.findByUserName(name);
if (u == null)
throw new UsernameNotFoundException("User details not found with this username: " + name);
String username = u.getUsername();
String password = u.getPassword();
List authList = new ArrayList();
authList.add(new SimpleGrantedAuthority("USER"));
User user = new User(username, password, authList);
return user;
}
The UserService mentioned above saves a user in the AppUserRepository. The AppUser is an entity.
The entire error is:
2014-12-28 12:02:59.555 INFO 5220 --- [ost-startStop-1] org.hibernate.Version : HHH000412: Hibernate Core {4.3.1.Final}
2014-12-28 12:02:59.557 INFO 5220 --- [ost-startStop-1] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2014-12-28 12:02:59.560 INFO 5220 --- [ost-startStop-1] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2014-12-28 12:02:59.722 INFO 5220 --- [ost-startStop-1] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
2014-12-28 12:02:59.753 WARN 5220 --- [ost-startStop-1] o.h.e.jdbc.internal.JdbcServicesImpl : HHH000342: Could not obtain connection to query metadata : No suitable driver found for jdbc:mysql://localhost:3306/mutibodb
2014-12-28 12:02:59.760 INFO 5220 --- [ost-startStop-1] org.hibernate.dialect.Dialect : HHH000400: Using dialect: showcase.MySQLDialect
2014-12-28 12:02:59.767 INFO 5220 --- [ost-startStop-1] o.h.e.jdbc.internal.LobCreatorBuilder : HHH000422: Disabling contextual LOB creation as connection was null
2014-12-28 12:02:59.835 ERROR 5220 --- [cat-startStop-1] org.apache.catalina.core.ContainerBase : A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[]]
at java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.util.concurrent.FutureTask.get(FutureTask.java:192)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:799)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
... 6 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.setFilterChainProxySecurityConfigurer(org.springframework.security.config.annotation.ObjectPostProcessor,java.util.List) throws java.lang.Exception; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'webSecurityConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private showcase.CustomUserDetailsService showcase.WebSecurityConfiguration.customUserDetailsService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDetailsService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: showcase.AppUserRepository showcase.CustomUserDetailsService.repository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'appUserRepository': Cannot create inner bean '(inner bean)#165fa72a' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#165fa72a': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [showcase/DatabaseConfig.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
I had not focused on the hibernate errors before. I guess my hibernate config is wrong. But is there a way of doing this without injecting the datasource? When I did not have the datasource field in the securrity config and was only using auth.userDetailsService(customUserDetailsService), I was getting a No qualifying bean of type [javax.sql.DataSource] is defined error. Trying to fix that lead me to this path.

can I use xml wire with java annotation in spring

I have a class of GenerateKey which is for spring mvc boot. Since it needs to contact database and message queue, so I tried to wire it using xml
#RestController
public class GenerateKey {
final private DriverManagerDataSource dataSource;
final private AmqpTemplate rabbitMQTemplate;
final private String queueName;
public GenerateKey(DriverManagerDataSource dataSource,AmqpTemplate rabbitMQTemplate,String queueName){
this.dataSource=dataSource;
this.rabbitMQTemplate =rabbitMQTemplate;
this.queueName =queueName;
}
#RequestMapping("/key/generate")
public String generateKey(#RequestParam(value = "businesskey") String businesskey, #RequestParam(value = "customer") String customer, Model model) {
JdbcTemplate jdbctemplate = new JdbcTemplate(dataSource);
JSONObject obj = new JSONObject();
obj.put("businesskey", businesskey);
obj.put("customer", customer);
rabbitMQTemplate.convertAndSend(queueName, obj.toString());
System.out.println(businesskey+customer);
return "greeting" + businesskey + customer;
}
}
the xml configurations is as the following and using
#ImportResource( { "rabbit-listener-context.xml" } )
to import it
<bean id="request" class="com.testcom.keyservice.GenerateKey" c:dataSource-ref="dataSource" c:rabbitMQTemplate-ref="keyRequestTemplate" c:queueName="${keyRequestQueueName}"/>
but it complain "No default constructor found" as following:
2014-11-26 21:42:16.095 INFO 17400 --- [ main] utoConfigurationReportLoggingInitializer :
Error starting ApplicationContext. To display the auto-configuration report enabled debug logging (start with --debug)
2014-11-26 21:42:16.097 ERROR 17400 --- [ main] o.s.boot.SpringApplication : Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'generateKey' defined in file [/home/oracle/NetBeansProjects/rabbitmq-native/keyService/build/classes/main/com/testcom/keyservice/GenerateKey.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.testcom.keyservice.GenerateKey]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.testcom.keyservice.GenerateKey.<init>()
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1095)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1040)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:505)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:229)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:725)
Exception in thread "main" at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:762)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicatixt.java:482)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:109)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
Since you are using Spring Boot I assume you have also #ComponentScan active in your application. Because of that you create two instances of GenerateKey class - once because of #RestController annotation, second time in XML. I believe that's not what you want to achieve.
Get rid of XML declaration of request bean representing GeneratorKey class and use only Java based autowiring.
#RestController
public class GenerateKey {
private final DriverManagerDataSource dataSource;
private final AmqpTemplate rabbitMQTemplate;
private final String queueName;
#Autowired
public GenerateKey(#Qualifier("dataSource") DriverManagerDataSource dataSource, #Qualifier("keyRequestTemplate") AmqpTemplate rabbitMQTemplate, #Value("${keyRequestQueueName}") String queueName) {
this.dataSource=dataSource;
this.rabbitMQTemplate =rabbitMQTemplate;
this.queueName =queueName;
}

Resources