EntityManagerFactory failed to initialize - spring

guys
I have this entity :
import lombok.*;
import javax.persistence.*;
import java.util.List;
#Entity
#Table(name = "clients")
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
public class Client {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "username")
private String username;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "dob")
private String dob;
#Column(name = "email")
private String email;
#Column(name = "password")
private String password;
#ManyToOne(fetch = FetchType.EAGER, optional = false)
#JoinColumn(name = "role_id")
private Role role;
#OneToMany(mappedBy = "client", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Card> cards;
#OneToMany(mappedBy = "client", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Address> addresses;
#OneToMany(mappedBy = "client", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Order> orders;
}
import lombok.*;
import javax.persistence.*;
import java.util.List;
#Entity
#Table(name = "roles")
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
public class Role {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "name")
private String name;
#OneToMany(mappedBy = "role", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Client> clients;
}
import lombok.*;
import ru.mialyshev.demo.demo.model.enums.*;
import javax.persistence.*;
import java.util.List;
#Entity
#Table(name = "orders")
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
public class Order {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#ManyToOne(fetch = FetchType.EAGER, optional = false)
#JoinColumn(name = "client_id")
private Client client;
#ManyToOne(fetch = FetchType.EAGER, optional = false)
#JoinColumn(name = "address_id")
private Address address;
#Enumerated(EnumType.STRING)
#Column(name = "delivery_type")
private Delivery delivery;
#Enumerated(EnumType.STRING)
#Column(name = "order_status")
private OrderStatus orderStatus;
#Enumerated(EnumType.STRING)
#Column(name = "payment_status")
private PaymentStatus paymentStatus;
#Enumerated(EnumType.STRING)
#Column(name = "payment_type")
private PaymentType paymentType;
#OneToMany(mappedBy = "order", fetch = FetchType.EAGER)
private List<OrderProduct> orderProducts;
}
import lombok.*;
import javax.persistence.*;
import java.util.List;
#Entity
#Table(name = "cards")
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
public class Card {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "card_number")
private String number;
#Column(name = "validaty_date")
private String validatyDate;
#Column(name = "card_owner")
private String owner;
#Column(name = "code")
private String code;
#ManyToOne(fetch = FetchType.EAGER, optional = false)
#JoinColumn(name = "client_id")
private Client client;
}
import lombok.*;
import javax.persistence.*;
import java.util.List;
#Entity
#Table(name = "addresses")
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
public class Address {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "country")
private String country;
#Column(name = "city")
private String city;
#Column(name = "postal_code")
private String postalCode;
#Column(name = "street")
private String street;
#Column(name = "house_number")
private String houseNumber;
#Column(name = "apartament_number")
private String apartamentNumber;
#Column(name = "is_saved")
private boolean isSaved;
#ManyToOne(fetch = FetchType.EAGER, optional = false)
#JoinColumn(name = "client_id")
private Client client;
#OneToMany(mappedBy = "address", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Order> orders;
}
And some service for him, which added new database entries. When I'm start this app (Spring boot + Spring Data), i am getting the following exception :
Failed to initialize JPA EntityManagerFactory: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags: [ru.mialyshev.demo.demo.model.Client.cards, ru.mialyshev.demo.demo.model.Client.orders]
2020-12-28 16:15:09.040 WARN 12012 --- [ main] ConfigServletWebServerApplicationContext : 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/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags: [ru.mialyshev.demo.demo.model.Client.cards, ru.mialyshev.demo.demo.model.Client.orders]
Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags: [ru.mialyshev.demo.demo.model.Client.cards, ru.mialyshev.demo.demo.model.Client.orders]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1788) ~[spring-beans-5.3.2.jar:5.3.2]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:609) ~[spring-beans-5.3.2.jar:5.3.2]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:531) ~[spring-beans-5.3.2.jar:5.3.2]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.2.jar:5.3.2]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.2.jar:5.3.2]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.2.jar:5.3.2]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.2.jar:5.3.2]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1159) ~[spring-context-5.3.2.jar:5.3.2]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913) ~[spring-context-5.3.2.jar:5.3.2]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:588) ~[spring-context-5.3.2.jar:5.3.2]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:144) ~[spring-boot-2.4.1.jar:2.4.1]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:767) ~[spring-boot-2.4.1.jar:2.4.1]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) ~[spring-boot-2.4.1.jar:2.4.1]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:426) ~[spring-boot-2.4.1.jar:2.4.1]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:326) ~[spring-boot-2.4.1.jar:2.4.1]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1309) ~[spring-boot-2.4.1.jar:2.4.1]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1298) ~[spring-boot-2.4.1.jar:2.4.1]
at ru.mialyshev.demo.demo.DemoApplication.main(DemoApplication.java:10) ~[classes/:na]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags: [ru.mialyshev.demo.demo.model.Client.cards, ru.mialyshev.demo.demo.model.Client.orders]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:421) ~[spring-orm-5.3.2.jar:5.3.2]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:396) ~[spring-orm-5.3.2.jar:5.3.2]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.3.2.jar:5.3.2]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1847) ~[spring-beans-5.3.2.jar:5.3.2]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1784) ~[spring-beans-5.3.2.jar:5.3.2]
... 17 common frames omitted
Caused by: org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags: [ru.mialyshev.demo.demo.model.Client.cards, ru.mialyshev.demo.demo.model.Client.orders]
at org.hibernate.loader.plan.exec.internal.AbstractLoadQueryDetails.generate(AbstractLoadQueryDetails.java:193) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.loader.plan.exec.internal.EntityLoadQueryDetails.<init>(EntityLoadQueryDetails.java:85) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.loader.plan.exec.internal.BatchingLoadQueryDetailsFactory.makeEntityLoadQueryDetails(BatchingLoadQueryDetailsFactory.java:64) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.loader.entity.plan.AbstractLoadPlanBasedEntityLoader.<init>(AbstractLoadPlanBasedEntityLoader.java:97) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.loader.entity.plan.AbstractLoadPlanBasedEntityLoader.<init>(AbstractLoadPlanBasedEntityLoader.java:112) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.loader.entity.plan.EntityLoader.<init>(EntityLoader.java:117) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.loader.entity.plan.EntityLoader.<init>(EntityLoader.java:30) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.loader.entity.plan.EntityLoader$Builder.byUniqueKey(EntityLoader.java:82) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.loader.entity.plan.EntityLoader$Builder.byPrimaryKey(EntityLoader.java:75) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.loader.entity.plan.AbstractBatchingEntityLoaderBuilder.buildNonBatchingLoader(AbstractBatchingEntityLoaderBuilder.java:30) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.loader.entity.BatchingEntityLoaderBuilder.buildLoader(BatchingEntityLoaderBuilder.java:61) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.createEntityLoader(AbstractEntityPersister.java:2610) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.createEntityLoader(AbstractEntityPersister.java:2632) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.generateDelayedEntityLoader(AbstractEntityPersister.java:4384) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.internal.util.collections.LazyIndexedMap.lockedComputeIfAbsent(LazyIndexedMap.java:77) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.internal.util.collections.LazyIndexedMap.computeIfAbsent(LazyIndexedMap.java:63) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.persister.entity.EntityLoaderLazyCollection.getOrBuildByLockMode(EntityLoaderLazyCollection.java:34) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.getLoaderByLockMode(AbstractEntityPersister.java:4375) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.createLoaders(AbstractEntityPersister.java:4362) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.postInstantiate(AbstractEntityPersister.java:4337) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.metamodel.internal.MetamodelImpl.initialize(MetamodelImpl.java:257) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:301) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:469) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1259) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) ~[spring-orm-5.3.2.jar:5.3.2]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.3.2.jar:5.3.2]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:409) ~[spring-orm-5.3.2.jar:5.3.2]
... 21 common frames omitted
Process finished with exit code 1
What am I doing wrong? Before that, I wrote an application with similar functionality and everything worked fine. Now, in the new application, these are the errors.

You have defined fetch = FetchType.EAGER at your #OneToMany relations. That means Hibernate would try to fetch them together with the related entities using a JOIN, with multiple relations in place, that would be way to huge. Generally it's not advisable to use EAGER fetching, better user LAZY fetching and build custom queries where they are needed. Check out https://vladmihalcea.com/eager-fetching-is-a-code-smell/ on this topic. Maybe Bootify.io may help you as well to create the database model.

Related

java.lang.OutOfMemoryError: Java heap space Hibernate entityIsPersistent

I am reading 5gb of XML file using the below code and processing that data into Database using spring dataJpa, this below is just sample logic we are closing the inpustream and aswell xsr object.
XMLInputFactory xf=XMLInputFactory.newInstance();
XMLStreamReader xsr=xf.createXMLStreamReader(new InputStreamReader(new FileInputStream("test.xml"))
i have configured the max 8GB(ie -xms7000m and -xmx8000m) of heap memory But its getting the below hibernate heap issue when saving the data. it inserted around 700000 data total of 2100000
[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Handler dispatch failed; nested exception is java.lang.OutOfMemoryError: Java heap space] with root cause
java.lang.OutOfMemoryError: Java heap space
at java.base/java.util.IdentityHashMap.resize(IdentityHashMap.java:472) ~[na:na]
at java.base/java.util.IdentityHashMap.put(IdentityHashMap.java:441) ~[na:na]
at org.hibernate.event.internal.DefaultPersistEventListener.entityIsPersistent(DefaultPersistEventListener.java:159) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:124) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
at org.hibernate.internal.SessionImpl$$Lambda$1620/0x00000008010a3040.applyEventToListener(Unknown Source) ~[na:na]
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:113) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
at org.hibernate.internal.SessionImpl.persistOnFlush(SessionImpl.java:765) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
at org.hibernate.engine.spi.CascadingActions$8.cascade(CascadingActions.java:341) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:492) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:416) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:218) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
at org.hibernate.engine.internal.Cascade.cascadeCollectionElements(Cascade.java:525) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
at org.hibernate.engine.internal.Cascade.cascadeCollection(Cascade.java:456) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:419) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:218) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:151) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
at org.hibernate.event.internal.AbstractFlushingEventListener.cascadeOnFlush(AbstractFlushingEventListener.java:158) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
at org.hibernate.event.internal.AbstractFlushingEventListener.prepareEntityFlushes(AbstractFlushingEventListener.java:148) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
at org.hibernate.event.internal.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:81) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
at org.hibernate.internal.SessionImpl$$Lambda$1597/0x0000000801076040.accept(Unknown Source) ~[na:na]
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:102) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1362) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:453) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3212) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2380) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:447) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:183) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:40) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:281) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:101) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:534) ~[spring-orm-5.2.10.RELEASE.jar:5.2.10.RELEASE]
As per the above trace logs it seems some issue with hibernate save casacade , but not able to figured out , below are the entity classes which uses to save the data in databse.
#Data
#EqualsAndHashCode
#Builder(toBuilder = true)
#NoArgsConstructor(access = AccessLevel.PRIVATE)
#AllArgsConstructor(access = AccessLevel.PRIVATE)
public class UMEnityPK implements Serializable {
private static final long serialVersionUID=1L;
private String batchId;
private Long batchVersion;
private BigInteger umId;
}
#Data
#Builder(toBuilder = true)
#NoArgsConstructor(access = AccessLevel.PRIVATE)
#AllArgsConstructor(access = AccessLevel.PRIVATE)
#EqualsAndHashCode(of = {"batchId", "batchVersion", "umId"})
#Entity
#Table(name ="um_base")
#IdClass(UMEnityPK.class)
public class UMBase {
#Id private String batchId;
#Id private Long batchVersion;
#Id private BigInteger umId;
private String firstName;
private String lastName;
private String umType;
private String umLevel;
#OneToMany(mappedBy = "umBase", cascade = CascadeType.ALL)
private List<UMAddress> umAddresses;
#OneToMany(mappedBy = "umBase", cascade = CascadeType.ALL)
private List<UMIdentifier> umIdentifiers;
#OneToOne(mappedBy = "umBase", cascade = CascadeType.ALL)
private UMHierarchy umHierarchy;
}
#Data
#Builder(toBuilder = true)
#NoArgsConstructor(access = AccessLevel.PRIVATE)
#AllArgsConstructor(access = AccessLevel.PRIVATE)
#EqualsAndHashCode(of = {"id"})
#Entity
#Table(name = "um_identifier")
public class UMIdentifier {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "um_address")
#SequenceGenerator(name = "um_address", sequenceName = "SEQ_UM_ADDRESS", allocationSize = 1)
private Long id;
private String idValue;
private String idType;
private String groupType;
#ManyToOne
#JoinColumns({
#JoinColumn(name = "BATCH_ID", referencedColumnName = "batchId"),
#JoinColumn(name = "BATCH_VERSION", referencedColumnName = "batchVersion"),
#JoinColumn(name = "UM_ID", referencedColumnName = "umId")
})
private UMBase umBase;
}
#Data
#Builder(toBuilder = true)
#NoArgsConstructor(access = AccessLevel.PRIVATE)
#AllArgsConstructor(access = AccessLevel.PRIVATE)
#EqualsAndHashCode(of = {"batchId", "batchVersion", "umId"})
#Entity
#Table(name ="um_hierarchy")
public class UMHierarchy {
#Id
private String batchId;
#Id private Long batchVersion;
#Id private BigInteger umId;
private String hierarchyTpe;
private String umStatusCode;
private String immediateParentId;
private Date hierarchyDate;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumns({
#JoinColumn(name = "BATCH_ID", referencedColumnName = "batchId"),
#JoinColumn(name = "BATCH_VERSION", referencedColumnName = "batchVersion"),
#JoinColumn(name = "UM_ID", referencedColumnName = "umId")
})
private UMBase umBase;
}
#Data
#Builder(toBuilder = true)
#NoArgsConstructor(access = AccessLevel.PRIVATE)
#AllArgsConstructor(access = AccessLevel.PRIVATE)
#EqualsAndHashCode(of = {"id"})
#Entity
#Table(name = "um_address")
public class UMAddress {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "um_address")
#SequenceGenerator(name = "um_address", sequenceName = "SEQ_UM_ADDRESS", allocationSize = 1)
private Long id;
private String addressType;
private String addressLine1;
private String getAddressLine2;
private String city;
private String state;
private String postalCode;
private String country;
#ManyToOne
#JoinColumns({
#JoinColumn(name = "BATCH_ID", referencedColumnName = "batchId"),
#JoinColumn(name = "BATCH_VERSION", referencedColumnName = "batchVersion"),
#JoinColumn(name = "UM_ID", referencedColumnName = "umId")
})
private UMBase umBase;
}
Is there any issues with hibernate entity mapping which eating of the memory
After checking the heap dump, the issue is with the org.hibernate.engine.StatefulPersistenceContext -> org.hibernate.util.IdentityMap memory leak , so used the below way and worked fine , create a custom JPARepository and have below sample method logic.
public <S extends T> void saveInBatch(Iterable<S> entities) {
if (entities == null) {
return;
}
EntityManager entityManager = entityManagerFactory.createEntityManager();
EntityTransaction entityTransaction = entityManager.getTransaction();
try {
entityTransaction.begin();
int i = 0;
for (S entity : entities) {
if (i % batchSize == 0 && i > 0) {
entityTransaction.commit();
entityTransaction.begin();
entityManager.clear();
}
entityManager.persist(entity);
i++;
}
entityTransaction.commit();
} catch (RuntimeException e) {
if (entityTransaction.isActive()) {
entityTransaction.rollback();
}
throw e;
} finally {
entityManager.close();
}
}
}
When dealing with converting datasets that big you need to do that in batches. Read 100 records from the xml, convert them to entities, save each of them with em.persist(record), then call em.flush() and em.clear() to remove them from Hibernate, then clear them from your local collection, then manually invoke the garbage collector using System.gc(). You may even want to use Hibernate's batch processing as described in this tutorial.
In pseudocode this would be:
boolean finished = false;
List<Entity> locals = new ArrayList<>(100);
while (!finished) {
for (int records = 0; records < 100; records++) {
Entity ent = readEntityFrom(xml);
// readEntity function must return null when no more remain to read
if (ent == null) {
finished = true;
break;
}
locals.add(ent);
}
for (Entity ent : locals) em.persist(ent);
em.flush(); // send any that are still waiting to the database
em.clear(); // remove references Hibernate holds to these entities
locals.clear(); // remove references we hold to these entities
// now all these entity references are weak and can be garbage-collected
System.gc(); // purge them from memory
}
Also you may want to manually begin and commit a transaction around each insert loop to ensure the database isn't holding everything for your entire import, or it might run out of memory instead of your java application.

Why does #JoinColumn with POJO throw IllegalStateException

I have an error when start my Spring Boot Application: java.lang.IllegalStateException: Expected to be able to resolve a type but got null! This usually stems from types implementing raw Map or Collection interfaces!
I created two tables via sql query:
create table experiment_results
(
id int8 not null,
model jsonb,
train_errors jsonb,
test_errors jsonb,
prediction_error float8,
prediction_result jsonb,
prediction_report_file text,
creation_date timestamp NOT NULL,
PRIMARY KEY (id)
);
create table experiments
(
id int8 not null,
name text not null,
normalized_file text,
normalization_method varchar(255),
normalization_statistic jsonb,
neat_settings jsonb,
columns jsonb,
prediction_window_size int4,
prediction_period int4,
fk_project_id int8 not null,
creation_date timestamp not null,
updated_date timestamp not null,
train_end_index int4,
test_end_index int4,
fk_experiment_result_id int8,
PRIMARY KEY (id)
);
ALTER TABLE if EXISTS experiments add CONSTRAINT project_experiment_fk FOREIGN KEY(fk_project_id) references projects;
ALTER TABLE if EXISTS experiments add CONSTRAINT experiment_reuslt_fk FOREIGN KEY (fk_experiment_result_id) references experiment_results;
After that i created two POJO classes for them:
ExperimentResult:
#Data
#Entity
#NoArgsConstructor
#AllArgsConstructor
#Builder(toBuilder = true)
#Table(name = "experiment_results", schema = "public")
#TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
#JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id"
)
public class ExperimentResult {
#Id
#SequenceGenerator(name = "EXPERIMENT_RESULT_ID_GEN", sequenceName = "experiment_result_id_sequence", allocationSize = 1, schema = "public")
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "EXPERIMENT_RESULT_ID_GEN")
#Column(name = "id")
private Long id;
#Basic
#Column(name = "model", columnDefinition = "jsonb")
#Type(type = "jsonb")
private Map model;
#Column(name = "train_errors", columnDefinition = "jsonb")
#Type(type = "jsonb")
private List<Map<String, Object>> trainErrors;
#Column(name = "test_errors", columnDefinition = "jsonb")
#Type(type = "jsonb")
private List<Map<String, Object>> testErrors;
#Basic
#Column(name = "prediction_error")
private Double predictionError;
#Basic
#Column(name = "creation_date", nullable = false)
private LocalDateTime creationDate;
#Basic
#Column(name = "prediction_reporAt_file")
private String predictionReportFile;
}
Experiment:
#Data
#Entity
#NoArgsConstructor
#AllArgsConstructor
#Builder(toBuilder = true)
#Table(name = "experiments", schema = "public")
#TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
#JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id"
)
public class Experiment {
#Id
#SequenceGenerator(name = "EXPERIMENT_ID_GEN", sequenceName = "experiment_id_sequence", allocationSize = 1, schema = "public")
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "EXPERIMENT_ID_GEN")
#Column(name = "id")
#JsonView(ExperimentView.Id.class)
private Long id;
#Basic
#Column(name = "name")
#JsonView(ExperimentView.Info.class)
private String name;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "fk_project_id", referencedColumnName = "id", nullable = false)
#JsonIgnore
private Project project;
#Basic
#Column(name = "normalized_file")
#JsonIgnore
private String normalizedDataFile;
#Basic
#Column(name = "normalization_method")
#JsonView(ExperimentView.FullInfo.class)
private String normalizationMethod;
#Basic
#Column(name = "normalization_statistic", columnDefinition = "jsonb")
#Type(type = "jsonb")
#JsonView(ExperimentView.FullInfo.class)
private Map<String, Object> normalization_statistic;
#Basic
#Column(name = "neat_settings", columnDefinition = "jsonb")
#Type(type = "jsonb")
#JsonView(ExperimentView.FullInfo.class)
private List<Map<String, Object>> neatSettings;
#Basic
#Column(name = "columns", columnDefinition = "jsonb")
#Type(type = "jsonb")
#JsonView(ExperimentView.FullInfo.class)
private List<Map<String, Object>> columns;
#Basic
#Column(name = "prediction_window_size")
#JsonView(ExperimentView.FullInfo.class)
private Short predictionWindowSize;
#Basic
#Column(name = "prediction_period")
#JsonView(ExperimentView.FullInfo.class)
private Short predictionPeriod;
#Basic
#Column(name = "creation_date", nullable = false)
#JsonView(ExperimentView.Info.class)
private LocalDateTime creationDate;
#Basic
#Column(name = "updated_date", nullable = false)
#JsonView(ExperimentView.Info.class)
private LocalDateTime updatedDate;
#OneToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "fk_experiment_result_id", referencedColumnName = "id")
private ExperimentResult experimentResult;
}
While application is starting, it fails with stacktrace:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'experimentRepository' defined in ru.filippov.neat.repository.ExperimentRepository defined in #EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Expected to be able to resolve a type but got null! This usually stems from types implementing raw Map or Collection interfaces!
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1794) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:324) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$$Lambda$209/0000000000000000.getObject(Unknown Source) ~[na:na]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:624) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:612) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.data.repository.config.DeferredRepositoryInitializationListener.onApplicationEvent(DeferredRepositoryInitializationListener.java:51) ~[spring-data-commons-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.repository.config.DeferredRepositoryInitializationListener.onApplicationEvent(DeferredRepositoryInitializationListener.java:36) ~[spring-data-commons-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172) ~[spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165) ~[spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139) ~[spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:404) ~[spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:361) ~[spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:898) ~[spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:554) ~[spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143) ~[spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758) ~[spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750) ~[spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) ~[spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) ~[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 ru.filippov.neat.NeatvueApplication.main(NeatvueApplication.java:11) ~[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.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.3.4.RELEASE.jar:2.3.4.RELEASE]
Caused by: java.lang.IllegalStateException: Expected to be able to resolve a type but got null! This usually stems from types implementing raw Map or Collection interfaces!
at org.springframework.data.util.TypeInformation.getRequiredActualType(TypeInformation.java:184) ~[spring-data-commons-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.mapping.model.AbstractPersistentProperty.getActualType(AbstractPersistentProperty.java:286) ~[spring-data-commons-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.jpa.mapping.JpaPersistentPropertyImpl.getActualType(JpaPersistentPropertyImpl.java:120) ~[spring-data-jpa-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.jpa.mapping.JpaPersistentPropertyImpl.lambda$new$3(JpaPersistentPropertyImpl.java:111) ~[spring-data-jpa-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.jpa.mapping.JpaPersistentPropertyImpl$$Lambda$718/0000000000000000.get(Unknown Source) ~[na:na]
at org.springframework.data.util.Lazy.getNullable(Lazy.java:212) ~[spring-data-commons-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.util.Lazy.get(Lazy.java:94) ~[spring-data-commons-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.jpa.mapping.JpaPersistentPropertyImpl.isEntity(JpaPersistentPropertyImpl.java:150) ~[spring-data-jpa-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.mapping.model.AbstractPersistentProperty.getPersistentEntityTypes(AbstractPersistentProperty.java:150) ~[spring-data-commons-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.jpa.mapping.JpaPersistentPropertyImpl.getPersistentEntityTypes(JpaPersistentPropertyImpl.java:132) ~[spring-data-jpa-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.createAndRegisterProperty(AbstractMappingContext.java:562) ~[spring-data-commons-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.doWith(AbstractMappingContext.java:520) ~[spring-data-commons-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.util.ReflectionUtils.doWithFields(ReflectionUtils.java:705) ~[spring-core-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:389) ~[spring-data-commons-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator$$Lambda$723/0000000000000000.accept(Unknown Source) ~[na:na]
at java.base/java.util.Collections$SingletonSet.forEach(Collections.java:4797) ~[na:na]
at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.createAndRegisterProperty(AbstractMappingContext.java:562) ~[spring-data-commons-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.doWith(AbstractMappingContext.java:520) ~[spring-data-commons-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.util.ReflectionUtils.doWithFields(ReflectionUtils.java:705) ~[spring-core-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:389) ~[spring-data-commons-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:263) ~[spring-data-commons-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:206) ~[spring-data-commons-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:90) ~[spring-data-commons-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$4(RepositoryFactoryBeanSupport.java:295) ~[spring-data-commons-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport$$Lambda$663/0000000000000000.accept(Unknown Source) ~[na:na]
at java.base/java.util.Optional.ifPresent(Optional.java:183) ~[na:na]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:295) ~[spring-data-commons-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:144) ~[spring-data-jpa-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1853) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1790) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
... 31 common frames omitted
After that i removed ExperimentResult field from Experiment POJO and my application started succesfully. What i'm doing wrong? For example, fk_project_id works fine, but it have #ManyToOne annotation.
JSONB is not directly supported by Hibernate.
You have to use a converter.
There is a collection of converters in Hibernate Types project: https://github.com/vladmihalcea/hibernate-types
The problem was private Map model; in ExperimentResult POJO.
We MUST define generics, for example Map<String, Object> model

JPA Issues #OneToMany(MappedBy)

I have this issue with these models in my project and I don't know what is the issue exactly with these two models and these two realationships in Data JPA Car Model Below:
package com.wq.v1.domain.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Set;
#Entity
#Table(name = "cars")
#Getter
#Setter
public class Car implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(nullable = false, updatable = false)
#JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private long id;
#ManyToOne
#JoinColumn(name="firm_id", nullable=false)
private Firm firm;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "driver_id", referencedColumnName = "id")
private Driver driver;
#Column(name = "car_type")
private String car_type;
#Column(name = "car_model")
private String car_model;
#Column(name = "car_plate")
private String car_plate;
#Column(name = "car_owner")
private String car_owner;
#OneToMany(mappedBy="cars")
#JsonIgnore
private Set<Image> images;
#OneToMany(mappedBy="cars")
#JsonIgnore
private Set<Docs> docs;
public Car(){
}
public Car(Firm firm, Driver driver, String car_type, String car_model, String car_plate, String car_owner, Set<Image> images, Set<Docs> docs) {
this.firm = firm;
this.driver = driver;
this.car_type = car_type;
this.car_model = car_model;
this.car_plate = car_plate;
this.car_owner = car_owner;
this.images = images;
this.docs = docs;
}
}
And this is the Docs model:
package com.wq.v1.domain.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.io.Serializable;
#Entity
#Table(name = "docs")
#Getter
#Setter
public class Docs implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(nullable = false, updatable = false)
#JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private long id;
#ManyToOne
#JoinColumn(name = "driver_id", nullable = false)
private Driver driver;
#ManyToOne
#JoinColumn(name="car_id", nullable=false)
private Car car;
#Column(name = "nat_id", columnDefinition = "LONGTEXT")
private String nat_id;
#Column(name = "passport", columnDefinition = "LONGTEXT")
private String passport;
#Column(name = "driver_license", columnDefinition = "LONGTEXT")
private String driver_license;
#Column(name = "resd_id", columnDefinition = "LONGTEXT")
private String resd_id;
#Column(name = "resd_permit", columnDefinition = "LONGTEXT")
private String resd_permit;
#Column(name = "car_register", columnDefinition = "LONGTEXT")
private String car_register;
#Column(name = "disclaim", columnDefinition = "LONGTEXT")
private String disclaim;
#Column(name = "trans_autho", columnDefinition = "LONGTEXT")
private String trans_autho;
public Docs(){
}
public Docs(Driver driver, Car car, String nat_id, String passport, String driver_license, String resd_id, String resd_permit, String car_register, String disclaim, String trans_autho) {
this.driver = driver;
this.car = car;
this.nat_id = nat_id;
this.passport = passport;
this.driver_license = driver_license;
this.resd_id = resd_id;
this.resd_permit = resd_permit;
this.car_register = car_register;
this.disclaim = disclaim;
this.trans_autho = trans_autho;
}
}
And finally this is the error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: com.wq.v1.domain.model.Docs.cars in com.wq.v1.domain.model.Car.docs
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1788) ~[spring-beans-5.3.3.jar:5.3.3]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:609) ~[spring-beans-5.3.3.jar:5.3.3]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:531) ~[spring-beans-5.3.3.jar:5.3.3]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.3.jar:5.3.3]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.3.jar:5.3.3]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.3.jar:5.3.3]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.3.jar:5.3.3]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1159) ~[spring-context-5.3.3.jar:5.3.3]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913) ~[spring-context-5.3.3.jar:5.3.3]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:588) ~[spring-context-5.3.3.jar:5.3.3]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:144) ~[spring-boot-2.4.2.jar:2.4.2]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:767) ~[spring-boot-2.4.2.jar:2.4.2]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) ~[spring-boot-2.4.2.jar:2.4.2]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:426) ~[spring-boot-2.4.2.jar:2.4.2]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:326) ~[spring-boot-2.4.2.jar:2.4.2]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1311) ~[spring-boot-2.4.2.jar:2.4.2]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1300) ~[spring-boot-2.4.2.jar:2.4.2]
at com.wq.v1.V1Application.main(V1Application.java:21) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64) ~[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:564) ~[na:na]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.4.2.jar:2.4.2]
Caused by: org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: com.wq.v1.domain.model.Docs.cars in com.wq.v1.domain.model.Car.docs
at org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:844) ~[hibernate-core-5.4.27.Final.jar:5.4.27.Final]
at org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(CollectionBinder.java:795) ~[hibernate-core-5.4.27.Final.jar:5.4.27.Final]
at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:53) ~[hibernate-core-5.4.27.Final.jar:5.4.27.Final]
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1693) ~[hibernate-core-5.4.27.Final.jar:5.4.27.Final]
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1661) ~[hibernate-core-5.4.27.Final.jar:5.4.27.Final]
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:295) ~[hibernate-core-5.4.27.Final.jar:5.4.27.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:1224) ~[hibernate-core-5.4.27.Final.jar:5.4.27.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1255) ~[hibernate-core-5.4.27.Final.jar:5.4.27.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) ~[spring-orm-5.3.3.jar:5.3.3]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.3.3.jar:5.3.3]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:409) ~[spring-orm-5.3.3.jar:5.3.3]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:396) ~[spring-orm-5.3.3.jar:5.3.3]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.3.3.jar:5.3.3]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1847) ~[spring-beans-5.3.3.jar:5.3.3]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1784) ~[spring-beans-5.3.3.jar:5.3.3]
... 22 common frames omitted
Process finished with exit code 0
I searched a lot a tried many ways to fix it and didn't work even here I found a lot of questions without solving in here.

Spring JPA 2 nested many to many relationship

I am having a problem with my many to many relationship. Basically, here is what I am trying to do.
I have 2 many to many tables that are nested, as seen on the following image.
Db diagram
When compiling my code, I get the following error:
Caused by: java.sql.SQLSyntaxErrorException: Unknown column 'weeks0_.employee_project_employee_id' in 'field list'
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120) ~[mysql-connector-java-8.0.18.jar:8.0.18]
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.18.jar:8.0.18]
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.18.jar:8.0.18]
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953) ~[mysql-connector-java-8.0.18.jar:8.0.18]
at com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1003) ~[mysql-connector-java-8.0.18.jar:8.0.18]
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52) ~[HikariCP-3.4.1.jar:na]
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java) ~[HikariCP-3.4.1.jar:na]
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:57) ~[hibernate-core-5.4.6.Final.jar:5.4.6.Final]
So I understand that I have a problem with the weeks.
here are my entities:
Week:
package com.achsogo.rpt.entity;
import javax.persistence.*;
import java.util.Set;
#Entity
#Table(name="week")
public class Week {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private int weekNumber;
private int year;
#OneToMany(mappedBy = "week", cascade = CascadeType.ALL, orphanRemoval = true, fetch =
FetchType.EAGER)
private Set<EmployeeProjectWeek> employeeProjects;
public Week() {
}
public Week(int weekNumber, int year) {
this.weekNumber = weekNumber;
this.year = year;
} //Getter and Setters
Project:
import javax.persistence.*;
import java.util.*;
#Entity
#Table(name = "project")
public class Project {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String alias;
private String pspElement;
private int contractValue;
private int plannedCost;
private int plannedHours;
private int assignedHours;
private Date startDate;
private Date endDate;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "project", orphanRemoval = true, fetch =
FetchType.EAGER)
private Set<ProjectAP> projectAPS;
#ManyToOne
private Department department;
#OneToMany(mappedBy = "project", cascade = CascadeType.ALL, orphanRemoval = true, fetch =
FetchType.EAGER)
private Set<EmployeeProject> employees;
//Empty constructor
public Project(){}
//constructor for new project with default names
public Project(String alias){
this.alias = alias;
}
Employee:
#Entity
#Table(name = "employee")
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
private String email;
private int employeeNumber;
private String acronym;
private int availability;
#OneToMany(mappedBy = "employee", cascade = CascadeType.ALL, orphanRemoval = true, fetch =
FetchType.EAGER)
private Set<EmployeeProject> projects;
#ManyToOne
private Department department;
#ManyToOne
private Role role;
Table between Project and Employee (with the class to create the ID):
EmployeeProjectID:
#Embeddable
public class EmployeeProjectId implements Serializable {
private Long projectId;
private Long employeeId;
private EmployeeProjectId(){}
public EmployeeProjectId(Long projectId, Long employeeId){
this.employeeId = employeeId;
this.projectId = projectId;
}
EmployeeProject: It is here that the weeks are being called (If I am not mistaken)
#Entity
#Table(name = "project_employee")
public class EmployeeProject {
#EmbeddedId
private EmployeeProjectId id;
#ManyToOne(fetch = FetchType.EAGER)
#MapsId("projectId")
private Project project;
#ManyToOne(fetch = FetchType.EAGER)
#MapsId("employeeId")
private Employee employee;
#Column(name = "amount_time")
private int amountTime = 0;
#Column(name = "is_project_leader")
private boolean isProjectLeader = false;
#OneToMany(mappedBy = "employeeProject", cascade = CascadeType.ALL, orphanRemoval = true, fetch =
FetchType.EAGER)
private Set<EmployeeProjectWeek> weeks;
public EmployeeProject(){}
And now the table between Week and Employee Project:
EmployeeProjectWeekId: To create the ID for the nested many to many table:
#Embeddable
public class EmployeeProjectWeekId implements Serializable {
private EmployeeProjectId employeeProjectId;
private Long weekId;
private EmployeeProjectWeekId(){}
And finally the EmployeeProjectweek:
#Entity
#Table(name="project_employee_week")
public class EmployeeProjectWeek {
#EmbeddedId
private EmployeeProjectWeekId id;
#ManyToOne(fetch = FetchType.EAGER)
#MapsId("weekId")
private Week week;
#ManyToOne(fetch = FetchType.EAGER)
#MapsId("employeeProjectId")
private EmployeeProject employeeProject;
#Column(name="amount_time")
private int amountTime = 0;
#Column(name="is_project_leader")
private boolean isProjectLeader= false;
public EmployeeProjectWeek(Week week, EmployeeProject employeeProject) {
this.week = week;
this.employeeProject = employeeProject;
this.id = new EmployeeProjectWeekId(employeeProject.getId(), week.getId());
}
Does anyone has a clue where I have done an error? Thanks in advance for your time!
It was a naming problem. I solved this by dropping all the tables in my DB and having Spring to automatically generate the tables. Now everything works well.
I entered the following lines in my application.properties:
spring.jpa.hibernate.ddl=true
spring.jpa.hibernate.ddl-auto=update

Spring mapping using hibernate

I am joining two table using one to many relationship
my first table is role and second is roleCompany. where role_id is reference key in roleCompany table.
But when I am writting query to get all companies for specific id it showing me following error
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/myproject] threw exception [Request processing failed; nested exception is org.hibernate.PropertyAccessException: could not get a field value by reflection getter of com.test.myproject.domain.entity.RoleEntity.id] with root cause
java.lang.IllegalArgumentException: Can not set java.lang.Long field com.test.myproject.domain.entity.RoleEntity.id to java.lang.Long
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58)
at sun.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36)
My RoleEntity Class is :
#Entity
#Table(name = "roles")
public class RoleEntity {
#Id
#Getter
#Setter
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", unique = true, nullable = false)
private Long id;
#Getter
#Setter
#Column(name = "role", nullable = false)
private String role;
#Getter
#Setter
#OneToMany(mappedBy = "roles")
List<RoleCompanyEntity> companyentities;
}
and my RoleCompanyEntity is
#NamedQueries({
#NamedQuery(name = RoleCompanyEntity.FIND_ROLE_COMPANY_BY_ROLE_ID, query = "select r.companyId, r.companyName from RoleCompanyEntity r where r.roles =:roleId")
})
#Entity
#Table(name = "role_company")
public class RoleCompanyEntity {
public static final String FIND_ROLE_COMPANY_BY_ROLE_ID = "findRoleCompanyByRoleId";
#Id
#Getter
#Setter
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "company_id", unique = true, nullable = false)
private Long companyId;
#Getter
#Setter
#Column(name = "company_name", unique = true, nullable = false)
private String companyName;
#Getter
#Setter
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name="role_id", nullable=false)
private RoleEntity roles;
}

Resources