why is there error, when i use querydsl in kotlin? - spring-boot

i want to use querydsl in springboot(kotlin), but when i test querydsl by useing findOne(), there is error..
Account data class
#Entity
data class Account(
val username: String,
val firstName: String,
val lastName: String
) {
#Id
#GeneratedValue
val id: Long? = null
}
AccountRepository
interface AccountRepository : JpaRepository<Account, Long>,
QuerydslPredicateExecutor<Account>
test code
#DataJpaTest
class AccountRepositoryTest {
#Autowired
lateinit var accountRepository: AccountRepository
#Test
fun crud() {
accountRepository.save(Account(username = "sooyougkim",
firstName = "sooyoug",
lastName = "kim"))
val predicate: Predicate = QAccount
.account
.firstName
.containsIgnoreCase("sooyoug")
.and(QAccount.account.lastName.startsWith("kim"))
val findOne = accountRepository.findOne(predicate).get()
}
}
error message
java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableMap.put(Collections.java:1459)
at com.querydsl.jpa.JPQLSerializer.visitConstant(JPQLSerializer.java:327)
at com.querydsl.core.support.SerializerBase.visit(SerializerBase.java:221)
at com.querydsl.core.support.SerializerBase.visit(SerializerBase.java:36)
at com.querydsl.core.types.ConstantImpl.accept(ConstantImpl.java:140)
.
.
.
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
at java.lang.Thread.run(Thread.java:821)
AccountRepositoryTest > crud() FAILED
java.lang.UnsupportedOperationException at AccountRepositoryTest.kt:31
2020-07-30 09:58:37.653 INFO 21450 --- [extShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2020-07-30 09:58:37.653 INFO 21450 --- [extShutdownHook] .SchemaDropperImpl$DelayedDropActionImpl : HHH000477: Starting delayed evictData of schema as part of SessionFactory shut-down'
Hibernate:
i think that there is some mapping error QAccount -> Account...
is there anyone to check?

I solved the problem.
the reason is plugin version problem..
when i changed version to latest, querydsl doing well.
this is my dependency of build.gradle.kts
api("com.querydsl:querydsl-jpa:4.3.1")
kapt("com.querydsl:querydsl-apt:4.3.1:jpa")
and, you can check the version of plugin here.
https://docs.spring.io/spring-boot/docs/2.3.1.RELEASE/reference/html/appendix-dependency-versions.html

Related

Lazy fetching in Spring JPA - different behaviour within cron and REST request

I have a little problem to understand why lazy fetching have different behaviour when I'm trying to execute 'findAll' method from REST controller and CRON job.
I have two simple entities:
#Entity
#Data
public class MainEntity {
#Id
#GeneratedValue(generator = "MainEntitySeqGen", strategy = GenerationType.SEQUENCE)
#SequenceGenerator(name = "MainEntitySeqGen", sequenceName = "main_entity_seq")
private Long id;
#OneToMany(fetch = FetchType.LAZY)
#JoinColumn(name = "main_id", foreignKey = #ForeignKey(name = "FK_mainEntity_nestedEntity"))
private Set<NestedEntity> nestedEntities;
}
and
#Entity
#Data
public class NestedEntity {
#Id
#GeneratedValue(generator = "NestedEntitySeqGen", strategy = GenerationType.SEQUENCE)
#SequenceGenerator(name = "NestedEntitySeqGen", sequenceName = "nested_entity_seq")
private Long id;
#Column
private String sample;
}
and service with method to find all 'MainEntities'. This service doesn't have any #Transactional annotations! (I don't have it in whole project)
#Override
public List<MainEntity> findAll() {
log.info("Finding all main entities...");
return repository.findAll();
}
I have one additional service to test lazy initialization exception with method:
#Override
public void testMe() {
List<MainEntity> entities = mainEntityService.findAll();
if (!entities.isEmpty()) {
log.info("Nested entities size: {}", entities.get(0).getNestedEntities().size());
}
}
Still no transactions on method or service!
Ok, and now, when I'm trying to execute testMe method from REST controller:
#GetMapping
public ResponseEntity<Void> testMe() {
log.info("Execution from API: Not throwing LazyInitializationException");
testService.testMe();
return ResponseEntity.ok().build();
}
I have correct output:
2022-05-01 00:04:42.396 INFO 11428 --- [nio-8080-exec-2] c.r.jpatest.web.FirstTestServiceApi : Execution from API: Not throwing LazyInitializationException
2022-05-01 00:04:42.396 INFO 11428 --- [nio-8080-exec-2] c.r.j.s.impl.MainEntityServiceImpl : Finding all main entities...
2022-05-01 00:04:42.396 TRACE 11428 --- [nio-8080-exec-2] o.s.t.i.TransactionInterceptor : Getting transaction for [org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll]
Hibernate: select mainentity0_.id as id1_0_ from main_entity mainentity0_
2022-05-01 00:04:42.397 TRACE 11428 --- [nio-8080-exec-2] o.s.t.i.TransactionInterceptor : Completing transaction for [org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll]
Hibernate: select nestedenti0_.main_id as main_id3_1_0_, nestedenti0_.id as id1_1_0_, nestedenti0_.id as id1_1_1_, nestedenti0_.sample as sample2_1_1_ from nested_entity nestedenti0_ where nestedenti0_.main_id=?
2022-05-01 00:04:42.408 INFO 11428 --- [nio-8080-exec-2] c.r.j.service.impl.TestServiceImpl : Nested entities size: 5
Please note that TransactionInterceptor says, he completed transaction for 'findAll' (from repository) but nevertheless he's invoking SELECT query to fetch NestedEntities that should be loaded lazily and I expected it throw exception (but not).
And this same 'testMe' method executed from CRON:
#Scheduled(cron = "*/10 * * * * *")
public void testCron() {
log.info("Execution from CRON: Throwing LazyInitializationException");
testService.testMe();
}
is throwing exception:
2022-05-01 00:04:50.014 INFO 11428 --- [ scheduling-1] c.r.jpatest.cronservices.TestCron : Execution from CRON: Throwing LazyInitializationException
2022-05-01 00:04:50.014 INFO 11428 --- [ scheduling-1] c.r.j.s.impl.MainEntityServiceImpl : Finding all main entities...
2022-05-01 00:04:50.014 TRACE 11428 --- [ scheduling-1] o.s.t.i.TransactionInterceptor : Getting transaction for [org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll]
Hibernate: select mainentity0_.id as id1_0_ from main_entity mainentity0_
2022-05-01 00:04:50.015 TRACE 11428 --- [ scheduling-1] o.s.t.i.TransactionInterceptor : Completing transaction for [org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll]
2022-05-01 00:04:50.016 ERROR 11428 --- [ scheduling-1] o.s.s.s.TaskUtils$LoggingErrorHandler : Unexpected error occurred in scheduled task
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.axl.jpatest.domain.MainEntity.nestedEntities, could not initialize proxy - no Session
at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:614) ~[hibernate-core-5.6.8.Final.jar:5.6.8.Final]
at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:218) ~[hibernate-core-5.6.8.Final.jar:5.6.8.Final]
at org.hibernate.collection.internal.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:162) ~[hibernate-core-5.6.8.Final.jar:5.6.8.Final]
at org.hibernate.collection.internal.PersistentSet.size(PersistentSet.java:168) ~[hibernate-core-5.6.8.Final.jar:5.6.8.Final]
at com.axl.jpatest.service.impl.TestServiceImpl.testMe(TestServiceImpl.java:23) ~[classes/:na]
at com.axl.jpatest.cronservices.TestCron.testCron(TestCron.java:19) ~[classes/:na]
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:566) ~[na:na]
at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:84) ~[spring-context-5.3.19.jar:5.3.19]
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54) ~[spring-context-5.3.19.jar:5.3.19]
at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:95) ~[spring-context-5.3.19.jar:5.3.19]
at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515) ~[na:na]
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na]
at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:304) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]
Does anyone have idea why it works like that?
I use:
Spring Boot: v2.6.7
Hibernate: v5.6.8
I founded answer for this "problem" - cause is "Open Session In View" Spring mechanism.
Links:
#RestController methods seem to be Transactional by default, Why?
https://www.baeldung.com/spring-open-session-in-view
The error tell you that you're trying to fetch a lazy association, but there is no existing Hibernate Session for your current thread since you do it outside a transactional context.
Using JPA without delimiting your transaction boundaries explicitly with #Transactional is not a good thing because it creates an obscure code that creates a lot of short-lived Session and bypasses a lot of features that Hibernate offers you (session-level repeatable read, write-behind...)

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> {

How can i setup Spring Boot with two datasources (MapRepository and H2 JPARepository)?

I'm trying to set up a spring boot project with two datasources.
First datasource would be a H2 Database and second a MapRepository.
Both repositories would share the same entity.
I could manage to setup a project with two H2 databases, but when I try to setup a MapRepository instead of the second H2 datasource I get the following error:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.4.0)
2021-01-12 10:57:16.610 INFO 26672 --- [ main] ch.getonline.springtestapp.App : Starting App using Java 15.0.1 on nbbetina1 with PID 26672 (C:\Users\BetinaHiestand\eclipse20-workspace\spring-test-app\target\classes started by BetinaHiestand in C:\Users\BetinaHiestand\eclipse20-workspace\spring-test-app)
2021-01-12 10:57:16.612 INFO 26672 --- [ main] ch.getonline.springtestapp.App : The following profiles are active: dev
2021-01-12 10:57:17.070 INFO 26672 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2021-01-12 10:57:17.070 INFO 26672 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data Map repositories in DEFAULT mode.
2021-01-12 10:57:17.092 INFO 26672 --- [ main] .RepositoryConfigurationExtensionSupport : Spring Data Map - Could not safely identify store assignment for repository candidate interface ch.getonline.springtestapp.storage.repositories.map.MapRepository. If you want this repository to be a Map repository, consider extending one of the following types with your repository: org.springframework.data.keyvalue.repository.KeyValueRepository.
2021-01-12 10:57:17.092 INFO 26672 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 15 ms. Found 0 Map repository interfaces.
2021-01-12 10:57:17.094 INFO 26672 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2021-01-12 10:57:17.094 INFO 26672 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2021-01-12 10:57:17.111 INFO 26672 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 14 ms. Found 1 JPA repository interfaces.
2021-01-12 10:57:17.654 INFO 26672 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2021-01-12 10:57:17.661 INFO 26672 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-01-12 10:57:17.661 INFO 26672 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.39]
2021-01-12 10:57:17.758 INFO 26672 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-01-12 10:57:17.758 INFO 26672 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1105 ms
2021-01-12 10:57:17.976 INFO 26672 --- [ main] o.s.b.a.h2.H2ConsoleAutoConfiguration : H2 console available at '/dbadmin'. Database available at 'jdbc:h2:mem:db1dev'
2021-01-12 10:57:18.058 INFO 26672 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2021-01-12 10:57:18.099 INFO 26672 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.23.Final
2021-01-12 10:57:18.198 INFO 26672 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2021-01-12 10:57:18.324 INFO 26672 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
Hibernate:
drop table if exists "BasicEntity" CASCADE
Hibernate:
create table "BasicEntity" (
"DNA" binary not null,
"id" varchar(255),
"type" varchar(255),
primary key ("DNA")
)
2021-01-12 10:57:18.759 INFO 26672 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2021-01-12 10:57:18.765 INFO 26672 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2021-01-12 10:57:18.787 INFO 26672 --- [ main] ch.getonline.springtestapp.App : SpringTestApplication is starting...
2021-01-12 10:57:18.931 WARN 26672 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'appContext': Unsatisfied dependency expressed through field 'entityStorage'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityStorageHandler' defined in file [C:\Users\BetinaHiestand\eclipse20-workspace\spring-test-app\target\classes\ch\getonline\springtestapp\storage\handlers\EntityStorageHandler.class]: Unsatisfied dependency expressed through constructor parameter 2; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'ch.getonline.springtestapp.storage.repositories.map.MapRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
2021-01-12 10:57:18.931 INFO 26672 --- [ main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2021-01-12 10:57:18.933 INFO 26672 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2021-01-12 10:57:18.944 INFO 26672 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-01-12 10:57:18.956 ERROR 26672 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 2 of constructor in ch.getonline.springtestapp.storage.handlers.EntityStorageHandler required a bean of type 'ch.getonline.springtestapp.storage.repositories.map.MapRepository' 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 'ch.getonline.springtestapp.storage.repositories.map.MapRepository' in your configuration.
I already tried to add the ComponentScan and add a repository annotation to the MapRepository, but couldn't figure out why no bean was created for it. Both repositories are in seperate packages which are set as basePackages for the EnableMapRepositories/EnableJpaRepositories annotation. For the SQLRepository I created a configuration class with the driver properties etc. I am not sure if something like this would also be needed for the MapRepositories and couldn't find helpful documentation about it.
I am not really experienced with Spring Boot therefore the first question would be if its possible to have a setup like this? And if yes how am I supposed to configure it?
Application start:
#SpringBootApplication
#ComponentScan (basePackages = {"ch.getonline.springtestapp"})
#EntityScan("ch.getonline.springtestapp.entity.types")
#EnableMapRepositories(basePackages = "ch.getonline.springtestapp.storage.repositories.map")
#EnableJpaRepositories(basePackages = "ch.getonline.springtestapp.storage.repositories.sql", entityManagerFactoryRef = "sqlDatabaseEntityManager", transactionManagerRef = "sqlDatabaseTransactionManager")
public class App {
// Logger setup (Per class)
private static final Logger log = LoggerFactory.getLogger(App.class);
/*
* Application start
*/
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(App.class, args);
System.out.println("App context in main: " + ctx.getDisplayName());
}
MapRepository:
package ch.getonline.springtestapp.storage.repositories.map;
import org.springframework.stereotype.Repository;
import ch.getonline.springtestapp.storage.repositories.EntityRepository;
#Repository("mapRepository")
public interface MapRepository extends EntityRepository {
}
EntityRepository:
package ch.getonline.springtestapp.storage.repositories;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.NoRepositoryBean;
import ch.getonline.springtestapp.entity.types.BasicEntity;
#NoRepositoryBean
public interface EntityRepository extends CrudRepository<BasicEntity, Long>{
//Entity findByUuid(UUID id);
}
StorageHandler in which I tried to access both repositories:
package ch.getonline.springtestapp.storage.handlers;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import ch.getonline.springtestapp.AppContext;
import ch.getonline.springtestapp.entity.attribute.Attribute;
import ch.getonline.springtestapp.entity.types.BasicEntity;
import ch.getonline.springtestapp.storage.StorageHandler;
import ch.getonline.springtestapp.storage.repositories.EntityRepository;
import ch.getonline.springtestapp.storage.repositories.map.MapRepository;
import ch.getonline.springtestapp.storage.repositories.sql.SQLRepository;
/** Entity Storage
* <br>
*
* - Coordinates saving, loading, updating of Entities over different Repositories
*
*
* #author sigi
*
*/
#Component
public class EntityStorageHandler implements StorageHandler<BasicEntity, Long> {
// Logger
private static final Logger log = LoggerFactory.getLogger(EntityStorageHandler.class);
private final AppContext app;
private final Map<String, EntityRepository> repos;
EntityStorageHandler(AppContext app, SQLRepository sqlRepo, MapRepository mapRepo) {
this.app = app;
this.repos = new HashMap<String, EntityRepository>();
this.repos.put("sql", sqlRepo);
this.repos.put("map", mapRepo);
}
//StorageHandler start hook
public void run(String... args) throws Exception {
//Print all configs for the key app in the config
StringBuilder appConfig = new StringBuilder();
for(Entry<String, Object> entry : this.app.getConfig().entrySet()) {
appConfig.append("\nkey: " + entry.getKey() + " value: " + entry.getValue());
}
log.info(appConfig.toString());
//Write demo Entity into db
BasicEntity e1 = new BasicEntity();
e1.setId("1");
e1.setType("Type1");
this.repos.get("sql").save(e1);
BasicEntity e2 = new BasicEntity();
e2.setId("2");
e2.setType("Type2");
this.repos.get("sql").save(e2);
BasicEntity e3 = new BasicEntity();
e3.setId("3");
e3.setType("Type3");
this.repos.get("map").save(e2);
}
}
BasicEntity:
package ch.getonline.springtestapp.entity.types;
import java.util.UUID;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.springframework.data.keyvalue.annotation.KeySpace;
import ch.getonline.springtestapp.entity.GenericEntity;
/**
* Basic Entity Implementation
*
* #author sigi
*
*/
#Entity
#KeySpace("basicEntities")
public class BasicEntity extends GenericEntity {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
UUID DNA;
}
SQLConfiguration:
package ch.getonline.springtestapp.configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
import java.util.HashMap;
#Configuration
public class SQLConfiguration {
#Autowired
private Environment env;
public SQLConfiguration() {
super();
}
#Primary
#Bean
public LocalContainerEntityManagerFactoryBean sqlDatabaseEntityManager() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(sqlDataSource());
em.setPackagesToScan("ch.getonline.springtestapp.entity.types");
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
final HashMap<String, Object> properties = new HashMap<String, Object>();
properties.put("hibernate.hbm2ddl.auto", env.getProperty("spring.jpa.hibernate.ddl-auto"));
properties.put("hibernate.dialect", env.getProperty("spring.jpa.database-platform"));
properties.put("hibernate.jdbc.batch_size", env.getProperty("spring.jpa.properties.hibernate.jdbc.batch_size"));
properties.put("hibernate.order_inserts", env.getProperty("spring.jpa.properties.hibernate.order_inserts"));
properties.put("hibernate.order_updates", env.getProperty("spring.jpa.properties.hibernate.order_updates"));
properties.put("hibernate.jdbc.batch_versioned_data", env.getProperty("spring.jpa.properties.hibernate.jdbc.batch_versioned_data"));
properties.put("hibernate.generate_statistics", env.getProperty("spring.jpa.properties.hibernate.generate_statistics"));
properties.put("hibernate.id.new_generator_mappings", env.getProperty("spring.jpa.properties.hibernate.id.new_generator_mappings"));
properties.put("hhibernate.cache.use_second_level_cache", env.getProperty("spring.jpa.properties.hibernate.cache.use_second_level_cache"));
properties.put("hibernate.globally_quoted_identifiers", env.getProperty("spring.jpa.properties.hibernate.globally_quoted_identifiers"));
properties.put("hibernate.format_sql", env.getProperty("spring.jpa.properties.hibernate.format_sql"));
properties.put("hibernate.show_sql", env.getProperty("spring.jpa.properties.hibernate.show_sql"));
properties.put("hibernate.use_sql_comments", env.getProperty("spring.jpa.properties.hibernate.use_sql_comments"));
properties.put("hibernate.type", env.getProperty("spring.jpa.properties.hibernate.type"));
properties.put("hibernate.naming.physical-strategy", env.getProperty("spring.jpa.hibernate.naming.physical-strategy"));
em.setJpaPropertyMap(properties);
return em;
}
#Primary
#Bean
public DataSource sqlDataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("spring.datasource.driverClassName"));
dataSource.setUrl(env.getProperty("spring.datasource.url"));
dataSource.setUsername(env.getProperty("spring.datasource.username"));
dataSource.setPassword(env.getProperty("spring.datasource.password"));
return dataSource;
}
#Primary
#Bean
public PlatformTransactionManager sqlDatabaseTransactionManager() {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(sqlDatabaseEntityManager().getObject());
return transactionManager;
}
}
SQLRepository
package ch.getonline.springtestapp.storage.repositories.sql;
import ch.getonline.springtestapp.storage.repositories.EntityRepository;
public interface SQLRepository extends EntityRepository {
}
application.yml
#Debug mode
debug: false
#External config
spring:
#Basic setup
profiles.active: dev
config:
import: optional:classpath:config/app.properties, optional:classpath:config/config.yml
#Localization
messages:
basename: config.i18n.messages
#db
h2:
console:
path: /dbadmin
enabled: true
settings:
web-allow-others: true
datasource:
username: inmemory
password: inmemory
driverClassName: org.h2.Driver
port: 8080
#jpa
jpa:
hibernate:
ddl-auto: create
naming:
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
properties:
hibernate:
id:
new_generator_mappings: true
cache:
use_second_level_cache: true
order_inserts: true
order_updates: true
globally_quoted_identifiers: true
generate_statistics: false
show_sql: true
format_sql: true
use_sql_comments: true
type: trace
jdbc:
batch_size: 500
batch_versioned_data: false
tmp:
use_jdbc_metadata_defaults: false
database-platform: org.hibernate.dialect.H2Dialect
As written in my comment, it's quite unusual to use two different datasources with one spring boot service. But here are cases where this might be necessary, and here is how to achieve it in a clean way:
Keep in mind, my answer is mostly taken from that Baeldung tutorial
Consider having a datasource like this:
spring.datasource.jdbcUrl = [url]
spring.datasource.username = [username]
spring.datasource.password = [password]
Now, we want to add a second one, preferably with the same syntax:
spring.second-datasource.jdbcUrl = [url]
spring.second-datasource.username = [username]
spring.second-datasource.password = [password]
To use both configurations simoultanously, we just create two configuration classes with a Datasource Bean - pay attention to the prefix annotation:
#Configuration
#PropertySource({"classpath:persistence-multiple-db-boot.properties"})
#EnableJpaRepositories(
basePackages = "com.baeldung.multipledb.dao.user",
entityManagerFactoryRef = "userEntityManager",
transactionManagerRef = "userTransactionManager")
public class PersistenceUserAutoConfiguration {
#Primary
#Bean
#ConfigurationProperties(prefix="spring.datasource")
public DataSource userDataSource() {
return DataSourceBuilder.create().build();
}
// userEntityManager bean
// userTransactionManager bean
}
#Configuration
#PropertySource({"classpath:persistence-multiple-db-boot.properties"})
#EnableJpaRepositories(
basePackages = "com.baeldung.multipledb.dao.product",
entityManagerFactoryRef = "productEntityManager",
transactionManagerRef = "productTransactionManager")
public class PersistenceProductAutoConfiguration {
#Bean
#ConfigurationProperties(prefix="spring.second-datasource")
public DataSource productDataSource() {
return DataSourceBuilder.create().build();
}
// productEntityManager bean
// productTransactionManager bean
}
You could imo just create one configuration class and provide both beans in that one.
For more information see Spring JPA – Multiple Databases

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.

Resources