javax.persistence.RollbackException: Error while committing the transaction in Eclipse - jpa

I'm trying to create an application in JPA using Eclipse . the UML model of the application is the following :
enter image description here
And I have the error in class called "GRADETEST.java" in the function shouldSaveGrade() .
In this function I create variable grade final var grade = Fixtures.createGrade(subject).
before doing this I initialize a variable called subject which is fictitious . So when I do Junit test it crashes at the line
"entityManager.getTransaction().commit();"
I send to you Grade , subject , GRADETEST ,SubjectTest classes .
I'm new in this domain so I don't know why does this error appears .
javax.persistence.RollbackException: Error while committing the transaction
at org.hibernate.internal.ExceptionConverterImpl.convertCommitException(ExceptionConverterImpl.java:81)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:104)
at fr.uga.im2ag.l3.miage.db.repository.GradeTest.shouldSaveGrade(GradeTest.java:51)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:725)
at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:214)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:210)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:66)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:95)
at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:91)
at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:60)
at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:98)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:40)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:529)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:756)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:452)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:154)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181)
at org.hibernate.internal.ExceptionConverterImpl.convertCommitException(ExceptionConverterImpl.java:65)
... 71 more
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:59)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:37)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:200)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:46)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3375)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3908)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:107)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:604)
at org.hibernate.engine.spi.ActionQueue.lambda$executeActions$1(ActionQueue.java:478)
at java.base/java.util.LinkedHashMap.forEach(LinkedHashMap.java:684)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:475)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:344)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:40)
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1402)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:493)
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3285)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2420)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:449)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:183)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:40)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:281)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:101)
... 70 more
Caused by: org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: Intégrité référentielle violation de contrainte: "FKEP37YMUXQE45LFAYSRIMBRS2A: PUBLIC.GRADE FOREIGN KEY(SUBJECT_ID) REFERENCES PUBLIC.SUBJECT(ID) (CAST(1 AS BIGINT))"
Referential integrity constraint violation: "FKEP37YMUXQE45LFAYSRIMBRS2A: PUBLIC.GRADE FOREIGN KEY(SUBJECT_ID) REFERENCES PUBLIC.SUBJECT(ID) (CAST(1 AS BIGINT))"; SQL statement:
insert into Grade (subject_id, gradevalue, weight, id) values (?, ?, ?, ?) [23506-210]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:527)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:496)
at org.h2.message.DbException.get(DbException.java:227)
at org.h2.message.DbException.get(DbException.java:203)
at org.h2.constraint.ConstraintReferential.checkRowOwnTable(ConstraintReferential.java:311)
at org.h2.constraint.ConstraintReferential.checkRow(ConstraintReferential.java:252)
at org.h2.table.Table.fireConstraints(Table.java:1177)
at org.h2.table.Table.fireAfterRow(Table.java:1195)
at org.h2.command.dml.Insert.insertRows(Insert.java:188)
at org.h2.command.dml.Insert.update(Insert.java:135)
at org.h2.command.dml.DataChangeStatement.update(DataChangeStatement.java:61)
at org.h2.command.CommandContainer.update(CommandContainer.java:174)
at org.h2.command.Command.executeUpdate(Command.java:252)
at org.h2.jdbc.JdbcPreparedStatement.executeUpdateInternal(JdbcPreparedStatement.java:209)
at org.h2.jdbc.JdbcPreparedStatement.executeUpdate(JdbcPreparedStatement.java:169)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:197)
... 90 more
//GradeTEST
package fr.uga.im2ag.l3.miage.db.repository;
import java.sql.Date;
import java.time.LocalDate;
import fr.uga.im2ag.l3.miage.db.repository.api.GradeRepository;
import fr.uga.im2ag.l3.miage.db.repository.api.SubjectRepository;
import fr.uga.im2ag.l3.miage.db.model.*;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class GradeTest extends Base {
GradeRepository gradeRepository;
#BeforeEach
void before() {
gradeRepository = daoFactory.newGradeRepository(entityManager);
}
#AfterEach
void after() {
if (entityManager.getTransaction().isActive()) {
entityManager.getTransaction().rollback();
}
}
#Test
void shouldSaveGrade() {
// TODO
final var subject = Fixtures.createSubject();
subject.setId((long)1);
subject.setName("Math");
subject.setHours((float) 5.0);
// Create a date object
Date d = new Date(2022,2,28);
subject.setStart(d);
subject.setPoints(5);
subject.setEnd(d);
final var grade = Fixtures.createGrade(subject) ;
entityManager.getTransaction().begin();
gradeRepository.save(grade);
entityManager.getTransaction().commit();
entityManager.detach(grade);
var pGrade = gradeRepository.findById(grade.getId());
assertThat(pGrade).isNotNull().isNotSameAs(grade);
assertThat(pGrade.getValue()).isEqualTo(grade.getValue());
assertThat(pGrade.getWeight()).isEqualTo(grade.getWeight());
}
//Grade
package fr.uga.im2ag.l3.miage.db.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
//#Table(name="Grade")
// TODO ajouter une named query pour une des requêtes à faire dans le repository
public class Grade {
#Id
#GeneratedValue()
#Column(name = "id")
private Long id;
#ManyToOne
private Subject subject;
#Column(name = "gradevalue")
private Float value;
private Float weight;
public Long getId() {
return id;
}
public Subject getSubject() {
return subject;
}
public Grade setSubject(Subject subject) {
this.subject = subject;
return this;
}
public Float getValue() {
return value;
}
public Grade setValue(Float value) {
this.value = value;
return this;
}
public Float getWeight() {
return weight;
}
public Grade setWeight(Float weight) {
this.weight = weight;
return this;
}
}
//Subject
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;
#Entity
#Table(name = "Subject")
// TODO ajouter une named query pour une des requêtes à faire dans le repository
public class Subject {
#Id
#GeneratedValue()
#Column(name = "id",nullable=false)
private Long id;
private String name;
private Integer points;
private Float hours;
private Date start;
#Column(name = "end_date")
private Date end;
public Long getId() {
return id;
}
public Subject setId(Long id) {
this.id = id;
return this;
}
public String getName() {
return name;
}
public Subject setName(String name) {
this.name = name;
return this;
}
public Integer getPoints() {
return points;
}
public Subject setPoints(Integer points) {
this.points = points;
return this;
}
public Float getHours() {
return hours;
}
public Subject setHours(Float hours) {
this.hours = hours;
return this;
}
public Date getStart() {
return start;
}
public Subject setStart(Date start) {
this.start = start;
return this;
}
public Date getEnd() {
return end;
}
public Subject setEnd(Date end) {
this.end = end;
return this;
}
}

Referential integrity constraint violation: "FKEP37YMUXQE45LFAYSRIMBRS2A: PUBLIC.GRADE FOREIGN KEY(SUBJECT_ID) REFERENCES PUBLIC.SUBJECT(ID) (CAST(1 AS BIGINT))"; SQL statement: insert into Grade (subject_id, gradevalue, weight, id) values (?, ?, ?, ?)
Here Grade is dependent on Subject
and you're trying to save Grade without saving Subject
It'll work if you just save Subject
as Subject and Grade have a relation; it'll save Grade as well

Related

Why does id of child entity return 0 in response message in EclipseLink?

I'm using a One-To-One association between my Member and MemberRoles tables. I wanted them to share the same id as PK and FK in the database and did it. But I've got another problem. When I insert a Member, a MemberRole record is being inserted with it and Member record has the correct id in return response but MemberRole id is incorrect. It returns 0 like this:
{
"result": "Bulk user member saving is successfull. Members' informations are:",
"memberList": [
{
"id": 2,
"firstName": "Michael",
"lastName": "Schumacher",
"email": "ilkay.gune2l#kod5.org",
"enabled": false,
"memberLanguageCode": "tr",
"roleOfMember": {
"id": 0,
"email": "ilkay.gune2l#kod5.org",
"role": "ROLE_USER"
}
}
]
}
My Member Entity Class:
package com.ilkaygunel.entities;
import java.time.LocalDateTime;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
#Entity
#JsonInclude(Include.NON_NULL)
#NamedQueries({ #NamedQuery(name = "Member.findAll", query = "select m from Member m"),
#NamedQuery(name = "Member.findByFirstName", query = "select m from Member m where m.firstName =:firstName"),
#NamedQuery(name = "Member.findPasswordOfMember", query = "select m.password from Member m where m.id =:id"),
#NamedQuery(name = "Member.findByActivationToken", query = "select m from Member m where m.activationToken =:activationToken"),
#NamedQuery(name = "Member.findByEmail", query = "select m from Member m where m.email =:email") })
#Table(name = "MEMBER")
public class Member {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "MEMBER_ID")
private long id;
#Column(nullable = false)
private String firstName;
#Column(nullable = false)
private String lastName;
#Column(nullable = false, updatable = false)
private String email;
#Column(nullable = false, updatable = false)
private boolean enabled;
#Column(nullable = false)
private String password;
#Column(nullable = false)
private String memberLanguageCode;
#Column(updatable = false)
#JsonIgnore
private String activationToken;
#Column(updatable = false)
#JsonIgnore
private LocalDateTime activationTokenExpDate;
#OneToOne(cascade = CascadeType.ALL, mappedBy = "member", optional = false)
#PrimaryKeyJoinColumn(name = "MEMBER_ID")
private MemberRoles roleOfMember;
#Override
public String toString() {
return String.format("Member [id=%d, firstName='%s', lastName='%s', email='%s']", id, firstName, lastName,
email);
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
if (null != roleOfMember) {
roleOfMember.setId(id);
}
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public MemberRoles getRoleOfMember() {
return roleOfMember;
}
public void setRoleOfMember(MemberRoles roleOfMember) {
this.roleOfMember = roleOfMember;
}
public String getActivationToken() {
return activationToken;
}
public void setActivationToken(String activationToken) {
this.activationToken = activationToken;
}
public LocalDateTime getActivationTokenExpDate() {
return activationTokenExpDate;
}
public void setActivationTokenExpDate(LocalDateTime activationTokenExpDate) {
this.activationTokenExpDate = activationTokenExpDate;
}
public String getMemberLanguageCode() {
return memberLanguageCode;
}
public void setMemberLanguageCode(String memberLanguageCode) {
this.memberLanguageCode = memberLanguageCode;
}
}
And my MemberRoles Entity class:
package com.ilkaygunel.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.MapsId;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
#Entity
#NamedQueries({
#NamedQuery(name = "MemberRoles.findByEmail", query = "select mr from MemberRoles mr where mr.email = :email") })
#Table(name = "MEMBERROLES")
public class MemberRoles {
#Id
#Column(name = "MEMBERROLES_ID")
private long id;
private String email;
private String role;
#MapsId
#OneToOne(optional = false)
#JoinColumn(name = "MEMBERROLES_ID", unique = true, nullable = false, updatable = false)
#JsonIgnore
private Member member;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public Member getMember() {
return member;
}
public void setMember(Member member) {
this.member = member;
}
}
When I inserted a Member record, I check it on the database and see that Member and MemberRoles record have the same id. But why does MemberRoles area in response message has got id as 0?
My MemberSaveService class like this:
package com.ilkaygunel.service;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.MessagingException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import com.ilkaygunel.constants.ConstantFields;
import com.ilkaygunel.entities.Member;
import com.ilkaygunel.entities.MemberRoles;
import com.ilkaygunel.exception.CustomException;
import com.ilkaygunel.exception.ErrorCodes;
import com.ilkaygunel.pojo.MemberOperationPojo;
#Service
public class MemberSaveService extends BaseService {
public MemberOperationPojo addUserMember(List<Member> memberList) {
return addBulkMember(memberList, ConstantFields.ROLE_USER.getConstantField());
}
public MemberOperationPojo addAdminMember(List<Member> memberList) {
return addBulkMember(memberList, ConstantFields.ROLE_ADMIN.getConstantField());
}
public MemberOperationPojo addBulkMember(List<Member> memberList, String role) {
Logger LOGGER = loggingUtil.getLoggerForMemberSaving(this.getClass());
LOGGER.log(Level.INFO, resourceBundleMessageManager.getValueOfProperty(role + "_bulkMemberAddingMethod", "en"));
MemberOperationPojo memberOperationPojo = new MemberOperationPojo();
List<Member> savedMemberList = new ArrayList<>();
try {
memberUtil.checkEmailAddressAndLanguageOnMemberList(memberList, LOGGER);
for (Member member : memberList) {
addOneMember(member, role, LOGGER);
savedMemberList.add(member);
}
memberOperationPojo.setResult(
resourceBundleMessageManager.getValueOfProperty(role + "_bulkMemberAddingSuccessfull", "en"));
memberOperationPojo.setMemberList(memberUtil.removeFieldsFromReturningMember(savedMemberList));
LOGGER.log(Level.INFO,
resourceBundleMessageManager.getValueOfProperty(role + "_bulkMemberAddingSuccessfull", "en")
+ memberList);
} catch (CustomException customException) {
LOGGER.log(Level.SEVERE,
resourceBundleMessageManager.getValueOfProperty(role + "_bulkMemberAddingFaled", "en")
+ customException.getErrorCode() + " " + customException.getErrorMessage());
memberOperationPojo.setErrorCode(customException.getErrorCode());
memberOperationPojo.setResult(customException.getErrorMessage());
} catch (Exception e) {
LOGGER.log(Level.SEVERE,
resourceBundleMessageManager.getValueOfProperty(role + "_bulkMemberAddingFaled", "en")
+ e.getMessage());
memberOperationPojo.setErrorCode(ErrorCodes.ERROR_10.getErrorCode());
memberOperationPojo.setResult(e.getMessage());
}
return memberOperationPojo;
}
private void addOneMember(Member member, String role, Logger LOGGER) throws MessagingException {
MemberOperationPojo memberOperationPojo = new MemberOperationPojo();
LOGGER.log(Level.INFO, resourceBundleMessageManager.getValueOfProperty(role + "_memberAddingMethod",
member.getMemberLanguageCode()));
member.setPassword(getHashedPassword(member.getPassword()));
member.setEnabled(false);
addMemberRolesObject(role, member);
addActivationToken(member);
memberFacade.create(member);
// mailUtil.sendActivationMail(member.getEmail(), member.getActivationToken());
memberOperationPojo.setResult(resourceBundleMessageManager.getValueOfProperty(role + "_memberAddingSuccessfull",
member.getMemberLanguageCode()));
LOGGER.log(Level.INFO, resourceBundleMessageManager.getValueOfProperty(role + "_memberAddingSuccessfull",
member.getMemberLanguageCode()) + member);
}
private String getHashedPassword(String rawPassword) {
return new BCryptPasswordEncoder().encode(rawPassword);
}
private void addMemberRolesObject(String role, Member member) {
MemberRoles rolesOfMember = new MemberRoles();
rolesOfMember.setRole(role);
rolesOfMember.setEmail(member.getEmail());
rolesOfMember.setMember(member);
member.setRoleOfMember(rolesOfMember);
}
private void addActivationToken(Member member) {
String activationToken = UUID.randomUUID().toString();
member.setActivationToken(activationToken);
LocalDateTime activationTokenExpDate = LocalDateTime.now().plusDays(1);
// LocalDateTime activationTokenExpDate = LocalDateTime.now();//Use for expire
// date test!
member.setActivationTokenExpDate(activationTokenExpDate);
}
}
My Web Service End Point Class like this:
package com.ilkaygunel.restservice;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.ilkaygunel.entities.Member;
import com.ilkaygunel.pojo.MemberOperationPojo;
import com.ilkaygunel.service.MemberSaveService;
#RestController
#RequestMapping("/memberPostWebServiceEndPoint")
public class MemberSaveWebServiceEndPoint {
#Autowired
private MemberSaveService memberSaveService;
#RequestMapping(value = "/saveUserMember", method = RequestMethod.POST)
public ResponseEntity<MemberOperationPojo> saveUserMember(#RequestBody List<Member> memberList) {
MemberOperationPojo memberOperationPojo = memberSaveService.addUserMember(memberList);
return new ResponseEntity<MemberOperationPojo>(memberOperationPojo, HttpStatus.OK);
}
#RequestMapping(value = "/saveAdminMember", method = RequestMethod.POST)
public ResponseEntity<MemberOperationPojo> saveAdminMember(#RequestBody List<Member> memberList) {
MemberOperationPojo memberOperationPojo = memberSaveService.addAdminMember(memberList);
return new ResponseEntity<MemberOperationPojo>(memberOperationPojo, HttpStatus.OK);
}
}

Spring boot exception

I have created a spring boot project, and firstful i have created two entities with their Repository and metier interfaces and a restController and every thing was going well
location class:
package com.agence.entitises;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
#Entity
public class Location implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long NumLocation;
private Date DateCreation;
private String Categorie;
private String type;
#ManyToOne
#JoinColumn(name="NUM_LOCAT")
private Locataire locataire;
#ManyToOne
#JoinColumn(name="NUM_CONTRATS")
private Contrats contrats;
#ManyToOne
#JoinColumn(name="NUM_PERIODELOCATION")
private PerieodeLocation periodeLocation;
public Location(Long numLocation, Date dateCreation, String categorie,
String type, Locataire locataire, Contrats contrats,
PerieodeLocation periodeLocation) {
super();
NumLocation = numLocation;
DateCreation = dateCreation;
Categorie = categorie;
this.type = type;
this.locataire = locataire;
this.contrats = contrats;
this.periodeLocation = periodeLocation;
}
public PerieodeLocation getPeriodeLocation() {
return periodeLocation;
}
public void setPeriodeLocation(PerieodeLocation periodeLocation) {
this.periodeLocation = periodeLocation;
}
public Locataire getLocataire() {
return locataire;
}
public void setLocataire(Locataire locataire) {
this.locataire = locataire;
}
public Location(Long numLocation, Date dateCreation, String categorie,
String type) {
super();
NumLocation = numLocation;
DateCreation = dateCreation;
Categorie = categorie;
this.type = type;
}
public Location() {
super();
// TODO Auto-generated constructor stub
}
public Long getNumLocation() {
return NumLocation;
}
public void setNumLocation(Long numLocation) {
NumLocation = numLocation;
}
public Date getDateCreation() {
return DateCreation;
}
public void setDateCreation(Date dateCreation) {
DateCreation = dateCreation;
}
public String getCategorie() {
return Categorie;
}
public void setCategorie(String categorie) {
Categorie = categorie;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Contrats getContrats() {
return contrats;
}
public void setContrats(Contrats contrats) {
this.contrats = contrats;
}
}
Locataire class:
package com.agence.entitises;
import java.io.Serializable;
import java.sql.Date;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
#Entity
public class Locataire implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long NumLocataire ;
private Date dateCreation ;
private String raisonSociale ;
private String nomLocataire ;
private String prenomLocataire ;
private String ville ;
#OneToMany(mappedBy="locataire")
private List<Location> locations;
public Locataire(Long numLocataire, Date dateCreation,
String raisonSociale, String nomLocataire, String prenomLocataire,
String ville, List<Location> locations) {
super();
NumLocataire = numLocataire;
this.dateCreation = dateCreation;
this.raisonSociale = raisonSociale;
this.nomLocataire = nomLocataire;
this.prenomLocataire = prenomLocataire;
this.ville = ville;
this.locations = locations;
}
public String getPrenomLocataire() {
return prenomLocataire;
}
public void setPrenomLocataire(String prenomLocataire) {
this.prenomLocataire = prenomLocataire;
}
public String getVille() {
return ville;
}
public void setVille(String ville) {
this.ville = ville;
}
public List<Location> getLocations() {
return locations;
}
public void setLocations(List<Location> locations) {
this.locations = locations;
}
public Locataire(Long numLocataire, Date dateCreation,
String raisonSociale, String nomLocataire) {
super();
NumLocataire = numLocataire;
this.dateCreation = dateCreation;
this.raisonSociale = raisonSociale;
this.nomLocataire = nomLocataire;
}
public Locataire() {
super();
// TODO Auto-generated constructor stub
}
public Long getNumLocataire() {
return NumLocataire;
}
public void setNumLocataire(Long numLocataire) {
NumLocataire = numLocataire;
}
public Date getDateCreation() {
return dateCreation;
}
public void setDateCreation(Date dateCreation) {
this.dateCreation = dateCreation;
}
public String getRaisonSociale() {
return raisonSociale;
}
public void setRaisonSociale(String raisonSociale) {
this.raisonSociale = raisonSociale;
}
public String getNomLocataire() {
return nomLocataire;
}
public void setNomLocataire(String nomLocataire) {
this.nomLocataire = nomLocataire;
}
}
the Repository Interfaces:
package com.agence.Dao;
import org.springframework.data.jpa.repository.JpaRepository;
import com.agence.entitises.Locataire;
public interface ILocataireRepository extends JpaRepository<Locataire, Long>{
}
package com.agence.Dao;
import org.springframework.data.jpa.repository.JpaRepository;
import com.agence.entitises.Location;
public interface ILocationRepository extends JpaRepository<Location, Long> {
}
LocataireMetier
package com.agence.Metier;
import java.util.List;
import com.agence.entitises.Locataire;
public interface LocataireMetier {
public Locataire saveLocataire(Locataire locataire) ;
public List<Locataire > listeLocataires();
}
LocataireMetierImpl:
package com.agence.Metier;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.agence.Dao.ILocataireRepository;
import com.agence.entitises.Locataire;
#Service
public class LocataireMetierImpl implements LocataireMetier{
#Autowired
private ILocataireRepository locataireRepository ;
#Override
public Locataire saveLocataire(Locataire locataire) {
// TODO Auto-generated method stub
return locataireRepository.save(locataire);
}
#Override
public List<Locataire> listeLocataires() {
// TODO Auto-generated method stub
return locataireRepository.findAll();
}
}
LocataireMetier :
package com.agence.Metier;
import java.util.List;
import com.agence.entitises.Location;
public interface LocationMetier {
public Location saveLocation(Location loc);
public List<Location> listeLocation() ;
}
LocationMetierImpl:
package com.agence.Metier;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.agence.Dao.ILocationRepository;
import com.agence.entitises.Location;
#Service
public class LocationMetierImpl implements LocationMetier{
#Autowired
private ILocationRepository clientRepository ;
#Override
public Location saveLocation(Location loc) {
// TODO Auto-generated method stub
return clientRepository.save(loc);
}
#Override
public List<Location> listeLocation() {
// TODO Auto-generated method stub
return clientRepository.findAll();
}
}
The RestController:
package com.agence.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.agence.Metier.LocataireMetier;
import com.agence.Metier.LocationMetier;
import com.agence.entitises.Locataire;
import com.agence.entitises.Location;
#RestController
public class LocationRestService {
#Autowired
private LocationMetier locationMetier ;
private LocataireMetier locataireMetier ;
#RequestMapping(value="/Locations" ,method=RequestMethod.POST)
public Location saveLocation( #RequestBody Location loc) {
return locationMetier.saveLocation(loc);
}
#RequestMapping(value="/Locations" ,method=RequestMethod.GET)
public List<Location> listeLocation() {
return locationMetier.listeLocation();
}
#RequestMapping(value="/Locataires" ,method=RequestMethod.POST)
public Locataire saveLocataire( #RequestBody Locataire locataire) {
return locataireMetier.saveLocataire( locataire);
}
#RequestMapping(value="/Locataires" ,method=RequestMethod.GET)
public List<Locataire> listeLocataires() {
return locataireMetier.listeLocataires();
}
}
at this case everything works, but when i added the following entities:
Contrats:
package com.agence.entitises;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
#Entity
public class Contrats implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long NumContrat ;
private String EtatContrat ;
private Date dateCreation ;
private String referencePeriode ;
private String referenceLocataire ;
#OneToMany(mappedBy="Contrats")
private List<Location> locations;
public Contrats(Long numContrat, String etatContrat, Date dateCreation) {
super();
NumContrat = numContrat;
EtatContrat = etatContrat;
this.dateCreation = dateCreation;
}
public List<Location> getLocations() {
return locations;
}
public void setLocations(List<Location> locations) {
this.locations = locations;
}
public Long getNumContrat() {
return NumContrat;
}
public void setNumContrat(Long numContrat) {
NumContrat = numContrat;
}
public String getEtatContrat() {
return EtatContrat;
}
public void setEtatContrat(String etatContrat) {
EtatContrat = etatContrat;
}
public Date getDateCreation() {
return dateCreation;
}
public void setDateCreation(Date dateCreation) {
this.dateCreation = dateCreation;
}
public String getReferencePeriode() {
return referencePeriode;
}
public void setReferencePeriode(String referencePeriode) {
this.referencePeriode = referencePeriode;
}
public String getReferenceLocataire() {
return referenceLocataire;
}
public void setReferenceLocataire(String referenceLocataire) {
this.referenceLocataire = referenceLocataire;
}
public Contrats() {
super();
// TODO Auto-generated constructor stub
}
public Contrats(Long numContrat, String etatContrat, Date dateCreation,
String referencePeriode, String referenceLocataire) {
super();
NumContrat = numContrat;
EtatContrat = etatContrat;
this.dateCreation = dateCreation;
this.referencePeriode = referencePeriode;
this.referenceLocataire = referenceLocataire;
}
}
PriodeLocation:
package com.agence.entitises;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
#Entity
public class PerieodeLocation implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long numPeriode ;
private Long ReferenceLocation ;
private Date dateDebut ;
private Date dateFin ;
private double nombreSemaines ;
private String EtatPeriode ;
#OneToMany(mappedBy="PeriodeLocation")
private List<Location> locations ;
public PerieodeLocation(Long numPeriode, Long referenceLocation,
Date dateDebut, Date dateFin, double nombreSemaines,
String etatPeriode, List<Location> locations) {
super();
this.numPeriode = numPeriode;
ReferenceLocation = referenceLocation;
this.dateDebut = dateDebut;
this.dateFin = dateFin;
this.nombreSemaines = nombreSemaines;
EtatPeriode = etatPeriode;
this.locations = locations;
}
public List<Location> getLocations() {
return locations;
}
public void setLocations(List<Location> locations) {
this.locations = locations;
}
public PerieodeLocation() {
super();
// TODO Auto-generated constructor stub
}
public Long getNumPeriode() {
return numPeriode;
}
public void setNumPeriode(Long numPeriode) {
this.numPeriode = numPeriode;
}
public Long getReferenceLocation() {
return ReferenceLocation;
}
public void setReferenceLocation(Long referenceLocation) {
ReferenceLocation = referenceLocation;
}
public Date getDateDebut() {
return dateDebut;
}
public void setDateDebut(Date dateDebut) {
this.dateDebut = dateDebut;
}
public Date getDateFin() {
return dateFin;
}
public void setDateFin(Date dateFin) {
this.dateFin = dateFin;
}
public double getNombreSemaines() {
return nombreSemaines;
}
public void setNombreSemaines(double nombreSemaines) {
this.nombreSemaines = nombreSemaines;
}
public String getEtatPeriode() {
return EtatPeriode;
}
public void setEtatPeriode(String etatPeriode) {
EtatPeriode = etatPeriode;
}
}
when i execute the app it returns this exception:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1054) ~[spring-context-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:829) ~[spring-context-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538) ~[spring-context-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) ~[spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:766) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
at org.springframework.boot.SpringApplication.createAndRefreshContext(SpringApplication.java:361) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1191) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1180) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
at com.agence.AgenceTouristique2Application.main(AgenceTouristique2Application.java:13) [classes/:na]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:1249) ~[hibernate-entitymanager-4.3.11.Final.jar:4.3.11.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.access$600(EntityManagerFactoryBuilderImpl.java:120) ~[hibernate-entitymanager-4.3.11.Final.jar:4.3.11.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:860) ~[hibernate-entitymanager-4.3.11.Final.jar:4.3.11.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850) ~[hibernate-entitymanager-4.3.11.Final.jar:4.3.11.Final]
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:425) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:849) ~[hibernate-entitymanager-4.3.11.Final.jar:4.3.11.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:343) ~[spring-orm-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:319) ~[spring-orm-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
... 16 common frames omitted
Caused by: org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: com.agence.entitises.Location.PeriodeLocation in com.agence.entitises.PerieodeLocation.locations
at org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:769) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
at org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(CollectionBinder.java:729) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:70) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
at org.hibernate.cfg.Configuration.originalSecondPassCompile(Configuration.java:1697) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1426) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1846) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:857) ~[hibernate-entitymanager-4.3.11.Final.jar:4.3.11.Final]
... 24 common frames omitted
2016-05-10 20:40:18.330 INFO 3148 --- [ main] .b.l.ClasspathLoggingApplicationListener : Application failed to start with classpath: [file:/C:/Users/Lemin/workspace/AgenceTouristique2/target/classes/, file:/C:/Users/Lemin/.m2/repository/org/springframework/boot/spring-boot-starter-data-jpa/1.3.3.RELEASE/spring-boot-starter-data-jpa-1.3.3.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/boot/spring-boot-starter/1.3.3.RELEASE/spring-boot-starter-1.3.3.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/boot/spring-boot/1.3.3.RELEASE/spring-boot-1.3.3.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/boot/spring-boot-autoconfigure/1.3.3.RELEASE/spring-boot-autoconfigure-1.3.3.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/boot/spring-boot-starter-logging/1.3.3.RELEASE/spring-boot-starter-logging-1.3.3.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/ch/qos/logback/logback-classic/1.1.5/logback-classic-1.1.5.jar, file:/C:/Users/Lemin/.m2/repository/ch/qos/logback/logback-core/1.1.5/logback-core-1.1.5.jar, file:/C:/Users/Lemin/.m2/repository/org/slf4j/jul-to-slf4j/1.7.16/jul-to-slf4j-1.7.16.jar, file:/C:/Users/Lemin/.m2/repository/org/slf4j/log4j-over-slf4j/1.7.16/log4j-over-slf4j-1.7.16.jar, file:/C:/Users/Lemin/.m2/repository/org/yaml/snakeyaml/1.16/snakeyaml-1.16.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/boot/spring-boot-starter-aop/1.3.3.RELEASE/spring-boot-starter-aop-1.3.3.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/spring-aop/4.2.5.RELEASE/spring-aop-4.2.5.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/aopalliance/aopalliance/1.0/aopalliance-1.0.jar, file:/C:/Users/Lemin/.m2/repository/org/aspectj/aspectjweaver/1.8.8/aspectjweaver-1.8.8.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/boot/spring-boot-starter-jdbc/1.3.3.RELEASE/spring-boot-starter-jdbc-1.3.3.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/apache/tomcat/tomcat-jdbc/8.0.32/tomcat-jdbc-8.0.32.jar, file:/C:/Users/Lemin/.m2/repository/org/apache/tomcat/tomcat-juli/8.0.32/tomcat-juli-8.0.32.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/spring-jdbc/4.2.5.RELEASE/spring-jdbc-4.2.5.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/hibernate/hibernate-entitymanager/4.3.11.Final/hibernate-entitymanager-4.3.11.Final.jar, file:/C:/Users/Lemin/.m2/repository/org/jboss/logging/jboss-logging/3.3.0.Final/jboss-logging-3.3.0.Final.jar, file:/C:/Users/Lemin/.m2/repository/org/jboss/logging/jboss-logging-annotations/1.2.0.Beta1/jboss-logging-annotations-1.2.0.Beta1.jar, file:/C:/Users/Lemin/.m2/repository/org/hibernate/hibernate-core/4.3.11.Final/hibernate-core-4.3.11.Final.jar, file:/C:/Users/Lemin/.m2/repository/antlr/antlr/2.7.7/antlr-2.7.7.jar, file:/C:/Users/Lemin/.m2/repository/org/jboss/jandex/1.1.0.Final/jandex-1.1.0.Final.jar, file:/C:/Users/Lemin/.m2/repository/dom4j/dom4j/1.6.1/dom4j-1.6.1.jar, file:/C:/Users/Lemin/.m2/repository/xml-apis/xml-apis/1.0.b2/xml-apis-1.0.b2.jar, file:/C:/Users/Lemin/.m2/repository/org/hibernate/common/hibernate-commons-annotations/4.0.5.Final/hibernate-commons-annotations-4.0.5.Final.jar, file:/C:/Users/Lemin/.m2/repository/org/hibernate/javax/persistence/hibernate-jpa-2.1-api/1.0.0.Final/hibernate-jpa-2.1-api-1.0.0.Final.jar, file:/C:/Users/Lemin/.m2/repository/org/javassist/javassist/3.18.1-GA/javassist-3.18.1-GA.jar, file:/C:/Users/Lemin/.m2/repository/javax/transaction/javax.transaction-api/1.2/javax.transaction-api-1.2.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/data/spring-data-jpa/1.9.4.RELEASE/spring-data-jpa-1.9.4.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/data/spring-data-commons/1.11.4.RELEASE/spring-data-commons-1.11.4.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/spring-orm/4.2.5.RELEASE/spring-orm-4.2.5.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/spring-context/4.2.5.RELEASE/spring-context-4.2.5.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/spring-tx/4.2.5.RELEASE/spring-tx-4.2.5.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/spring-beans/4.2.5.RELEASE/spring-beans-4.2.5.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/slf4j/slf4j-api/1.7.16/slf4j-api-1.7.16.jar, file:/C:/Users/Lemin/.m2/repository/org/slf4j/jcl-over-slf4j/1.7.16/jcl-over-slf4j-1.7.16.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/spring-aspects/4.2.5.RELEASE/spring-aspects-4.2.5.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/boot/spring-boot-starter-web/1.3.3.RELEASE/spring-boot-starter-web-1.3.3.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/boot/spring-boot-starter-tomcat/1.3.3.RELEASE/spring-boot-starter-tomcat-1.3.3.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/apache/tomcat/embed/tomcat-embed-core/8.0.32/tomcat-embed-core-8.0.32.jar, file:/C:/Users/Lemin/.m2/repository/org/apache/tomcat/embed/tomcat-embed-el/8.0.32/tomcat-embed-el-8.0.32.jar, file:/C:/Users/Lemin/.m2/repository/org/apache/tomcat/embed/tomcat-embed-logging-juli/8.0.32/tomcat-embed-logging-juli-8.0.32.jar, file:/C:/Users/Lemin/.m2/repository/org/apache/tomcat/embed/tomcat-embed-websocket/8.0.32/tomcat-embed-websocket-8.0.32.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/boot/spring-boot-starter-validation/1.3.3.RELEASE/spring-boot-starter-validation-1.3.3.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/hibernate/hibernate-validator/5.2.4.Final/hibernate-validator-5.2.4.Final.jar, file:/C:/Users/Lemin/.m2/repository/javax/validation/validation-api/1.1.0.Final/validation-api-1.1.0.Final.jar, file:/C:/Users/Lemin/.m2/repository/com/fasterxml/classmate/1.1.0/classmate-1.1.0.jar, file:/C:/Users/Lemin/.m2/repository/com/fasterxml/jackson/core/jackson-databind/2.6.5/jackson-databind-2.6.5.jar, file:/C:/Users/Lemin/.m2/repository/com/fasterxml/jackson/core/jackson-annotations/2.6.5/jackson-annotations-2.6.5.jar, file:/C:/Users/Lemin/.m2/repository/com/fasterxml/jackson/core/jackson-core/2.6.5/jackson-core-2.6.5.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/spring-web/4.2.5.RELEASE/spring-web-4.2.5.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/spring-webmvc/4.2.5.RELEASE/spring-webmvc-4.2.5.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/spring-expression/4.2.5.RELEASE/spring-expression-4.2.5.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/mysql/mysql-connector-java/5.1.38/mysql-connector-java-5.1.38.jar, file:/C:/Users/Lemin/.m2/repository/org/springframework/spring-core/4.2.5.RELEASE/spring-core-4.2.5.RELEASE.jar, file:/C:/Users/Lemin/.m2/repository/org/scala-lang/scala-library/2.11.0/scala-library-2.11.0.jar]
please anyhelp i have to handle this exception

Why does JPQL Left Join ON Clause cause NullPointerException?

While this JPQL is working without any exception
Query query = em.createQuery("SELECT DISTINCT(r) FROM Request r LEFT JOIN Requesthistory h
WHERE h.request = r
AND (r.responsible = :employee OR h.employee = :employee)
AND r.requestedby != :employee ORDER BY r.objid DESC");
this JPQL is not working and throws NullPointerException
Query query = em.createQuery("SELECT DISTINCT(r) FROM Request r LEFT JOIN Requesthistory h
ON h.request = r
WHERE (r.responsible = :employee OR h.employee = :employee)
AND r.requestedby != :employee ORDER BY r.objid DESC");
The only difference between these two JPQL is ON Clause.
And yes there is 1:N relation between Request and Requesthistory in both entities and tables.
Here is exception I got:
Exception Description: Query failed to prepare, unexpected error occurred: [java.lang.NullPointerException].
Internal Exception: java.lang.NullPointerException
Query: ReportQuery(referenceClass=Request jpql="SELECT DISTINCT(r) FROM Request r LEFT JOIN Requesthistory h ON h.request = r WHERE (r.responsible = :employee OR h.employee = :employee) AND r.requestedby != :employee ORDER BY r.objid DESC")
at org.eclipse.persistence.exceptions.QueryException.prepareFailed(QueryException.java:1590) [eclipselink.jar:2.5.2.v20140319-9ad6abd]
at org.eclipse.persistence.queries.DatabaseQuery.checkPrepare(DatabaseQuery.java:680) [eclipselink.jar:2.5.2.v20140319-9ad6abd]
at org.eclipse.persistence.queries.ObjectLevelReadQuery.checkPrepare(ObjectLevelReadQuery.java:901) [eclipselink.jar:2.5.2.v20140319-9ad6abd]
at org.eclipse.persistence.queries.DatabaseQuery.checkPrepare(DatabaseQuery.java:613) [eclipselink.jar:2.5.2.v20140319-9ad6abd]
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:194) [eclipselink.jar:2.5.2.v20140319-9ad6abd]
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:116) [eclipselink.jar:2.5.2.v20140319-9ad6abd]
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.<init>(EJBQueryImpl.java:102) [eclipselink.jar:2.5.2.v20140319-9ad6abd]
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.<init>(EJBQueryImpl.java:86) [eclipselink.jar:2.5.2.v20140319-9ad6abd]
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1603) [eclipselink.jar:2.5.2.v20140319-9ad6abd]
at com.kadir.dao.notification.RequestDao.findToUserRequests(RequestDao.java:44) [classes:]
at com.kadir.service.notification.RequestService.getToUserRequests(RequestService.java:43) [classes:]
at com.kadir.bean.notification.RequestBean.init(RequestBean.java:49) [classes:]
... 110 more
Caused by: java.lang.NullPointerException
at org.eclipse.persistence.internal.expressions.ObjectExpression.getOwnedTables(ObjectExpression.java:583) [eclipselink.jar:2.5.2.v20140319-9ad6abd]
at org.eclipse.persistence.internal.expressions.FieldExpression.validateNode(FieldExpression.java:294) [eclipselink.jar:2.5.2.v20140319-9ad6abd]
at org.eclipse.persistence.expressions.Expression.normalize(Expression.java:3275) [eclipselink.jar:2.5.2.v20140319-9ad6abd]
at org.eclipse.persistence.internal.expressions.DataExpression.normalize(DataExpression.java:369) [eclipselink.jar:2.5.2.v20140319-9ad6abd]
at org.eclipse.persistence.internal.expressions.FieldExpression.normalize(FieldExpression.java:223) [eclipselink.jar:2.5.2.v20140319-9ad6abd]
at org.eclipse.persistence.internal.expressions.CompoundExpression.normalize(CompoundExpression.java:224) [eclipselink.jar:2.5.2.v20140319-9ad6abd]
at org.eclipse.persistence.internal.expressions.RelationExpression.normalize(RelationExpression.java:574) [eclipselink.jar:2.5.2.v20140319-9ad6abd]
at org.eclipse.persistence.internal.expressions.RelationExpression.normalize(RelationExpression.java:865) [eclipselink.jar:2.5.2.v20140319-9ad6abd]
at org.eclipse.persistence.expressions.ExpressionBuilder.normalize(ExpressionBuilder.java:267) [eclipselink.jar:2.5.2.v20140319-9ad6abd]
at org.eclipse.persistence.internal.expressions.RelationExpression.normalize(RelationExpression.java:825) [eclipselink.jar:2.5.2.v20140319-9ad6abd]
at org.eclipse.persistence.internal.expressions.CompoundExpression.normalize(CompoundExpression.java:232) [eclipselink.jar:2.5.2.v20140319-9ad6abd]
at org.eclipse.persistence.internal.expressions.CompoundExpression.normalize(CompoundExpression.java:224) [eclipselink.jar:2.5.2.v20140319-9ad6abd]
at org.eclipse.persistence.internal.expressions.SQLSelectStatement.normalize(SQLSelectStatement.java:1449) [eclipselink.jar:2.5.2.v20140319-9ad6abd]
at org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.buildReportQuerySelectStatement(ExpressionQueryMechanism.java:641) [eclipselink.jar:2.5.2.v20140319-9ad6abd]
at org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.buildReportQuerySelectStatement(ExpressionQueryMechanism.java:586) [eclipselink.jar:2.5.2.v20140319-9ad6abd]
at org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.prepareReportQuerySelectAllRows(ExpressionQueryMechanism.java:1694) [eclipselink.jar:2.5.2.v20140319-9ad6abd]
at org.eclipse.persistence.queries.ReportQuery.prepareSelectAllRows(ReportQuery.java:1203) [eclipselink.jar:2.5.2.v20140319-9ad6abd]
at org.eclipse.persistence.queries.ReadAllQuery.prepare(ReadAllQuery.java:744) [eclipselink.jar:2.5.2.v20140319-9ad6abd]
at org.eclipse.persistence.queries.ReportQuery.prepare(ReportQuery.java:1071) [eclipselink.jar:2.5.2.v20140319-9ad6abd]
at org.eclipse.persistence.queries.DatabaseQuery.checkPrepare(DatabaseQuery.java:661) [eclipselink.jar:2.5.2.v20140319-9ad6abd]
... 120 more
What am I doing wrong?
UPDATE FOR ENTITIES
Request.java
package com.kadir.entity.notification;
import com.kadir.entity.Base;
import com.kadir.entity.humanresource.Employee;
import java.io.Serializable;
import javax.persistence.*;
import java.util.List;
/**
* The persistent class for the REQUEST database table.
*
*/
#Cacheable
#Entity
#Table(name="REQUEST", schema="NOTIFICATION")
#NamedQuery(name="Request.findAll", query="SELECT r FROM Request r")
public class Request extends Base implements Serializable {
private static final long serialVersionUID = 1L;
#Column(name="CONTENT")
private String content;
#ManyToOne
#JoinColumn(name="REQUESTEDBY")
private Employee requestedby;
#ManyToOne
#JoinColumn(name="RESPONSIBLEOBJID")
private Employee responsible;
#Column(name="TITLE")
private String title;
//bi-directional many-to-one association to Requesttype
#ManyToOne
#JoinColumn(name="REQUESTTYPEOBJID")
private Requesttype requesttype;
//bi-directional many-to-one association to Responsetype
#ManyToOne
#JoinColumn(name="RESPONSETYPEOBJID")
private Responsetype responsetype;
//bi-directional many-to-one association to Requesthistory
#OneToMany(mappedBy="request")
private List<Requesthistory> requesthistories;
public Request() {
}
public String getContent() {
return this.content;
}
public void setContent(String content) {
this.content = content;
}
public Employee getRequestedby() {
return this.requestedby;
}
public void setRequestedby(Employee requestedby) {
this.requestedby = requestedby;
}
public Employee getResponsible() {
return this.responsible;
}
public void setResponsible(Employee responsible) {
this.responsible = responsible;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public Requesttype getRequesttype() {
return this.requesttype;
}
public void setRequesttype(Requesttype requesttype) {
this.requesttype = requesttype;
}
public Responsetype getResponsetype() {
return this.responsetype;
}
public void setResponsetype(Responsetype responsetype) {
this.responsetype = responsetype;
}
public List<Requesthistory> getRequesthistories() {
return this.requesthistories;
}
public void setRequesthistories(List<Requesthistory> requesthistories) {
this.requesthistories = requesthistories;
}
public Requesthistory addRequesthistory(Requesthistory requesthistory) {
getRequesthistories().add(requesthistory);
requesthistory.setRequest(this);
return requesthistory;
}
public Requesthistory removeRequesthistory(Requesthistory requesthistory) {
getRequesthistories().remove(requesthistory);
requesthistory.setRequest(null);
return requesthistory;
}
}
RequestHistory.java
package com.kadir.entity.notification;
import com.kadir.entity.humanresource.Employee;
import com.kadir.entity.Base;
import java.io.Serializable;
import javax.persistence.*;
/**
* The persistent class for the REQUESTHISTORY database table.
*
*/
#Cacheable
#Entity
#Table(name="REQUESTHISTORY", schema="NOTIFICATION")
#NamedQuery(name="Requesthistory.findAll", query="SELECT r FROM Requesthistory r")
public class Requesthistory extends Base implements Serializable {
private static final long serialVersionUID = 1L;
#ManyToOne
#JoinColumn(name="EMPLOYEEOBJID")
private Employee employee;
#Column(name="EXPLANATION")
private String explanation;
//bi-directional many-to-one association to Request
#ManyToOne
#JoinColumn(name="REQUESTOBJID")
private Request request;
//bi-directional many-to-one association to Responsetype
#ManyToOne
#JoinColumn(name="RESPONSETYPEOBJID")
private Responsetype responsetype;
public Requesthistory() {
}
public Employee getEmployee() {
return this.employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public String getExplanation() {
return this.explanation;
}
public void setExplanation(String explanation) {
this.explanation = explanation;
}
public Request getRequest() {
return this.request;
}
public void setRequest(Request request) {
this.request = request;
}
public Responsetype getResponsetype() {
return this.responsetype;
}
public void setResponsetype(Responsetype responsetype) {
this.responsetype = responsetype;
}
}
Base.java
package com.kadir.entity;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.Date;
import javax.persistence.Cacheable;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Version;
#Cacheable
#MappedSuperclass
public abstract class Base {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "OBJID")
private BigInteger objid;
#Column(name = "CREATEDBY")
private String createdby;
#Column(name = "CREATEDDATE")
private Timestamp createddate;
#Version
#Column(name = "ROWVERSION")
private Integer rowversion;
#Column(name = "UPDATEDBY")
private String updatedby;
#Column(name = "UPDATEDDATE")
private Timestamp updateddate;
#Column(name = "ARCHIVED", columnDefinition = "int default 0")
private int archived;
public BigInteger getObjid() {
return this.objid;
}
public void setObjid(BigInteger objid) {
this.objid = objid;
}
public String getCreatedby() {
return this.createdby;
}
public void setCreatedby(String createdby) {
this.createdby = createdby;
}
public Date getCreateddate() {
return this.createddate;
}
public void setCreateddate(Timestamp createddate) {
this.createddate = createddate;
}
public Integer getRowversion() {
return this.rowversion;
}
public void setRowversion(Integer rowversion) {
this.rowversion = rowversion;
}
public String getUpdatedby() {
return this.updatedby;
}
public void setUpdatedby(String updatedby) {
this.updatedby = updatedby;
}
public Timestamp getUpdateddate() {
return this.updateddate;
}
public void setUpdateddate(Timestamp updateddate) {
this.updateddate = updateddate;
}
public int getArchived() {
return archived;
}
public void setArchived(int archived) {
this.archived = archived;
}
}
I think problem is with your inheritance mapping.
The mapped supperclass Base has no inheritance strategy defined, so default one SINGLE_TABLE is used. Next you define #Table(name="...") annotations on each of your sublcasses Request and Requesthistory what makes no sense with SINGLE_TABLE strategy as with this strategy all subclasses are mapped to one shared table.
I think TABLE_PER_CLASS is the strategy you want.
#Cacheable
#MappedSuperclass
#Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class Base {
Update after closer look at your query
In jpql join clauses are used a little bit different as in sql. You can not join arbitrary entities and then bind them through ON or WHERE clause. You can join only entities associated in abstract schema.
Try following (jpql valid) query:
SELECT DISTINCT(r)
FROM Request r
LEFT JOIN r.requesthistories h
WHERE (r.responsible = :employee OR h.employee = :employee)
AND r.requestedby != :employee
ORDER BY r.objid DESC
(Note: Queries over non-associated entities are posssible, but it is different topic.)

HTTP Status 500 - Request processing failed; nested exception is Exception [EclipseLink-4002]

I'am working with JPA eclipselink at the moment and like to connect to my Database with Eclipselink
I have some classes for de Tables in My database and a Query to get my Entries:
final Query query = entityManager.createQuery("SELECT q FROM FDC_DBCHANGE q ORDER BY q.CHANGE_ID");
I made some classes for my tables:
FDC_DBCHANGE
package com.bechtle.dbchanges.model;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
#Entity
public class FDC_DBCHANGE {
#Id
#GeneratedValue(strategy = GenerationType.TABLE)
private long CHANGE_ID;
private String CHANGE_NAME;
private String CHANGE_DATE;
private int CHANGE_NUMBER;
#OneToMany(mappedBy = "FDC_DBCHANGE")
private final List<FDC_EXECUTED> checkBoxes = new ArrayList<FDC_EXECUTED>();
public String getChangeName() {
return CHANGE_NAME;
}
public void setChangeName(final String pChangeName) {
CHANGE_NAME = pChangeName;
}
public String getChangeDate() {
return CHANGE_DATE;
}
public void setChangeDate(final String pChangeDate) {
CHANGE_DATE = pChangeDate;
}
public int getChangeNumber() {
return CHANGE_NUMBER;
}
public void setChangeNumber(final int pChangeNumber) {
CHANGE_NUMBER = pChangeNumber;
}
public List<FDC_EXECUTED> getCheckBoxes() {
return checkBoxes;
}
#Override
public String toString() {
return "FDC_DBCHANGE [CHANGE_NAME=" + CHANGE_NAME + ", CHANGE_DATE="
+ CHANGE_DATE + "CHANGE_NUMBER=" + CHANGE_NUMBER + "]";
}
}
FDC_EXECUTED
package com.bechtle.dbchanges.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
#Entity
public class FDC_EXECUTED {
#Id
#GeneratedValue(strategy = GenerationType.TABLE)
private int ENTRY_ID;
private FDC_DBCHANGE FDC_DBCHANGE;
private FDC_SYSTEM FDC_SYSTEM;
#OneToOne
#JoinColumn
public FDC_DBCHANGE getDbChange() {
return FDC_DBCHANGE;
}
public void setDbChange(final FDC_DBCHANGE pDbChange) {
FDC_DBCHANGE = pDbChange;
}
#OneToOne
#JoinColumn
public FDC_SYSTEM getSystem() {
return FDC_SYSTEM;
}
public void setSystem(final FDC_SYSTEM pSystem) {
FDC_SYSTEM = pSystem;
}
}
and FDC_SYSTEM
package com.bechtle.dbchanges.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
#Entity
public class FDC_SYSTEM {
#Id
#GeneratedValue(strategy = GenerationType.TABLE)
private int SYSTEM_ID;
private String NAME;
private FDC_EXECUTED fdcexecuted;
public String getName() {
return NAME;
}
public void setName(final String pName) {
NAME = pName;
}
#OneToMany(mappedBy = "FED_SYSTEM")
public FDC_EXECUTED getExecuted() {
return fdcexecuted;
}
public void setExecuted(final FDC_EXECUTED pExecuted) {
fdcexecuted = pExecuted;
}
}
When I run it on my Tomcat there is this Exception:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: ORA-00904: "FDC_DBCHANGE_CHANGE_ID": invalid identifier
Error Code: 904
Call: SELECT ENTRY_ID, FDC_DBCHANGE_CHANGE_ID, FDC_SYSTEM_SYSTEM_ID FROM FDC_EXECUTED WHERE (FDC_DBCHANGE_CHANGE_ID = ?)
bind => [1 parameter bound]
Query: ReadAllQuery(name="checkBoxes" referenceClass=FDC_EXECUTED sql="SELECT ENTRY_ID, FDC_DBCHANGE_CHANGE_ID, FDC_SYSTEM_SYSTEM_ID FROM FDC_EXECUTED WHERE (FDC_DBCHANGE_CHANGE_ID = ?)")
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:932)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:816)
javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:801)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
Eclipselink tries to run the SQL Statement SELECT ENTRY_ID, FDC_DBCHANGE_CHANGE_ID, FDC_SYSTEM_SYSTEM_ID FROM FDC_EXECUTED WHERE (FDC_DBCHANGE_CHANGE_ID = ?)
instead of SELECT ENTRY_ID, CHANGE_ID, SYSTEM_ID FROM FDC_EXECUTED WHERE (CHANGE_ID = ?)
I don't konw why...
I hope someone can help me and sorry for my bad english...
obsidianfarmer
Ok, problem solved, its cause Eclipselink needs an OID I have no acces to, that was the problem...

Relation ManyToOne, javax.persistence.EntityExistsException: a different object with the same identifier value was already associated with the session

I've spent a lot of time searching for the bug and I can't resolve this.
I use spring JPA with Hibernate and Postgre.
I have two entities Location and Ap:
CREATE TABLE ap
(
id serial NOT NULL,
ssid text NOT NULL,
bssid text NOT NULL,
capabilities text,
CONSTRAINT ap_pkey PRIMARY KEY (id )
)
CREATE TABLE location2
(
latitude double precision NOT NULL,
longitude double precision NOT NULL,
power integer NOT NULL,
ap_id integer,
id serial NOT NULL,
CONSTRAINT location2_pkey PRIMARY KEY (id ),
CONSTRAINT location2_ap_id_fkey FOREIGN KEY (ap_id)
REFERENCES ap (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
Ap:
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "ap")
public class Ap implements Serializable {
private Long id;
private String ssid;
private String bssid;
private String capabilities;
private Set<Location> locations = new HashSet<Location>();
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#OneToMany(mappedBy = "ap", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
public Set<Location> getLocations() {
return locations;
}
public void setLocations(Set<Location> locations) {
this.locations = locations;
}
#Column
public String getSsid() {
return ssid;
}
public void setSsid(String ssid) {
this.ssid = ssid;
}
#Column
public String getBssid() {
return bssid;
}
public void setBssid(String bssid) {
this.bssid = bssid;
}
#Column
public String getCapabilities() {
return capabilities;
}
public void setCapabilities(String capabilities) {
this.capabilities = capabilities;
}
public void addLocation(Location location) {
location.setAp(this);
getLocations().add(location);
}
public void removeLocation(Location location) {
getLocations().remove(location);
}
public Ap() {
super();
}
public Ap(String ssid, String bssid, String capabilities) {
this.ssid = ssid;
this.bssid = bssid;
this.capabilities = capabilities;
}
}
Location2
#Entity
#Table(name = "location2")
public class Location implements Serializable {
private Long id;
private double latitude;
private double longitude;
private int power;
private Ap ap;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#ManyToOne
#JoinColumn(name = "ap_id")
public Ap getAp() {
return ap;
}
public void setAp(Ap ap) {
this.ap = ap;
}
#Column
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
#Column
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
#Column
public int getPower() {
return power;
}
public void setPower(int power) {
this.power = power;
}
public Location(double latitude, double longitude, int power) {
super();
this.latitude = latitude;
this.longitude = longitude;
this.power = power;
}
public Location() {
super();
}
When I add one Location to Ap it works, but when Ap has two or more Location I can't save Ap entity.
ApService service=context.getBean("ApService", ApService.class);
Ap ap=new Ap("test_ssid2", "test_bssid2", "test_capabilities2");
ap.addLocation(new Location(9.121, 12.9, 12));
ap.addLocation(new Location(9.122, 12.9, 12));
service.save(ap);
ApService:
public Ap save(Ap ap) {
return apRepository.save(ap);
}
It cases error:
Exception in thread "main" org.springframework.dao.DataIntegrityViolationException: a different object with the same identifier value was already associated with the session: [com.kulig.ap.domain.Location#9]; nested exception is javax.persistence.EntityExistsException: a different object with the same identifier value was already associated with the session: [com.kulig.ap.domain.Location#9]
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:318)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:106)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:403)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:58)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:163)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.data.jpa.repository.support.LockModeRepositoryPostProcessor$LockModePopulatingMethodIntercceptor.invoke(LockModeRepositoryPostProcessor.java:91)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:90)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy24.save(Unknown Source)
at com.kulig.ap.service.jpa.ApServiceImpl.save(ApServiceImpl.java:31)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:318)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:155)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy29.save(Unknown Source)
at com.kulig.ap.Test.main(Test.java:24)
Caused by: javax.persistence.EntityExistsException: a different object with the same identifier value was already associated with the session: [com.kulig.ap.domain.Location#9]
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1359)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1315)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1321)
at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:843)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:240)
at $Proxy19.persist(Unknown Source)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:341)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:334)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:319)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:155)
... 22 more
I also tried EntityManager with merge and persist methods and this gives the same error.
Please help.
In Location try to change
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
to
#Id
#GeneratedValue(generator="LOCATION_SEQ_GEN",strategy=GenerationType.SEQUENCE)
#SequenceGenerator(sequenceName="location_sequence_name",name="LOCATION_SEQ_GEN",allocationSize=1)
I heard that allocationSize=1 is bad practice but otherwise there are problems with sequence. You can read more Hibernate use of PostgreSQL sequence does not affect sequence table