Spring boot JUNIT test fails for service test - spring-boot

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

Related

Programmatically register EmbeddedDatabaseAutoConfiguration bean inside BeanDefinitionRegistryPostProcessor to use embedded Postgres

I am registering a bean for EmbeddedDatabaseAutoConfiguration but it is never acted upon.
Is something missing for it to be processed in the same manner as if the annotation was present? I'd like to not have to declare the EmbeddedDatabaseAutoConfiguration annotation on the test class.
The BeanDefinitionRegistryPostProcessor implementation:
import io.zonky.test.db.config.EmbeddedDatabaseAutoConfiguration;
import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
#Configuration
public class MyFactoryPostProcessor implements BeanDefinitionRegistryPostProcessor, PriorityOrdered {
#Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
System.out.println("postProcessBeanDefinitionRegistry before");
try {
registry.getBeanDefinition("io.zonky.test.db.config.EmbeddedDatabaseAutoConfiguration");
} catch (Exception e) {
System.out.println("Annotation missing, try programmatically register ..");
RootBeanDefinition beanDefinition = new RootBeanDefinition(EmbeddedDatabaseAutoConfiguration.class);
beanDefinition.setScope("singleton");
MutablePropertyValues values = new MutablePropertyValues();
values.addPropertyValue("zonky.test.database.provider", "zonky");
beanDefinition.setPropertyValues(values);
registry.registerBeanDefinition("io.zonky.test.db.config.EmbeddedDatabaseAutoConfiguration", beanDefinition);
}
System.out.println("postProcessBeanDefinitionRegistry after");
}
#Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
}
#Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
System.out.println("postProcessBeanFactory before");
beanFactory.getBeanDefinition("io.zonky.test.db.config.EmbeddedDatabaseAutoConfiguration");
System.out.println("postProcessBeanFactory after");
}
}
Current test class:
#ActiveProfiles("test")
#SpringBootTest
// I'd like `AutoConfigureEmbeddedDatabase` to be programmatically enabled for all test classes,
// rather than requiring declarative annotation
// If the annotation is provided, the test works fine
//#AutoConfigureEmbeddedDatabase(provider = AutoConfigureEmbeddedDatabase.DatabaseProvider.ZONKY)
public class ItemServiceTest {
#Autowired private ItemService itemService;
#Test
void test_Create() {
String text = "Initial value: " + new Date();
ItemDTO itemDTO = new ItemDTO();
itemDTO.setText(text);
itemDTO = itemService.create(itemDTO);
// assert something with itemDTO ..
}
}
In the console logs below, EmbeddedDatabaseAutoConfiguration is not acted upon in the programmatic use case. Instead processing assumes a non-embedded db is present and starts initializing.
Console output when annotation is declared on test class:
Finished Spring Data repository scanning in 35 ms. Found 1 JPA repository interfaces. []
postProcessBeanDefinitionRegistry before
Generic bean: class [io.zonky.test.db.config.EmbeddedDatabaseAutoConfiguration]; scope=singleton; abstract=false; lazyInit=null; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null
postProcessBeanDefinitionRegistry after
Replacing 'dataSource' DataSource bean with embedded version []
postProcessBeanFactory before
postProcessBeanFactory after
trationDelegate$BeanPostProcessorChecker : Bean 'io.zonky.test.db.config.EmbeddedDatabaseAutoConfiguration' of type [io.zonky.test.db.config.EmbeddedDatabaseAutoConfiguration$$EnhancerBySpringCGLIB$$c4933b50] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) []
o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default] []
org.hibernate.Version : HHH000412: Hibernate ORM core version 5.6.14.Final []
o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final} []
i.z.t.d.p.embedded.EmbeddedPostgres : Detected a Darwin aarch64 system []
Console output when annotation is not declared on test class and programatically trying to create the Spring bean:
Finished Spring Data repository scanning in 31 ms. Found 1 JPA repository interfaces. []
postProcessBeanDefinitionRegistry before
postProcessBeanDefinitionRegistry after
o.s.c.a.ConfigurationClassPostProcessor : Cannot enhance #Configuration bean definition 'myFactoryPostProcessor' 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'. []
postProcessBeanFactory before
postProcessBeanFactory after
o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default] []
org.hibernate.Version : HHH000412: Hibernate ORM core version 5.6.14.Final []
o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final} []
com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting... []
com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Exception during pool initialization. []
Dependencies in build.gradle.kts:
implementation(platform(org.springframework.boot.gradle.plugin.SpringBootPlugin.BOM_COORDINATES))
implementation("org.springframework.boot:spring-boot-starter")
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("org.springframework.boot:spring-boot-starter-validation")
implementation("org.springframework.boot:spring-boot-starter-test")
implementation("io.zonky.test:embedded-postgres:2.0.2")
implementation("io.zonky.test:embedded-database-spring-test:2.2.0")

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

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

trying to learn Springboot with foreign key and one to many relationship relationship using mysql but

trying to get foreign key one to many relationship in spring boot,but i'm not getting what is error and solution
Project struture
this is my user model class
package in.cubereum.Phoenix_backend.models;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.TableGenerator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.ToString;
#Entity
public class User {
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "user_id", updatable = false, nullable = false)
private int user_id;
#Column(name = "active")
private boolean active;
#Column(name = "department")
private String department;
#Column(name = "division")
private String division;
#Column(name = "email")
private String email;
#Column(name = "employee_id")
private String employee_id;
#Column(name = "mobile_number")
private String mobile_number;
#Column(name = "first_name")
private String first_name;
#Column(name = "last_name")
private String last_name;
#Column(name = "nickname")
private String nickname;
#Column(name = "landline_number")
private String landline_number;
#Column(name = "role_id")
private String role_id;
#Column(name = "title")
private String title;
#Column(name = "city")
private String city;
#Column(name = "username")
private String username;
#Column(name = "passwords")
private String passwords;
#Column(name = "created_by")
private String created_by;
#Column(name = "created_date")
private Date created_date;
#Column(name = "modified_by")
private String modified_by;
#Column(name = "modified_date")
private Date modified_date;
#Column(name = "manager")
private String manager;
#JoinColumn(name = "org_id")
#OneToMany
#JsonIgnore
private Organization organization;
public Organization getOrganization() {
return organization;
}
public void setOrganization(Organization organization) {
this.organization = organization;
}
}
this is my organisation model class
package in.cubereum.Phoenix_backend.models;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.*;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.ToString;
#Entity
public class Organization {
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "org_id", updatable = false, nullable = false)
private int org_id;
#Column(name = "org_code") private int org_code;
#Column(name = "org_name") private String org_name;
#Column(name = "org_description") private String org_description;
#Column(name = "parent_org") private String parent_org;
#Column(name = "address") private String address;
#Column(name = "contact_number") private String contact_number;
#Column(name = "created_by") private String created_by;
#Column(name = "created_date") private Date created_date;
#Column(name = "last_modified_by") private String last_modified_by;
#Column(name = "last_modified_date") private Date last_modified_date;
#ManyToOne
private Set<User> roles = new HashSet<>(0);
public Set<User> getRoles() {
return roles;
}
public void setRoles(Set<User> roles) {
this.roles = roles;
}
}
this is my User service class
package in.cubereum.Phoenix_backend.endpoints;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import in.cubereum.Phoenix_backend.repository.Userrepository;
#RestController
#RequestMapping(path = "/main")
#Component
#CrossOrigin(origins = "*")
public class UserService {
#Autowired
private Userrepository userrepository;
}
this is my Organizationrepository Interface
package in.cubereum.Phoenix_backend.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import in.cubereum.Phoenix_backend.models.Organization;
#Repository
public interface Organizationrepository extends JpaRepository<Organization, String>{
}
this is my Userrepository
package in.cubereum.Phoenix_backend.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import in.cubereum.Phoenix_backend.models.User;
#Repository
public interface Userrepository extends JpaRepository<User, String>{
}
this is my main application class
package in.cubereum.Phoenix_backend;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
#SpringBootApplication(scanBasePackages={"in.cubereum.Phoenix_backend.repository"})
#EnableJpaRepositories(basePackages = "in.cubereum.Phoenix_backend.repository")
public class Phoenix_backendApplication extends SpringBootServletInitializer{
#Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/greeting-javaconfig").allowedOrigins("http://localhost:");
}
};
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Phoenix_backendApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(Phoenix_backendApplication.class, args);
}
}
this is my build.gradle file
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:2.0.3.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'war'
group = 'in.cubereum'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
mavenCentral()
}
// In this section you declare where to find the dependencies of your project
repositories {
// Use jcenter for resolving your dependencies.
// You can declare any Maven/Ivy/file repository here.
jcenter()
}
dependencies {
// This dependency is used internally, and not exposed to consumers on their own compile classpath.
implementation 'com.google.guava:guava:23.0'
// This dependency is exported to consumers, that is to say found on their compile classpath.
// https://mvnrepository.com/artifact/org.apache.commons/commons-math3
compile group: 'org.apache.commons', name: 'commons-math3', version: '3.6.1'
// Use JUnit test framework
testImplementation 'junit:junit:4.12'
compile('org.springframework.boot:spring-boot-starter')
testCompile('org.springframework.boot:spring-boot-starter-test')
// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web
compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.0.4.RELEASE'
// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-parent
compile group: 'org.springframework.boot', name: 'spring-boot-starter-parent', version: '2.0.3.RELEASE', ext: 'pom'
// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '2.0.3.RELEASE'
// https://mvnrepository.com/artifact/mysql/mysql-connector-java
compile group: 'mysql', name: 'mysql-connector-java', version: '5.1.47'
// https://mvnrepository.com/artifact/com.fasterxml.jackson.dataformat/jackson-dataformat-xml
compile group: 'com.fasterxml.jackson.dataformat', name: 'jackson-dataformat-xml', version: '2.9.6'
providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat:2.0.4.RELEASE'
// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-json
compile group: 'org.springframework.boot', name: 'spring-boot-starter-json', version: '2.0.5.RELEASE'
// https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind
compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind'
// https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple
compile group: 'com.googlecode.json-simple', name: 'json-simple'
// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-devtools
compile group: 'org.springframework.boot', name: 'spring-boot-devtools', version: '2.0.4.RELEASE'
// https://mvnrepository.com/artifact/org.hibernate/hibernate-core
compile group: 'org.hibernate', name: 'hibernate-core', version: '4.1.4.Final'
// https://mvnrepository.com/artifact/javax.persistence/javax.persistence-api
compile group: 'javax.persistence', name: 'javax.persistence-api', version: '2.2'
// https://mvnrepository.com/artifact/org.projectlombok/lombok
compile group: 'org.projectlombok', name: 'lombok', version: '1.16.6'
}
this is console output that i'm getting
17:36:28.478 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Included patterns for restart : []
17:36:28.481 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Excluded patterns for restart : [/spring-boot-actuator/target/classes/, /spring-boot-devtools/target/classes/, /spring-boot/target/classes/, /spring-boot-starter-[\w-]+/, /spring-boot-autoconfigure/target/classes/, /spring-boot-starter/target/classes/]
17:36:28.481 [main] DEBUG org.springframework.boot.devtools.restart.ChangeableUrls - Matching URLs for reloading : [file:/home/cubereum/workspace/Phoenix_backend/bin/]
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.0.3.RELEASE)
2018-10-04 17:36:29.008 INFO 20416 --- [ restartedMain] i.c.P.Phoenix_backendApplication : Starting Phoenix_backendApplication on cubereum with PID 20416 (/home/cubereum/workspace/Phoenix_backend/bin started by cubereum in /home/cubereum/workspace/Phoenix_backend)
2018-10-04 17:36:29.012 INFO 20416 --- [ restartedMain] i.c.P.Phoenix_backendApplication : No active profile set, falling back to default profiles: default
2018-10-04 17:36:29.140 INFO 20416 --- [ restartedMain] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext#4eaf4b3d: startup date [Thu Oct 04 17:36:29 IST 2018]; root of context hierarchy
2018-10-04 17:36:31.116 INFO 20416 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$d548bd60] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-10-04 17:36:31.675 INFO 20416 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2018-10-04 17:36:31.722 INFO 20416 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-10-04 17:36:31.722 INFO 20416 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.31
2018-10-04 17:36:31.734 INFO 20416 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib]
2018-10-04 17:36:31.841 INFO 20416 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-10-04 17:36:31.842 INFO 20416 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2710 ms
2018-10-04 17:36:32.041 INFO 20416 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
2018-10-04 17:36:32.047 INFO 20416 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-10-04 17:36:32.047 INFO 20416 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-10-04 17:36:32.047 INFO 20416 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-10-04 17:36:32.048 INFO 20416 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-10-04 17:36:32.182 WARN 20416 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: At least one JPA metamodel must be present!
2018-10-04 17:36:32.190 INFO 20416 --- [ restartedMain] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2018-10-04 17:36:32.225 INFO 20416 --- [ restartedMain] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-10-04 17:36:32.233 ERROR 20416 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: At least one JPA metamodel must be present!
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1708) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:581) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:503) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:741) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869) ~[spring-context-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:395) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1255) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1243) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at in.cubereum.Phoenix_backend.Phoenix_backendApplication.main(Phoenix_backendApplication.java:34) [bin/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_181]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_181]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_181]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_181]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.0.4.RELEASE.jar:2.0.4.RELEASE]
Caused by: java.lang.IllegalArgumentException: At least one JPA metamodel must be present!
at org.springframework.util.Assert.notEmpty(Assert.java:450) ~[spring-core-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.data.jpa.mapping.JpaMetamodelMappingContext.<init>(JpaMetamodelMappingContext.java:54) ~[spring-data-jpa-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.jpa.repository.config.JpaMetamodelMappingContextFactoryBean.createInstance(JpaMetamodelMappingContextFactoryBean.java:88) ~[spring-data-jpa-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.data.jpa.repository.config.JpaMetamodelMappingContextFactoryBean.createInstance(JpaMetamodelMappingContextFactoryBean.java:43) ~[spring-data-jpa-2.0.8.RELEASE.jar:2.0.8.RELEASE]
at org.springframework.beans.factory.config.AbstractFactoryBean.afterPropertiesSet(AbstractFactoryBean.java:141) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1767) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1704) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
... 21 common frames omitted
I think you are use MyISAM engine, use InnoDB. It supports Foreign Keys.
Add this line to your application.properties
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL57InnoDBDialect

Spring Data JPA Repository generation error with Property Expression

I am trying to create a spring data JPA repository method using a Property Expression but get an error when starting the Spring Boot application.
package com.ourkid.springdata;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.stereotype.Repository;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.io.Serializable;
import java.sql.Date;
#SpringBootApplication
#EnableJpaRepositories
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
#Repository
interface TimeExtensionRepository extends JpaRepository<TimeExtension, Long> {
TimeExtension findByStatus_ShortNameAndBusinessDateAndWorkplace(String shortName, Date businessDate, Workplace workplace);
}
#Entity
class Workplace implements Serializable {
public final static long serialVersionUID = 1L;
#Id
#GeneratedValue
private Long id;
#Column(nullable = false)
private String description;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
#Entity
class Status implements Serializable {
public final static long serialVersionUID = 2L;
#Id
#GeneratedValue
private Long id;
#Column(nullable = false)
private String shortName;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getShortName() {
return shortName;
}
public void setShortName(String shortName) {
this.shortName = shortName;
}
}
#Entity
class TimeExtension implements Serializable {
public final static long serialVersionUID = 3L;
#Id
#GeneratedValue
private Long id;
#Column(nullable = false)
private Date businessDate;
#Column(nullable = false)
private Workplace workplace;
#Column(nullable = false)
private Status status;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getBusinessDate() {
return businessDate;
}
public void setBusinessDate(Date businessDate) {
this.businessDate = businessDate;
}
public Workplace getWorkplace() {
return workplace;
}
public void setWorkplace(Workplace workplace) {
this.workplace = workplace;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
}
Simple repo methods work but I cannot get this property expression to work properly. I am using Spring Boot 1.4.3.RELEASE with dependency spring-boot-starter-data-jpa and Java 8.
The error and entire output is as follows:
/Library/Java/JavaVirtualMachines/jdk1.8.0_74.jdk/Contents/...
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.4.3.RELEASE)
2017-01-04 23:55:25.092 INFO 1788 --- [ main] com.ourkid.springdata.DemoApplication : Starting DemoApplication on SRA-MBA.local with PID 1788 (/Users/saj/Downloads/demo/target/classes started by saj in /Users/saj/Downloads/demo)
2017-01-04 23:55:25.096 INFO 1788 --- [ main] com.ourkid.springdata.DemoApplication : No active profile set, falling back to default profiles: default
2017-01-04 23:55:25.238 INFO 1788 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#5427c60c: startup date [Wed Jan 04 23:55:25 GMT 2017]; root of context hierarchy
2017-01-04 23:55:26.850 INFO 1788 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2017-01-04 23:55:26.875 INFO 1788 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2017-01-04 23:55:26.968 INFO 1788 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.0.11.Final}
2017-01-04 23:55:26.969 INFO 1788 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2017-01-04 23:55:26.971 INFO 1788 --- [ main] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2017-01-04 23:55:27.093 INFO 1788 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2017-01-04 23:55:27.208 INFO 1788 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2017-01-04 23:55:27.717 INFO 1788 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000227: Running hbm2ddl schema export
2017-01-04 23:55:27.730 INFO 1788 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000230: Schema export complete
2017-01-04 23:55:27.774 INFO 1788 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2017-01-04 23:55:28.063 WARN 1788 --- [ main] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'timeExtensionRepository': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Illegal attempt to dereference path source [null.status] of basic type
2017-01-04 23:55:28.063 INFO 1788 --- [ main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2017-01-04 23:55:28.063 INFO 1788 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000227: Running hbm2ddl schema export
2017-01-04 23:55:28.070 INFO 1788 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000230: Schema export complete
2017-01-04 23:55:28.079 INFO 1788 --- [ main] utoConfigurationReportLoggingInitializer :
Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-01-04 23:55:28.092 ERROR 1788 --- [ main] o.s.boot.SpringApplication : Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'timeExtensionRepository': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Illegal attempt to dereference path source [null.status] of basic type
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1589) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:554) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:740) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866) ~[spring-context-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:761) [spring-boot-1.4.3.RELEASE.jar:1.4.3.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:371) [spring-boot-1.4.3.RELEASE.jar:1.4.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-1.4.3.RELEASE.jar:1.4.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1186) [spring-boot-1.4.3.RELEASE.jar:1.4.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1175) [spring-boot-1.4.3.RELEASE.jar:1.4.3.RELEASE]
at com.ourkid.springdata.DemoApplication.main(DemoApplication.java:21) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_74]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_74]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_74]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_74]
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147) [idea_rt.jar:na]
Caused by: java.lang.IllegalStateException: Illegal attempt to dereference path source [null.status] of basic type
at org.hibernate.jpa.criteria.path.AbstractPathImpl.illegalDereference(AbstractPathImpl.java:82) ~[hibernate-entitymanager-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.jpa.criteria.path.AbstractPathImpl.get(AbstractPathImpl.java:174) ~[hibernate-entitymanager-5.0.11.Final.jar:5.0.11.Final]
at org.springframework.data.jpa.repository.query.QueryUtils.toExpressionRecursively(QueryUtils.java:622) ~[spring-data-jpa-1.10.6.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.QueryUtils.toExpressionRecursively(QueryUtils.java:576) ~[spring-data-jpa-1.10.6.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.JpaQueryCreator$PredicateBuilder.getTypedPath(JpaQueryCreator.java:334) ~[spring-data-jpa-1.10.6.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.JpaQueryCreator$PredicateBuilder.build(JpaQueryCreator.java:277) ~[spring-data-jpa-1.10.6.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.JpaQueryCreator.toPredicate(JpaQueryCreator.java:182) ~[spring-data-jpa-1.10.6.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.JpaQueryCreator.create(JpaQueryCreator.java:109) ~[spring-data-jpa-1.10.6.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.JpaQueryCreator.create(JpaQueryCreator.java:49) ~[spring-data-jpa-1.10.6.RELEASE.jar:na]
at org.springframework.data.repository.query.parser.AbstractQueryCreator.createCriteria(AbstractQueryCreator.java:109) ~[spring-data-commons-1.12.6.RELEASE.jar:na]
at org.springframework.data.repository.query.parser.AbstractQueryCreator.createQuery(AbstractQueryCreator.java:88) ~[spring-data-commons-1.12.6.RELEASE.jar:na]
at org.springframework.data.repository.query.parser.AbstractQueryCreator.createQuery(AbstractQueryCreator.java:73) ~[spring-data-commons-1.12.6.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.PartTreeJpaQuery$QueryPreparer.<init>(PartTreeJpaQuery.java:118) ~[spring-data-jpa-1.10.6.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.PartTreeJpaQuery$CountQueryPreparer.<init>(PartTreeJpaQuery.java:241) ~[spring-data-jpa-1.10.6.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:68) ~[spring-data-jpa-1.10.6.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:103) ~[spring-data-jpa-1.10.6.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:214) ~[spring-data-jpa-1.10.6.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:77) ~[spring-data-jpa-1.10.6.RELEASE.jar:na]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:435) ~[spring-data-commons-1.12.6.RELEASE.jar:na]
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:220) ~[spring-data-commons-1.12.6.RELEASE.jar:na]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:280) ~[spring-data-commons-1.12.6.RELEASE.jar:na]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:266) ~[spring-data-commons-1.12.6.RELEASE.jar:na]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:92) ~[spring-data-jpa-1.10.6.RELEASE.jar:na]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1648) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1585) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
... 20 common frames omitted
Process finished with exit code 1
The issue looks similar to that reported in https://jira.spring.io/browse/DATAJPA-476 but the underlying error is meant to have been fixed.
Following change to TimeExtension fixes the issue.
#Entity
class TimeExtension implements Serializable {
public final static long serialVersionUID = 3L;
#Id
#GeneratedValue
private Long id;
#Column(nullable = false)
private Date businessDate;
#OneToOne
#JoinColumn(nullable = false, name = "workplace_id")
private Workplace workplace;
#OneToOne
#JoinColumn(nullable = false, name = "status_id")
private Status status;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getBusinessDate() {
return businessDate;
}
public void setBusinessDate(Date businessDate) {
this.businessDate = businessDate;
}
public Workplace getWorkplace() {
return workplace;
}
public void setWorkplace(Workplace workplace) {
this.workplace = workplace;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
}
Maybe I missed some new features of Spring and JPA but for me it looks like you dont have any relationships mapped on your entities.
The TimeExtension entity should have any relation to Status and Workplace. Something like #OneToMany, #ManyToOne, #OneToOne or #ManyToMany. So JPA know the relation between the entities.

Spring boot cassandra integration #EnableCassandraRepositories not generating implementation for Cassandra Repository

I am trying to integrate cassandra with Spring boot using spring-data-cassandra.
Application.java
package hello;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.ComponentScan;
#ComponentScan
#EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
CassandraConfiguration.java
package conf;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.cassandra.config.CassandraClusterFactoryBean;
import org.springframework.data.cassandra.config.java.AbstractCassandraConfiguration;
import org.springframework.data.cassandra.mapping.BasicCassandraMappingContext;
import org.springframework.data.cassandra.mapping.CassandraMappingContext;
import org.springframework.data.cassandra.repository.config.EnableCassandraRepositories;
#Configuration
#EnableCassandraRepositories("dao")
public class CassandraConfiguration extends AbstractCassandraConfiguration {
#Bean
#Override
public CassandraClusterFactoryBean cluster() {
CassandraClusterFactoryBean cluster = new CassandraClusterFactoryBean();
cluster.setContactPoints("localhost");
cluster.setPort(9042);
return cluster;
}
#Override
protected String getKeyspaceName() {
return "mykeyspace";
}
#Bean
#Override
public CassandraMappingContext cassandraMapping() throws ClassNotFoundException {
return new BasicCassandraMappingContext();
}
}
UserDao.java
package dao;
import hello.User;
import org.springframework.data.cassandra.repository.CassandraRepository;
import org.springframework.data.cassandra.repository.Query;
public interface UserDao extends CassandraRepository<User> {
#Query("select * from users where fname = ?0")
Iterable findByFname(String fname);
}
RestController.java
package hello;
import dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class UserController {
#Autowired
UserDao userDao;
#RequestMapping("/greeting")
public Iterable<User> getInfo(#RequestParam(value="name", defaultValue="Hello") String name, #RequestParam(value="lname", defaultValue="World") String lname) {
return userDao.findByFname(name) ;//new User(counter.incrementAndGet(),name, lname);
}
}
User.java
package hello;
import org.springframework.data.cassandra.mapping.Column;
import org.springframework.data.cassandra.mapping.PrimaryKey;
import org.springframework.data.cassandra.mapping.Table;
#Table
public class User {
#PrimaryKey
private final long id;
#Column
private final String fname;
#Column
private final String lname;
public User(long id, String fname, String lname) {
this.id = id;
this.fname = fname;
this.lname = lname;
}
public long getId() {
return id;
}
public String getFname() {
return fname;
}
public String getLname() {
return lname;
}
}
Behind the scene #EnableCassandraConfiguration should create an implementation for UserDao interface. but seems like it is not doing so for some reason. Logs are not that useful to tell specific mistake i am making here. Still for help i am posting it here.
2015-02-11 12:10:58.424 INFO 7828 --- [ main] hello.Application : Starting Application on HOTCPC9941 with PID 7828 (C:\Users\prashant.tiwari\Documents\NetBeansProjects\DemoApp\target\classes started by prashant.tiwari in C:\Users\prashant.tiwari\Documents\NetBeansProjects\DemoApp)
2015-02-11 12:10:58.459 INFO 7828 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#4f5737ca: startup date [Wed Feb 11 12:10:58 GMT 2015]; root of context hierarchy
2015-02-11 12:10:59.141 INFO 7828 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'beanNameViewResolver': replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]]
2015-02-11 12:10:59.865 INFO 7828 --- [ main] .t.TomcatEmbeddedServletContainerFactory : Server initialized with port: 8080
2015-02-11 12:11:00.035 INFO 7828 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
2015-02-11 12:11:00.036 INFO 7828 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/7.0.57
2015-02-11 12:11:00.127 INFO 7828 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2015-02-11 12:11:00.128 INFO 7828 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1672 ms
2015-02-11 12:11:00.555 INFO 7828 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2015-02-11 12:11:00.557 INFO 7828 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2015-02-11 12:11:00.682 WARN 7828 --- [ main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: dao.UserDao hello.UserController.userDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [dao.UserDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:301)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1186)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
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:706)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:762)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.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)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:952)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:941)
at hello.Application.main(Application.java:12)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: dao.UserDao hello.UserController.userDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [dao.UserDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:522)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:298)
... 16 common frames omitted
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [dao.UserDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1118)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:967)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:862)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:494)
... 18 common frames omitted
Seems that your Dao class doesn't get registered into the context. I'd say it is missing an appropriate annotation like #Repository.
Additionally your Application class is living in the hello package and without any further configuration is only scanning for components below it. That is why it is not finding the CassandraConfiguration (living in conf). And this is then also not scanning the dao package.
I was also facing the same problem for auto wiring the class which uses cassandra support, try adding:
#EnableCassandraRepositories(basePackages="package path where where is ur bean")

Resources