Can't make one to many connection between two tables - java

I try to connect Lbg to iLbg with OneToMany annotation
package bg.moi.domain.model;
import javax.persistence.*;
import java.util.Date;
import java.util.Set;
#Entity
#Table(name = "l_bg" , catalog = "bds1")//, schema = "admbds",
#IdClass(LBgEntityPK.class)
public class LBgEntity {
#Id
#Column(name = "sid_o", nullable = false, precision = 0)
private int sidO;
public int getSidO() {
return sidO;
}
public void setSidO(int sidO) {
this.sidO = sidO;
}
#Id
#Column(name = "pnr_o", nullable = false)
private short pnrO;
public short getPnrO() {
return pnrO;
}
public void setPnrO(short pnrO) {
this.pnrO = pnrO;
}
#Basic
#Column(name = "egn", nullable = false, length = 10)
private String egn;
public String getEgn() {
return egn;
}
public void setEgn(String egn) {
this.egn = egn;
}
#Basic
#Column(name = "ime", nullable = false, length = 25)
private String ime;
public String getIme() {
return ime;
}
public void setIme(String ime) {
this.ime = ime;
}
#Basic
#Column(name = "prezime", nullable = false, length = 25)
private String prezime;
public String getPrezime() {
return prezime;
}
public void setPrezime(String prezime) {
this.prezime = prezime;
}
#Basic
#Column(name = "familno", nullable = false, length = 43)
private String familno;
public String getFamilno() {
return familno;
}
public void setFamilno(String familno) {
this.familno = familno;
}
#Basic
#Column(name = "dat_vav", nullable = false)
private Date datVav;
public Date getDatVav() { return datVav; }
public void setDatVav(Date datVav) { this.datVav = datVav; }
#Basic
#Column(name = "mrk_akt", nullable = false, length = 1)
private String mrkAkt;
public String getMrkAkt() {
return mrkAkt;
}
public void setMrkAkt(String mrkAkt) {
this.mrkAkt = mrkAkt;
}
#OneToMany(targetEntity = ILbgEntity.class,fetch = FetchType.LAZY)
#JoinColumns({#JoinColumn(name = "sidO",referencedColumnName = "sidO",insertable = false,updatable = false),
#JoinColumn(name = "pnrO" ,referencedColumnName = "pnrO",insertable = false,updatable = false)})
//#JoinColumn(foreignKey = #ForeignKey(name = "r130_1013"))
private Set<ILbgEntity> iLbgEntity;
public void setiLbgEntity(Set<ILbgEntity> iLbgEntity) { this.iLbgEntity = iLbgEntity; }
public Set<ILbgEntity> getiLbgEntity(){ return iLbgEntity; }
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
LBgEntity lBgEntity = (LBgEntity) o;
if (sidO != lBgEntity.sidO) return false;
if (pnrO != lBgEntity.pnrO) return false;
if (egn != null ? !egn.equals(lBgEntity.egn) : lBgEntity.egn != null) return false;
if (ime != null ? !ime.equals(lBgEntity.ime) : lBgEntity.ime != null) return false;
if (prezime != null ? !prezime.equals(lBgEntity.prezime) : lBgEntity.prezime != null) return false;
if (familno != null ? !familno.equals(lBgEntity.familno) : lBgEntity.familno != null) return false;
if (datVav != null ? !datVav.equals(lBgEntity.datVav) : lBgEntity.datVav != null) return false;
if (mrkAkt != null ? !mrkAkt.equals(lBgEntity.mrkAkt) : lBgEntity.mrkAkt != null) return false;
return true;
}
#Override
public int hashCode() {
int result = sidO;
result = 31 * result + (int) pnrO;
result = 31 * result + (egn != null ? egn.hashCode() : 0);
result = 31 * result + (ime != null ? ime.hashCode() : 0);
result = 31 * result + (prezime != null ? prezime.hashCode() : 0);
result = 31 * result + (familno != null ? familno.hashCode() : 0);
result = 31 * result + (datVav != null ? datVav.hashCode() : 0);
result = 31 * result + (mrkAkt != null ? mrkAkt.hashCode() : 0);
return result;
}
}
package bg.moi.domain.models;
import javax.persistence.Column;
import javax.persistence.Id;
import java.io.Serializable;
public class LBgEntityPK implements Serializable {
private int sidO;
private short pnrO;
#Column(name = "sid_o", nullable = false, precision = 0)
#Id
public int getSidO() {
return sidO;
}
public void setSidO(int sidO) {
this.sidO = sidO;
}
#Column(name = "pnr_o", nullable = false)
#Id
public short getPnrO() {
return pnrO;
}
public void setPnrO(short pnrO) {
this.pnrO = pnrO;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
LBgEntityPK that = (LBgEntityPK) o;
if (sidO != that.sidO) return false;
if (pnrO != that.pnrO) return false;
return true;
}
#Override
public int hashCode() {
int result = sidO;
result = 31 * result + (int) pnrO;
return result;
}
}
package bg.moi.domain.model;
import javax.persistence.*;
#Entity
#Table(name = "i_lbg", catalog = "bds1") //schema = "admbds",
#IdClass(ILbgEntityPK.class)
public class ILbgEntity {
#Id
#Column(name = "sid_o", nullable = false, precision = 0)
private int sidO;
public int getSidO() {
return sidO;
}
public void setSidO(int sidO) {
this.sidO = sidO;
}
#Id
#Column(name = "pnr_o", nullable = false)
private short pnrO;
public short getPnrO() {
return pnrO;
}
public void setPnrO(short pnrO) {
this.pnrO = pnrO;
}
#Basic
#Column(name = "ob1", nullable = false)
private int ob1;
public int getOb1() {
return ob1;
}
public void setOb1(int ob1) {
this.ob1 = ob1;
}
#Basic
#Column(name = "ob2", nullable = false)
private int ob2;
public int getOb2() {
return ob2;
}
public void setOb2(int ob2) {
this.ob2 = ob2;
}
#Basic
#Column(name = "ob3", nullable = false)
private int ob3;
public int getOb3() {
return ob3;
}
public void setOb3(int ob3) {
this.ob3 = ob3;
}
#Basic
#Column(name = "dtr", nullable = false)
private int dtr;
public int getDtr() {
return dtr;
}
public void setDtr(int dtr) {
this.dtr = dtr;
}
#Basic
#Column(name = "kpb", nullable = false)
private short kpb;
public short getKpb() {
return kpb;
}
public void setKpb(short kpb) {
this.kpb = kpb;
}
#Id
#Column(name = "pornom", nullable = false)
private short pornom;
public short getPornom() {
return pornom;
}
public void setPornom(short pornom) {
this.pornom = pornom;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ILbgEntity that = (ILbgEntity) o;
if (sidO != that.sidO) return false;
if (pnrO != that.pnrO) return false;
if (ob1 != that.ob1) return false;
if (ob2 != that.ob2) return false;
if (ob3 != that.ob3) return false;
if (dtr != that.dtr) return false;
if (kpb != that.kpb) return false;
if (pornom != that.pornom) return false;
return true;
}
#Override
public int hashCode() {
int result = sidO;
result = 31 * result + (int) pnrO;
result = 31 * result + ob1;
result = 31 * result + ob2;
result = 31 * result + ob3;
result = 31 * result + dtr;
result = 31 * result + (int) kpb;
result = 31 * result + (int) pornom;
return result;
}
}
package bg.moi.domain.models;
import javax.persistence.Column;
import javax.persistence.Id;
import java.io.Serializable;
public class ILbgEntityPK implements Serializable {
private int sidO;
private short pnrO;
private short pornom;
#Column(name = "sid_o", nullable = false, precision = 0)
#Id
public int getSidO() {
return sidO;
}
public void setSidO(int sidO) {
this.sidO = sidO;
}
#Column(name = "pnr_o", nullable = false)
#Id
public short getPnrO() {
return pnrO;
}
public void setPnrO(short pnrO) {
this.pnrO = pnrO;
}
#Column(name = "pornom", nullable = false)
#Id
public short getPornom() { return pornom; }
public void setPornom(short pornom) { this.pornom = pornom; }
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ILbgEntityPK that = (ILbgEntityPK) o;
if (sidO != that.sidO) return false;
if (pnrO != that.pnrO) return false;
if (pornom != that.pornom) return false;
return true;
}
#Override
public int hashCode() {
int result = sidO;
result = 31 * result + (int) pnrO;
result = 31 * result + (int) pornom;
return result;
}
}
Classes generate from database.
Exception is:
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'entityManagerFactory' defined in class path
resource
[org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]:
Invocation of init method failed; nested exception is
javax.persistence.PersistenceException: [PersistenceUnit: default]
Unable to build Hibernate SessionFactory at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628)
~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE] at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE] at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE] at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE] at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE] at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE] at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE] at
org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081)
~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE] at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856)
~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE] at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE] at
org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737)
[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE] at
org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370)
[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE] at
org.springframework.boot.SpringApplication.run(SpringApplication.java:314)
[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE] at
org.springframework.boot.SpringApplication.run(SpringApplication.java:1162)
[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE] at
org.springframework.boot.SpringApplication.run(SpringApplication.java:1151)
[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE] at
bg.moi.Applicaion.main(Applicaion.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:954)
~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final] at
org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:882)
~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final] at
org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60)
~[spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE] at
org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353)
~[spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE] at
org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:370)
~[spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE] at
org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:359)
~[spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE] at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE] at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE] ... 15 common frames
omitted Caused by:
org.hibernate.tool.schema.spi.SchemaManagementException: Unable to
execute schema management to JDBC target [alter table i_lbg add
constraint foreign key (sid_o, pnr_o) references l_bg constraint
FK422xjl1722nwcy2wxv5yg6nbx] at
org.hibernate.tool.schema.internal.TargetDatabaseImpl.accept(TargetDatabaseImpl.java:59)
~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] at
org.hibernate.tool.schema.internal.SchemaMigratorImpl.applySqlString(SchemaMigratorImpl.java:431)
~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] at
org.hibernate.tool.schema.internal.SchemaMigratorImpl.applySqlStrings(SchemaMigratorImpl.java:420)
~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] at
org.hibernate.tool.schema.internal.SchemaMigratorImpl.applyForeignKeys(SchemaMigratorImpl.java:386)
~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] at
org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigrationToTargets(SchemaMigratorImpl.java:214)
~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] at
org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigration(SchemaMigratorImpl.java:60)
~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] at
org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:134)
~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] at
org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:101)
~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] at
org.hibernate.internal.SessionFactoryImpl.(SessionFactoryImpl.java:472)
~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] at
org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444)
~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] at
org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879)
~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final] ... 21
common frames omitted Caused by: java.sql.SQLException: A constraint
of the same type already exists on the column set. at
com.informix.util.IfxErrMsg.buildException(IfxErrMsg.java:474)
~[jdbc-4.10.8.1.jar:4.10.8.1] at
com.informix.util.IfxErrMsg.getSQLException(IfxErrMsg.java:443)
~[jdbc-4.10.8.1.jar:4.10.8.1] at
com.informix.util.IfxErrMsg.getSQLException(IfxErrMsg.java:394)
~[jdbc-4.10.8.1.jar:4.10.8.1] at
com.informix.jdbc.IfxSqli.addException(IfxSqli.java:3191)
~[jdbc-4.10.8.1.jar:4.10.8.1] at
com.informix.jdbc.IfxSqli.receiveError(IfxSqli.java:3472)
~[jdbc-4.10.8.1.jar:4.10.8.1] at
com.informix.jdbc.IfxSqli.dispatchMsg(IfxSqli.java:2379)
~[jdbc-4.10.8.1.jar:4.10.8.1] at
com.informix.jdbc.IfxSqli.receiveMessage(IfxSqli.java:2304)
~[jdbc-4.10.8.1.jar:4.10.8.1] at
com.informix.jdbc.IfxSqli.executeCommand(IfxSqli.java:874)
~[jdbc-4.10.8.1.jar:4.10.8.1] at
com.informix.jdbc.IfxResultSet.executeUpdate(IfxResultSet.java:294)
~[jdbc-4.10.8.1.jar:4.10.8.1] at
com.informix.jdbc.IfxStatement.executeUpdateImpl(IfxStatement.java:1094)
~[jdbc-4.10.8.1.jar:4.10.8.1] at
com.informix.jdbc.IfxStatement.executeUpdateBody(IfxStatement.java:391)
~[jdbc-4.10.8.1.jar:4.10.8.1] at
com.informix.jdbc.IfxStatement.executeUpdate(IfxStatement.java:279)
~[jdbc-4.10.8.1.jar:4.10.8.1] at
org.hibernate.tool.schema.internal.TargetDatabaseImpl.accept(TargetDatabaseImpl.java:56)
~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] ... 31 common frames
omitted Caused by: java.sql.SQLException: null at
com.informix.util.IfxErrMsg.buildException(IfxErrMsg.java:474)
~[jdbc-4.10.8.1.jar:4.10.8.1] at
com.informix.util.IfxErrMsg.getSQLException(IfxErrMsg.java:443)
~[jdbc-4.10.8.1.jar:4.10.8.1] at
com.informix.util.IfxErrMsg.getSQLException(IfxErrMsg.java:394)
~[jdbc-4.10.8.1.jar:4.10.8.1] at
com.informix.jdbc.IfxSqli.receiveError(IfxSqli.java:3477)
~[jdbc-4.10.8.1.jar:4.10.8.1] ... 39 common frames omitted
Did someone have a similar problem?
Is there any solution?
Is possible this is bug ?!

1) You put #Id and #Column annotations on the entity class only. Do not put them in the ILbgEntityPK class.
2) Do not add setters in the id class.. create a constructor accepting the id fields.
3) When defining the #JoinColumns try to use database column names, not entity field names:
#OneToMany(targetEntity = ILbgEntity.class,fetch = FetchType.LAZY)
#JoinColumns({#JoinColumn(name = "sid_o",referencedColumnName = "sid_o",insertable = false,updatable = false),
#JoinColumn(name = "pnr_o" ,referencedColumnName = "pnr_o",insertable = false,updatable = false)})

Use below code in case of #OneToMany
#OneToMany(targetEntity = ILbgEntity.class, orphanRemoval = true, cascade = { CascadeType.ALL, CascadeType.REMOVE })
#JoinColumn(name = "sid_o", nullable = false)
#LazyCollection(LazyCollectionOption.FALSE)
#Fetch(FetchMode.SUBSELECT)

Related

JPA stackoverflow error when fetching data

I have 2 entities namely Teacher and Club, I need to retrieve the teacher data along with its related club and/or sports.
I a bit new to JPA so am having trouble debugging the stack overflow error I get when I use the findAll method on the Teacher repository.
I had tried adding #JsonIgnore annotation to my one-to-many annotation to deal with the recursion problem as suggested in some similar questions but was still getting problems and am not sure how exactly it's supposed to solve the problem.
TEACHER ENTITY:
#Entity
#Table(name = "TEACHER")
public class Teacher {
private String id;
private String name;
private Collection<ClubTeacher> clubTeachersById;
#Id
#Column(name = "Id", nullable = false, length = 10)
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Basic
#Column(name = "NAME", nullable = true, length = 25)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Teacher teacher = (Teacher) o;
if (id != null ? !id.equals(teacher.id) : teacher.id != null) return false;
if (name != null ? !name.equals(teacher.name) : teacher.name != null) return false;
return true;
}
#Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (name != null ? name.hashCode() : 0);
return result;
}
#OneToMany(mappedBy = "TICClub" ,fetch = FetchType.EAGER)
public Collection<ClubTeacher> getClubTeachersById() {
return clubTeachersById;
}
public void setClubTeachersById(Collection<ClubTeacher> clubTeachersById) {
this.clubTeachersById = clubTeachersById;
}
}
CLUB ENTITY:
#Entity
#Table(name = "CLUB_TEACHER", schema = "abbc", catalog = "")
#IdClass(ClubTeacherPK.class)
public class ClubTeacher implements Serializable {
private String tic;
private String clubkey;
private Teacher teacherByTic;
#Id
#Column(name = "TIC", nullable = false, length = 10)
public String getTic() {
return tic;
}
public void setTic(String tic) {
this.tic = tic;
}
#Id
#Column(name = "CLUBKEY", nullable = false, length = 25)
public String getClubkey() {
return clubkey;
}
public void setClubkey(String clubkey) {
this.clubkey = clubkey;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ClubTeacher that = (ClubTeacher) o;
if (tic != null ? !tic.equals(that.tic) : that.tic != null) return false;
if (clubkey != null ? !clubkey.equals(that.clubkey) : that.clubkey != null) return false;
return true;
}
#Override
public int hashCode() {
int result = tic != null ? tic.hashCode() : 0;
result = 31 * result + (clubkey != null ? clubkey.hashCode() : 0);
return result;
}
#ManyToOne
#JoinColumn(name = "TIC", referencedColumnName = "Id", nullable = false,insertable=false, updatable=false)
public Teacher getTeacherByTic() {
return teacherByTic;
}
public void setTeacherByTic(Teacher teacherByTic) {
this.teacherByTic = teacherByTic;
}
}
STACK TRACE:
2021-02-17 21:42:56.516 ERROR 20546 --- [nio-3005-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Handler dispatch failed; nested exception is java.lang.StackOverflowError] with root cause
java.lang.StackOverflowError: null
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:245) ~[gson-2.8.6.jar:na]
at com.google.gson.Gson$FutureTypeAdapter.write(Gson.java:1027) ~[gson-2.8.6.jar:na]
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:69) ~[gson-2.8.6.jar:na]
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:127) ~[gson-2.8.6.jar:na]
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:245) ~[gson-2.8.6.jar:na]
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:69) ~[gson-2.8.6.jar:na]
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:97) ~[gson-2.8.6.jar:na]
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:61) ~[gson-2.8.6.jar:na]
....

Hibernate #OneToMany fails with "collection is not associated with any session"

Here's the point: I want to load "DeliveryOrderEntity" (code below) from DB (MySQL). It has 1 foreign key with "one-to-many" relationship. It connects "BillsEntity" using billNumber. To make it clear - I have table ORDER with column BILL_NUMBER and table BILL with columns BILL_ID (primary key) and BILL_NUMBER (column, that connects BILL with ORDER).
Here is my code:
DeliveryOrderEntity.java:
#Entity
#Table(name = "DELIVERY_ORDER", schema = "", catalog = "kursach")
#NamedQueries(value = {
#NamedQuery(name = "findAllOrders", query = "from DeliveryOrderEntity"),
#NamedQuery(name = "getOrder", query = "from DeliveryOrderEntity where orderId=:orderId"),
#NamedQuery(name = "removeOrder", query = "delete from DeliveryOrderEntity where orderId=:orderId")
})
public class DeliveryOrderEntity implements Serializable{
private int orderId;
private Timestamp orderDate;
private String orderName;
private String orderTelephone;
private Integer billNumber;
private Integer regionId;
private List<BillEntity> listBill;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ORDER_ID")
public int getOrderId() {
return orderId;
}
public void setOrderId(int orderId) {
this.orderId = orderId;
}
#Basic
#Column(name = "ORDER_DATE")
public Timestamp getOrderDate() {
return orderDate;
}
public void setOrderDate(Timestamp orderDate) {
this.orderDate = orderDate;
}
#Basic
#Column(name = "ORDER_NAME")
public String getOrderName() {
return orderName;
}
public void setOrderName(String orderName) {
this.orderName = orderName;
}
#Basic
#Column(name = "ORDER_TELEPHONE")
public String getOrderTelephone() {
return orderTelephone;
}
public void setOrderTelephone(String orderTelephone) {
this.orderTelephone = orderTelephone;
}
#Basic
#Column(name = "BILL_NUMBER")
public Integer getBillNumber() {
return billNumber;
}
public void setBillNumber(Integer billNumber) {
this.billNumber = billNumber;
}
#Basic
#Column(name = "REGION_ID")
public Integer getRegionId() {
return regionId;
}
public void setRegionId(Integer regionNumber) {
this.regionId = regionNumber;
}
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.REFRESH)
#Fetch(FetchMode.JOIN)
#JoinColumn(name = "BILL_NUMBER", referencedColumnName = "BILL_NUMBER", nullable = false, insertable = false, updatable = false)
public List<BillEntity> getListBill() {
return listBill;
}
public void setListBill(List<BillEntity> listBill) {
this.listBill = listBill;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DeliveryOrderEntity entity = (DeliveryOrderEntity) o;
if (orderId != entity.orderId) return false;
if (orderDate != null ? !orderDate.equals(entity.orderDate) : entity.orderDate != null) return false;
if (orderName != null ? !orderName.equals(entity.orderName) : entity.orderName != null) return false;
if (orderTelephone != null ? !orderTelephone.equals(entity.orderTelephone) : entity.orderTelephone != null)
return false;
if (billNumber != null ? !billNumber.equals(entity.billNumber) : entity.billNumber != null) return false;
return !(regionId != null ? !regionId.equals(entity.regionId) : entity.regionId != null);
}
#Override
public int hashCode() {
int result = orderId;
result = 31 * result + (orderDate != null ? orderDate.hashCode() : 0);
result = 31 * result + (orderName != null ? orderName.hashCode() : 0);
result = 31 * result + (orderTelephone != null ? orderTelephone.hashCode() : 0);
result = 31 * result + (billNumber != null ? billNumber.hashCode() : 0);
return result;
}
}
BillsEntity.java:
#Entity
#Table(name = "BILL")
#NamedQueries({
#NamedQuery(name = "findAllBills", query = "from BillEntity"),
#NamedQuery(name = "findAllBillIds", query = "select billNumber from BillEntity group by billNumber"),
#NamedQuery(name = "findAllBillsById", query = "from BillEntity where billNumber=:billNumber")
})
public class BillEntity implements Serializable {
private int billId;
private Integer billNumber;
private Integer goodCount;
private Integer goodId;
private Integer billStatus;
private GoodsEntity good;
#Id
#Column(name = "BILL_ID")
public int getBillId() {
return billId;
}
public void setBillId(int billId) {
this.billId = billId;
}
#Basic
#Column(name = "BILL_NUMBER", updatable = false, insertable = false)
public Integer getBillNumber() {
return billNumber;
}
public void setBillNumber(Integer billNumber) {
this.billNumber = billNumber;
}
#Basic
#Column(name = "GOOD_COUNT")
public Integer getGoodCount() {
return goodCount;
}
public void setGoodCount(Integer goodCount) {
this.goodCount = goodCount;
}
#Basic
#Column(name = "BILL_STATUS")
public Integer getBillStatus() {
return billStatus;
}
#Basic
#Column(name = "GOOD_ID")
public Integer getGoodId() {
return goodId;
}
public void setGoodId(Integer goodId) {
this.goodId = goodId;
}
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "GOOD_ID", referencedColumnName = "GOOD_ID", nullable = false, insertable = false, updatable = false)
public GoodsEntity getGood() {
return good;
}
public void setGood(GoodsEntity good) {
this.good = good;
}
public void setBillStatus(Integer billStatus) {
this.billStatus = billStatus;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BillEntity that = (BillEntity) o;
if (billId != that.billId) return false;
if (billNumber != null ? !billNumber.equals(that.billNumber) : that.billNumber != null) return false;
if (goodCount != null ? !goodCount.equals(that.goodCount) : that.goodCount != null) return false;
if (goodId != null ? !goodId.equals(that.goodId) : that.goodId != null) return false;
return !(billStatus != null ? !billStatus.equals(that.billStatus) : that.billStatus != null);
}
#Override
public int hashCode() {
int result = billId;
result = 31 * result + (billNumber != null ? billNumber.hashCode() : 0);
result = 31 * result + (goodCount != null ? goodCount.hashCode() : 0);
result = 31 * result + (goodId != null ? goodId.hashCode() : 0);
result = 31 * result + (billStatus != null ? billStatus.hashCode() : 0);
return result;
}
#Override
public String toString() {
return "BillEntity{" +
"billId=" + billId +
", billNumber=" + billNumber +
", goodCount=" + goodCount +
", billStatus=" + billStatus +
", good=" + good +
'}';
}
}
As you can see, I have unidirectional OneToMany relationship. The problem is that when i have 2 rows in DELIVERY_ORDER table with the same BILL_NUMBER and I try to get list of orders - it fails with:
Caused by: org.hibernate.HibernateException: collection is not associated with any session
at org.hibernate.collection.internal.AbstractPersistentCollection.forceInitialization(AbstractPersistentCollection.java:676)
at org.hibernate.engine.internal.StatefulPersistenceContext.initializeNonLazyCollections(StatefulPersistenceContext.java:1030)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:346)
at org.hibernate.loader.Loader.doList(Loader.java:2522)
at org.hibernate.loader.Loader.doList(Loader.java:2508)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2338)
at org.hibernate.loader.Loader.list(Loader.java:2333)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:490)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:355)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:195)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1269)
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:101)
at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:264)
Here is the code where i fetch the list:
public List<DeliveryOrderEntity> listOrders() {
List findAllOrders = new ArrayList();
EntityManager entityManager = transactionManager.getEntityManagerFactory().createEntityManager();
try {
entityManager.getTransaction().begin();
findAllOrders = entityManager.createNamedQuery("findAllOrders").getResultList();
} catch (Exception e) {
e.printStackTrace();
} finally {
entityManager.getTransaction().commit();
}
return findAllOrders;
}
Thank you in advance.

issue with a Criteria when querying a many to many association

I have an issue with how hibernate implemented a many to many relationship.
Hibernate created the 2 following classes to map the tables relationship:
package entities;
// default package
// Generated Jul 13, 2015 2:58:02 PM by Hibernate Tools 4.0.0
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
* CategoriesDuSpectacle generated by hbm2java
*/
#Entity
#Table(name = "Categories_Du_Spectacle")
public class CategoriesDuSpectacle implements java.io.Serializable {
private CategoriesDuSpectacleId id;
public CategoriesDuSpectacle() {
}
public CategoriesDuSpectacle(CategoriesDuSpectacleId id) {
this.id = id;
}
#EmbeddedId
#AttributeOverrides({
#AttributeOverride(name = "spectacleId", column = #Column(name = "Spectacle_Id", nullable = false)),
#AttributeOverride(name = "categorieId", column = #Column(name = "Categorie_Id", nullable = false)),
#AttributeOverride(name = "duree", column = #Column(name = "Duree")),
#AttributeOverride(name = "commentaire", column = #Column(name = "Commentaire")),
#AttributeOverride(name = "theme", column = #Column(name = "Theme")),
#AttributeOverride(name = "contrainte", column = #Column(name = "Contrainte")) })
public CategoriesDuSpectacleId getId() {
return this.id;
}
public void setId(CategoriesDuSpectacleId id) {
this.id = id;
}
}
and:
package entities;
// default package
// Generated Jul 13, 2015 2:58:02 PM by Hibernate Tools 4.0.0
import javax.persistence.Column;
import javax.persistence.Embeddable;
/**
* CategoriesDuSpectacleId generated by hbm2java
*/
#Embeddable
public class CategoriesDuSpectacleId implements java.io.Serializable {
private int spectacleId;
private int categorieId;
private Integer duree;
private String commentaire;
private String theme;
private String contrainte;
public CategoriesDuSpectacleId() {
}
public CategoriesDuSpectacleId(int spectacleId, int categorieId) {
this.spectacleId = spectacleId;
this.categorieId = categorieId;
}
public CategoriesDuSpectacleId(int spectacleId, int categorieId,
Integer duree, String commentaire, String theme, String contrainte) {
this.spectacleId = spectacleId;
this.categorieId = categorieId;
this.duree = duree;
this.commentaire = commentaire;
this.theme = theme;
this.contrainte = contrainte;
}
#Column(name = "Spectacle_Id", nullable = false)
public int getSpectacleId() {
return this.spectacleId;
}
public void setSpectacleId(int spectacleId) {
this.spectacleId = spectacleId;
}
#Column(name = "Categorie_Id", nullable = false)
public int getCategorieId() {
return this.categorieId;
}
public void setCategorieId(int categorieId) {
this.categorieId = categorieId;
}
#Column(name = "Duree")
public Integer getDuree() {
return this.duree;
}
public void setDuree(Integer duree) {
this.duree = duree;
}
#Column(name = "Commentaire")
public String getCommentaire() {
return this.commentaire;
}
public void setCommentaire(String commentaire) {
this.commentaire = commentaire;
}
#Column(name = "Theme")
public String getTheme() {
return this.theme;
}
public void setTheme(String theme) {
this.theme = theme;
}
#Column(name = "Contrainte")
public String getContrainte() {
return this.contrainte;
}
public void setContrainte(String contrainte) {
this.contrainte = contrainte;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof CategoriesDuSpectacleId))
return false;
CategoriesDuSpectacleId castOther = (CategoriesDuSpectacleId) other;
return (this.getSpectacleId() == castOther.getSpectacleId())
&& (this.getCategorieId() == castOther.getCategorieId())
&& ((this.getDuree() == castOther.getDuree()) || (this
.getDuree() != null && castOther.getDuree() != null && this
.getDuree().equals(castOther.getDuree())))
&& ((this.getCommentaire() == castOther.getCommentaire()) || (this
.getCommentaire() != null
&& castOther.getCommentaire() != null && this
.getCommentaire().equals(castOther.getCommentaire())))
&& ((this.getTheme() == castOther.getTheme()) || (this
.getTheme() != null && castOther.getTheme() != null && this
.getTheme().equals(castOther.getTheme())))
&& ((this.getContrainte() == castOther.getContrainte()) || (this
.getContrainte() != null
&& castOther.getContrainte() != null && this
.getContrainte().equals(castOther.getContrainte())));
}
public int hashCode() {
int result = 17;
result = 37 * result + this.getSpectacleId();
result = 37 * result + this.getCategorieId();
result = 37 * result
+ (getDuree() == null ? 0 : this.getDuree().hashCode());
result = 37
* result
+ (getCommentaire() == null ? 0 : this.getCommentaire()
.hashCode());
result = 37 * result
+ (getTheme() == null ? 0 : this.getTheme().hashCode());
result = 37
* result
+ (getContrainte() == null ? 0 : this.getContrainte()
.hashCode());
return result;
}
}
I apologize for the fields naes in French.
Now, when I try to catch all of the entities:
List l = session.createCriteria(CategoriesDuSpectacle.class).list();
This works fine.
But when I try to add a criteria:
l = session.createCriteria(CategoriesDuSpectacle.class).add(Restrictions.ilike("commentaire", "a")).list();
I get the following error:
org.hibernate.QueryException: could not resolve property: commentaire of: entities.CategoriesDuSpectacle
This sounds strange to me as the concerned field is mentionned in CategoriesDuSpectacle class:
#EmbeddedId
#AttributeOverrides({
{...}
#AttributeOverride(name = "commentaire", column = #Column(name = "Commentaire")),
{...}
})
Any idea about what I missed?
Thx in advance.
a good night made me figure it out.
I used the parameter on the wrong object:
l = session.createCriteria(CategoriesDuSpectacle.class).add(Restrictions.ilike("commentaire", "a")).list();
While it should have been this way:
l = session.createCriteria(CategoriesDuSpectacle.class).add(Restrictions.ilike("id.commentaire", "a")).list();
Hope it will help someone else.

Column does not exist - Hibernate ManyToMany association class

I'm facing the following problem. Imagine this data model:
As you can see project_function entity is association many to many entity.
Here are my entity classes.
PeronalCard:
#Entity
#Table(name = "personal_card")
#XmlRootElement
public class PersonalCard implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id_person")
private Integer idPerson;
/* SOME OTHER ATTRIBUTES */
#OneToMany(cascade = CascadeType.ALL, mappedBy = "projectFunctionPK.personalCard")
private Set<ProjectFunction> projectFunctionSet;
public PersonalCard() {
}
public Integer getIdPerson() {
return idPerson;
}
public void setIdPerson(Integer idPerson) {
this.idPerson = idPerson;
}
#XmlTransient
public Set<ProjectFunction> getProjectFunctionSet() {
return projectFunctionSet;
}
public void setProjectFunctionSet(Set<ProjectFunction> projectFunctionSet) {
this.projectFunctionSet = projectFunctionSet;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idPerson != null ? idPerson.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof PersonalCard)) {
return false;
}
PersonalCard other = (PersonalCard) object;
if ((this.idPerson == null && other.idPerson != null) || (this.idPerson != null && !this.idPerson.equals(other.idPerson))) {
return false;
}
return true;
}
}
Project:
#Entity
#Table(name = "project")
#XmlRootElement
public class Project implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id_project")
private Integer idProject;
/* OTHER ATTRIBUTES*/
#OneToMany(cascade = CascadeType.ALL, mappedBy = "projectFunctionPK.project")
private Set<ProjectFunction> projectFunctionSet;
public Project() {
}
public Integer getIdProject() {
return idProject;
}
public void setIdProject(Integer idProject) {
this.idProject = idProject;
}
#XmlTransient
public Set<ProjectFunction> getProjectFunctionSet() {
return projectFunctionSet;
}
public void setProjectFunctionSet(Set<ProjectFunction> projectFunctionSet) {
this.projectFunctionSet = projectFunctionSet;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idProject != null ? idProject.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Project)) {
return false;
}
Project other = (Project) object;
if ((this.idProject == null && other.idProject != null) || (this.idProject != null && !this.idProject.equals(other.idProject))) {
return false;
}
return true;
}
}
ProjectFunction:
#Entity
#Table(name = "project_function")
#XmlRootElement
#AssociationOverrides({
#AssociationOverride(name = "projectFunctionPK.project",
joinColumns = #JoinColumn(name = "id_project", referencedColumnName = "id_project")),
#AssociationOverride(name = "projectFunctionPK.personalCard",
joinColumns = #JoinColumn(name = "id_person", referencedColumnName = "id_person")) })
public class ProjectFunction implements Serializable {
private static final long serialVersionUID = 1L;
protected ProjectFunctionPK projectFunctionPK;
private Date fromd;
private Date tod;
public ProjectFunction() {
this.projectFunctionPK = new ProjectFunctionPK();
}
#EmbeddedId
public ProjectFunctionPK getProjectFunctionPK() {
return projectFunctionPK;
}
public void setProjectFunctionPK(ProjectFunctionPK projectFunctionPK) {
this.projectFunctionPK = projectFunctionPK;
}
#Column(name = "fromd")
#Temporal(TemporalType.DATE)
public Date getFromd() {
return fromd;
}
public void setFromd(Date fromd) {
this.fromd = fromd;
}
#Column(name = "tod")
#Temporal(TemporalType.DATE)
public Date getTod() {
return tod;
}
public void setTod(Date tod) {
this.tod = tod;
}
#Transient
public Project getProject() {
return projectFunctionPK.getProject();
}
public void setProject(Project project) {
this.projectFunctionPK.setProject(project);
}
#Transient
public PersonalCard getPersonalCard() {
return this.projectFunctionPK.getPersonalCard();
}
public void setPersonalCard(PersonalCard personalCard) {
//this.personalCard = personalCard;
this.projectFunctionPK.setPersonalCard(personalCard);
}
#Override
public int hashCode() {
int hash = 0;
hash += (projectFunctionPK != null ? projectFunctionPK.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof ProjectFunction)) {
return false;
}
ProjectFunction other = (ProjectFunction) object;
if ((this.projectFunctionPK == null && other.projectFunctionPK != null) || (this.projectFunctionPK != null && !this.projectFunctionPK.equals(other.projectFunctionPK))) {
return false;
}
return true;
}
}
And finally my embedded Primary Key ProjectFunctionPK:
#Embeddable
public class ProjectFunctionPK implements Serializable {
#ManyToOne
private Project project;
#ManyToOne
private PersonalCard personalCard;
public ProjectFunctionPK() {
}
public Project getProject() {
return project;
}
public void setProject(Project project) {
this.project = project;
}
public PersonalCard getPersonalCard() {
return personalCard;
}
public void setPersonalCard(PersonalCard personalCard) {
this.personalCard = personalCard;
}
#Override
public int hashCode() {
int hash = 3;
hash = 41 * hash + Objects.hashCode(this.project);
hash = 41 * hash + Objects.hashCode(this.personalCard);
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final ProjectFunctionPK other = (ProjectFunctionPK) obj;
if (!Objects.equals(this.project, other.project)) {
return false;
}
if (!Objects.equals(this.personalCard, other.personalCard)) {
return false;
}
return true;
}
}
First I save the Project. It works fine. Then i want to connect it using project_function - so I create project_function set them existing project and personal_card and after trying to persist I get following error:
Caused by: org.postgresql.util.PSQLException: ERROR: column projectfun0_.personalcard does not exist
Position: 8
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2198)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1927)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:255)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:561)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:419)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:304)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:82)
... 119 more
So apparently Hibernate does not know projectfun0_.personalcard . But I dont know why. Do you see any error in the entity classes? Or could the error possibly be somewhere else ?
Thank you very much for all your answers :)
EmbeddedId documentation
Relationship mappings defined within an embedded id class are not supported.
So, ProjectFunctionPK should contain only basic mappings, and entity mappings should be done in the entity itself. Here are some related posts
https://stackoverflow.com/a/9760808/4074715
https://stackoverflow.com/a/4692144/4074715

Update fails on Hibernate with OneToMany

Hey guys I'm trying to updata an entry in my Entity managed by Hibernate, it has 3 relationships ManyToOne non-Indentifying.
When I try to update giving the Id and the new value of quantidade column, throws an exception
Stacktrace:
org.hibernate.PropertyValueException: not-null property references a null or transient value : br.com.cheetah.catalog.entity.ModeloPeca.armazemByArmazemIdarmazem
at org.hibernate.engine.internal.Nullability.checkNullability(Nullability.java:106)
at org.hibernate.event.internal.DefaultFlushEntityEventListener.scheduleUpdate(DefaultFlushEntityEventListener.java:309)
at org.hibernate.event.internal.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:160)
at org.hibernate.event.internal.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:231)
at org.hibernate.event.internal.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:102)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:55)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1222)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:1335)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:262)
at com.sun.proxy.$Proxy31.flush(Unknown Source)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.flush(SimpleJpaRepository.java:416)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.saveAndFlush(SimpleJpaRepository.java:384)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:358)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:343)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.jpa.repository.support.LockModeRepositoryPostProcessor$LockModePopulatingMethodIntercceptor.invoke(LockModeRepositoryPostProcessor.java:105)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy37.saveAndFlush(Unknown Source)
at br.com.cheetah.catalog.controller.business.ModelosEmUsoController.addModeloEmUso(ModelosEmUsoController.java:58)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:301)
Entity :
#Entity
#Table(name = "modelopeca")
public class ModeloPeca
{
private Integer idPeca;
private String modelo;
private Date dataAquisicao;
private String estado;
private String marca;
private String detalhe;
private Double valor;
private String tipo;
private Integer quantidade;
private Armazem armazemByArmazemId;
private Fornecedor fornecedorByFornecedorId;
private SubEquipe subequipeBySubEquipeId;
private Collection<ModelosEmUso> modelosemusosByIdPeca;
#Id
#Column(name = "idPeca")
#GeneratedValue
public Integer getIdPeca()
{
return idPeca;
}
public void setIdPeca(Integer idPeca)
{
this.idPeca = idPeca;
}
#Basic
#Column(name = "modelo")
public String getModelo()
{
return modelo;
}
public void setModelo(String modelo)
{
this.modelo = modelo;
}
#Basic
#Column(name = "dataAquisicao")
public Date getDataAquisicao()
{
return dataAquisicao;
}
public void setDataAquisicao(Date dataAquisicao)
{
this.dataAquisicao = dataAquisicao;
}
#Basic
#Column(name = "estado")
public String getEstado()
{
return estado;
}
public void setEstado(String estado)
{
this.estado = estado;
}
#Basic
#Column(name = "marca")
public String getMarca()
{
return marca;
}
public void setMarca(String marca)
{
this.marca = marca;
}
#Basic
#Column(name = "detalhe")
public String getDetalhe()
{
return detalhe;
}
public void setDetalhe(String detalhe)
{
this.detalhe = detalhe;
}
#Basic
#Column(name = "valor")
public Double getValor()
{
return valor;
}
public void setValor(Double valor)
{
this.valor = valor;
}
#Basic
#Column(name = "tipo")
public String getTipo()
{
return tipo;
}
public void setTipo(String tipo)
{
this.tipo = tipo;
}
#Basic
#Column(name = "quantidade")
public Integer getQuantidade()
{
return quantidade;
}
public void setQuantidade(Integer quantidade)
{
this.quantidade = quantidade;
}
#Override
public boolean equals(Object o)
{
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ModeloPeca that = (ModeloPeca) o;
if (dataAquisicao != null ? !dataAquisicao.equals(that.dataAquisicao)
: that.dataAquisicao != null)
return false;
if (detalhe != null ? !detalhe.equals(that.detalhe) : that.detalhe !=
null)
return false;
if (estado != null ? !estado.equals(that.estado) : that.estado != null)
return false;
if (idPeca != null ? !idPeca.equals(that.idPeca) : that.idPeca != null)
return false;
if (marca != null ? !marca.equals(that.marca) : that.marca != null)
return false;
if (modelo != null ? !modelo.equals(that.modelo) : that.modelo != null)
return false;
if (quantidade != null ? !quantidade.equals(that.quantidade) : that.quantidade != null)
return false;
if (tipo != null ? !tipo.equals(that.tipo) : that.tipo != null)
return false;
if (valor != null ? !valor.equals(that.valor) : that.valor != null)
return false;
return true;
}
#Override
public int hashCode()
{
int result = idPeca != null ? idPeca.hashCode() : 0;
result = 31 * result + (modelo != null ? modelo.hashCode() : 0);
result = 31 * result + (dataAquisicao != null ? dataAquisicao
.hashCode() :
0);
result = 31 * result + (estado != null ? estado.hashCode() : 0);
result = 31 * result + (marca != null ? marca.hashCode() : 0);
result = 31 * result + (detalhe != null ? detalhe.hashCode() : 0);
result = 31 * result + (valor != null ? valor.hashCode() : 0);
result = 31 * result + (tipo != null ? tipo.hashCode() : 0);
result = 31 * result + (quantidade != null ? quantidade.hashCode() : 0);
return result;
}
#ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name = "armazem_idarmazem",
referencedColumnName = "idArmazem",
nullable = false)
public Armazem getArmazemByArmazemId()
{
return armazemByArmazemId;
}
public void setArmazemByArmazemId(Armazem armazemByArmazemIdarmazem)
{
this.armazemByArmazemId = armazemByArmazemIdarmazem;
}
#ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name = "Fornecedor_idFornecedor",
referencedColumnName = "idFornecedor",
nullable = false)
public Fornecedor getFornecedorByFornecedorId()
{
return fornecedorByFornecedorId;
}
public void setFornecedorByFornecedorId(Fornecedor
fornecedorByFornecedorIdFornecedor)
{
this.fornecedorByFornecedorId =
fornecedorByFornecedorIdFornecedor;
}
#ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name = "subEquipe_idSubEquipe",
referencedColumnName = "idSubEquipe",
nullable = false)
public SubEquipe getSubequipeBySubEquipeId()
{
return subequipeBySubEquipeId;
}
public void setSubequipeBySubEquipeId(SubEquipe
subequipeBySubEquipeIdSubEquipe)
{
this.subequipeBySubEquipeId = subequipeBySubEquipeIdSubEquipe;
}
#OneToMany(mappedBy = "modelopecaByModeloPecaIdPeca")
public Collection<ModelosEmUso> getModelosemusosByIdPeca()
{
return modelosemusosByIdPeca;
}
public void setModelosemusosByIdPeca(Collection<ModelosEmUso>
modelosemusosByIdPeca)
{
this.modelosemusosByIdPeca = modelosemusosByIdPeca;
}
}
How I insert data and update:
ModeloPeca modelo = new ModeloPeca();
modelo.setIdPeca(idModelo);
modelo.setQuantidade(restante);
modeloPecaRepository.saveAndFlush(modelo);
PS: I'm using Spring, Spring Data JPA, and Hibernate provider for JPA
Thanks for your time!
The property armazemByArmazemId can not be null.
You are creating a new ModeloPeca, but leaving this property as null.
Hence, Hibernate is rejecting this.
You have a choice, either:
Modify the mapping so the value can be null:
#ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name = "armazem_idarmazem",
referencedColumnName = "idArmazem",
nullable = true)
public Armazem getArmazemByArmazemId()
{
return armazemByArmazemId;
}
OR, Actually call modelo.setArmazemByArmazemId before calling saveAndFlush
Your are giving validation as nullable = false and passing null value at the time of update so its giving error that not-null property references a null so just change nullable = false to nullable = true in armazem_idarmazem column.

Categories