Update fails on Hibernate with OneToMany - java

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.

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]
....

Spring Boot JpaRepository save call doesn't seem to be doing anything

I'm writing a Spring Boot application that uses JpaRepository interfaces. In a service method where I'm attempting to write some objects, calls to two repositories' save() methods don't appear to be doing anything, but are also not throwing any exceptions.
I'm using mysql, with ISAM tables, with MySQL5Dialect.
Here are my entities:
Bookings
package com.bigbadcon.dataservices.entity.eventManager;
import com.bigbadcon.dataservices.entity.wordpress.Users;
import javax.persistence.*;
import java.math.BigDecimal;
import java.sql.Timestamp;
#Entity
#Table(name = "bookings", schema = "redacted", catalog = "")
public class Bookings {
private Long bookingId;
private Integer bookingSpaces;
private String bookingComment;
private Timestamp bookingDate;
private Integer bookingStatus;
private BigDecimal bookingPrice;
private String bookingMeta;
private BigDecimal bookingTaxRate;
private BigDecimal bookingTaxes;
private Users user;
private Events event;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "booking_id")
public Long getBookingId() {
return bookingId;
}
public void setBookingId(Long bookingId) {
this.bookingId = bookingId;
}
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "person_id", referencedColumnName = "ID")
public Users getUser() {
return this.user;
}
public void setUser(Users user) {
this.user = user;
}
#ManyToOne
#JoinColumn(name = "event_id")
public Events getEvent() {
return this.event;
}
public void setEvent(Events event) {
this.event = event;
}
#Basic
#Column(name = "booking_spaces")
public Integer getBookingSpaces() {
return bookingSpaces;
}
public void setBookingSpaces(Integer bookingSpaces) {
this.bookingSpaces = bookingSpaces;
}
#Basic
#Column(name = "booking_comment", columnDefinition = "TEXT")
public String getBookingComment() {
return bookingComment;
}
public void setBookingComment(String bookingComment) {
this.bookingComment = bookingComment;
}
#Basic
#Column(name = "booking_date")
public Timestamp getBookingDate() {
return bookingDate;
}
public void setBookingDate(Timestamp bookingDate) {
this.bookingDate = bookingDate;
}
#Basic
#Column(name = "booking_status", columnDefinition = "TINYINT", length = 1)
public Integer getBookingStatus() {
return bookingStatus;
}
public void setBookingStatus(Integer bookingStatus) {
this.bookingStatus = bookingStatus;
}
#Basic
#Column(name = "booking_price")
public BigDecimal getBookingPrice() {
return bookingPrice;
}
public void setBookingPrice(BigDecimal bookingPrice) {
this.bookingPrice = bookingPrice;
}
#Basic
#Lob
#Column(name = "booking_meta")
public String getBookingMeta() {
return bookingMeta;
}
public void setBookingMeta(String bookingMeta) {
this.bookingMeta = bookingMeta;
}
#Basic
#Column(name = "booking_tax_rate")
public BigDecimal getBookingTaxRate() {
return bookingTaxRate;
}
public void setBookingTaxRate(BigDecimal bookingTaxRate) {
this.bookingTaxRate = bookingTaxRate;
}
#Basic
#Column(name = "booking_taxes")
public BigDecimal getBookingTaxes() {
return bookingTaxes;
}
public void setBookingTaxes(BigDecimal bookingTaxes) {
this.bookingTaxes = bookingTaxes;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Bookings that = (Bookings) o;
if (bookingId != null ? !bookingId.equals(that.bookingId) : that.bookingId != null) return false;
if (bookingSpaces != null ? !bookingSpaces.equals(that.bookingSpaces) : that.bookingSpaces != null)
return false;
if (bookingComment != null ? !bookingComment.equals(that.bookingComment) : that.bookingComment != null)
return false;
if (bookingDate != null ? !bookingDate.equals(that.bookingDate) : that.bookingDate != null) return false;
if (bookingStatus != null ? !bookingStatus.equals(that.bookingStatus) : that.bookingStatus != null)
return false;
if (bookingPrice != null ? !bookingPrice.equals(that.bookingPrice) : that.bookingPrice != null) return false;
if (bookingMeta != null ? !bookingMeta.equals(that.bookingMeta) : that.bookingMeta != null) return false;
if (bookingTaxRate != null ? !bookingTaxRate.equals(that.bookingTaxRate) : that.bookingTaxRate != null)
return false;
if (bookingTaxes != null ? !bookingTaxes.equals(that.bookingTaxes) : that.bookingTaxes != null) return false;
return true;
}
#Override
public int hashCode() {
int result = bookingId != null ? bookingId.hashCode() : 0;
result = 31 * result + (bookingSpaces != null ? bookingSpaces.hashCode() : 0);
result = 31 * result + (bookingComment != null ? bookingComment.hashCode() : 0);
result = 31 * result + (bookingDate != null ? bookingDate.hashCode() : 0);
result = 31 * result + (bookingStatus != null ? bookingStatus.hashCode() : 0);
result = 31 * result + (bookingPrice != null ? bookingPrice.hashCode() : 0);
result = 31 * result + (bookingMeta != null ? bookingMeta.hashCode() : 0);
result = 31 * result + (bookingTaxRate != null ? bookingTaxRate.hashCode() : 0);
result = 31 * result + (bookingTaxes != null ? bookingTaxes.hashCode() : 0);
return result;
}
}
TicketsBookings
import com.bigbadcon.dataservices.entity.wordpress.Users;
import javax.persistence.*;
import java.math.BigDecimal;
import java.sql.Timestamp;
#Entity
#Table(name = "bookings", schema = "redacted", catalog = "")
public class Bookings {
private Long bookingId;
private Integer bookingSpaces;
private String bookingComment;
private Timestamp bookingDate;
private Integer bookingStatus;
private BigDecimal bookingPrice;
private String bookingMeta;
private BigDecimal bookingTaxRate;
private BigDecimal bookingTaxes;
private Users user;
private Events event;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "booking_id")
public Long getBookingId() {
return bookingId;
}
public void setBookingId(Long bookingId) {
this.bookingId = bookingId;
}
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "person_id", referencedColumnName = "ID")
public Users getUser() {
return this.user;
}
public void setUser(Users user) {
this.user = user;
}
#ManyToOne
#JoinColumn(name = "event_id")
public Events getEvent() {
return this.event;
}
public void setEvent(Events event) {
this.event = event;
}
#Basic
#Column(name = "booking_spaces")
public Integer getBookingSpaces() {
return bookingSpaces;
}
public void setBookingSpaces(Integer bookingSpaces) {
this.bookingSpaces = bookingSpaces;
}
#Basic
#Column(name = "booking_comment", columnDefinition = "TEXT")
public String getBookingComment() {
return bookingComment;
}
public void setBookingComment(String bookingComment) {
this.bookingComment = bookingComment;
}
#Basic
#Column(name = "booking_date")
public Timestamp getBookingDate() {
return bookingDate;
}
public void setBookingDate(Timestamp bookingDate) {
this.bookingDate = bookingDate;
}
#Basic
#Column(name = "booking_status", columnDefinition = "TINYINT", length = 1)
public Integer getBookingStatus() {
return bookingStatus;
}
public void setBookingStatus(Integer bookingStatus) {
this.bookingStatus = bookingStatus;
}
#Basic
#Column(name = "booking_price")
public BigDecimal getBookingPrice() {
return bookingPrice;
}
public void setBookingPrice(BigDecimal bookingPrice) {
this.bookingPrice = bookingPrice;
}
#Basic
#Lob
#Column(name = "booking_meta")
public String getBookingMeta() {
return bookingMeta;
}
public void setBookingMeta(String bookingMeta) {
this.bookingMeta = bookingMeta;
}
#Basic
#Column(name = "booking_tax_rate")
public BigDecimal getBookingTaxRate() {
return bookingTaxRate;
}
public void setBookingTaxRate(BigDecimal bookingTaxRate) {
this.bookingTaxRate = bookingTaxRate;
}
#Basic
#Column(name = "booking_taxes")
public BigDecimal getBookingTaxes() {
return bookingTaxes;
}
public void setBookingTaxes(BigDecimal bookingTaxes) {
this.bookingTaxes = bookingTaxes;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Bookings that = (Bookings) o;
if (bookingId != null ? !bookingId.equals(that.bookingId) : that.bookingId != null) return false;
if (bookingSpaces != null ? !bookingSpaces.equals(that.bookingSpaces) : that.bookingSpaces != null)
return false;
if (bookingComment != null ? !bookingComment.equals(that.bookingComment) : that.bookingComment != null)
return false;
if (bookingDate != null ? !bookingDate.equals(that.bookingDate) : that.bookingDate != null) return false;
if (bookingStatus != null ? !bookingStatus.equals(that.bookingStatus) : that.bookingStatus != null)
return false;
if (bookingPrice != null ? !bookingPrice.equals(that.bookingPrice) : that.bookingPrice != null) return false;
if (bookingMeta != null ? !bookingMeta.equals(that.bookingMeta) : that.bookingMeta != null) return false;
if (bookingTaxRate != null ? !bookingTaxRate.equals(that.bookingTaxRate) : that.bookingTaxRate != null)
return false;
if (bookingTaxes != null ? !bookingTaxes.equals(that.bookingTaxes) : that.bookingTaxes != null) return false;
return true;
}
#Override
public int hashCode() {
int result = bookingId != null ? bookingId.hashCode() : 0;
result = 31 * result + (bookingSpaces != null ? bookingSpaces.hashCode() : 0);
result = 31 * result + (bookingComment != null ? bookingComment.hashCode() : 0);
result = 31 * result + (bookingDate != null ? bookingDate.hashCode() : 0);
result = 31 * result + (bookingStatus != null ? bookingStatus.hashCode() : 0);
result = 31 * result + (bookingPrice != null ? bookingPrice.hashCode() : 0);
result = 31 * result + (bookingMeta != null ? bookingMeta.hashCode() : 0);
result = 31 * result + (bookingTaxRate != null ? bookingTaxRate.hashCode() : 0);
result = 31 * result + (bookingTaxes != null ? bookingTaxes.hashCode() : 0);
return result;
}
}
Here is the JpaRepository for the Bookings entity:
import com.bigbadcon.dataservices.entity.eventManager.Bookings;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
#Repository
#Transactional
public interface BookingsRepositoryInterface extends JpaRepository<Bookings, Long> {
#Query(value = "SELECT b from Bookings b where b.user.id = ?1 AND b.event.eventName not like 'Verify % badge%' " +
"AND FUNCTION('YEAR', b.event.eventStartDate) = ?2 and b.bookingStatus = 1")
List<Bookings> findForUser(Long userId, Integer filterYear);
#Query(value = "SELECT b from Bookings b where b.event.eventId= ?1 and b.bookingSpaces = 1 and b.bookingStatus = 1")
List<Bookings> findForEvent(Long eventId);
}
And for the TicketsBookings entity:
package com.bigbadcon.dataservices.repository.eventManager.interfaces;
import com.bigbadcon.dataservices.entity.eventManager.TicketsBookings;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
#Repository
#Transactional
public interface TicketsBookingsRepositoryInterface extends JpaRepository<TicketsBookings, Long> {
#Query(value = "SELECT tb from TicketsBookings tb where tb.bookingId.event.eventId = ?1 ")
List<TicketsBookings> findForEvent(Long eventId);
}
And finally, here's the method that's not behaving:
#Service
public class BookingsService {
#Autowired
private BookingsRepositoryInterface bookingsDAO;
#Autowired
private TicketsRepositoryInterface ticketsDAO;
#Autowired
private TicketsBookingsRepositoryInterface ticketsBookingsDAO;
#Autowired
private EventsRepositoryInterface eventsDAO;
#Autowired
private UsersRepositoryInterface usersDAO;
#Autowired
private OptionsRepositoryInterface optionsDAO;
#Autowired
private EmailService emailService;
#Autowired
private BookingsService bookingsService;
#Autowired
private SecurityService securityService;
#PersistenceContext
EntityManager em;
private static final Logger log = LoggerFactory.getLogger(BookingsService.class);
public HashMap<String, Boolean> stateTable;
private Integer statusBooked = 1;
private Integer statusCancelled = 2;
private Integer statusDeleted = 3;
/**
* <p>This method is only to be called by the game registration consumer. It assumes the UI has done some sort
* of check that the user isn't already booked in the game. The WP UI does this.</p>
* <p>Admin users can call the addPlayerToGame method instead.</p>
* #param eventId
* #param userId
* #param uuid
*/
#Transactional(propagation = Propagation.REQUIRES_NEW)
public void createBooking(Long eventId, Long userId, String uuid) {
Events event = eventsDAO.findOne(eventId);
log.info("Event found: " + event.toString());
Users user = usersDAO.findOne(userId);
log.info("User found: " + user.toString());
Timestamp now = new Timestamp(System.currentTimeMillis());
Tickets ticket = ticketsDAO.findTicketByEventId(event.getEventId());
if (ticket == null) {
log.info("Event " + event.getEventId() + " is not open for registration yet.");
return;
}
log.info("Found ticket: " + ticket.toString());
List<Bookings> bookingsList = bookingsDAO.findForEvent(event.getEventId());
for (Bookings booking : bookingsList) {
if (booking.getUser().getId().equals(userId)) {
log.info("User " + booking.getUser().getDisplayName() + " has already signed up for event id " + event.getEventId());
return;
}
}
Integer bookingSpaces = 1;
Integer bookingStatus = 1;
if (bookingsList.size() >= ticket.getTicketSpaces()) {
bookingSpaces = 0;
bookingStatus = 4;
}
Bookings booking = new Bookings();
booking.setEvent(event);
booking.setUser(user);
booking.setBookingSpaces(bookingSpaces);
booking.setBookingDate(now);
booking.setBookingStatus(bookingStatus);
booking.setBookingMeta("a:0:{}");
bookingsDAO.save(booking);
TicketsBookings ticketBooking = new TicketsBookings();
ticketBooking.setBookingId(booking);
ticketBooking.setTicketId(ticket.getTicketId());
ticketBooking.setTicketBookingSpaces(statusBooked);
ticketBooking.setTicketBookingPrice(new BigDecimal(0));
ticketsBookingsDAO.save(ticketBooking);
//TODO send rejection mail for overbookings
try {
if (bookingStatus.equals(1)) {
emailService.sendEmail(createConfirmedPlayerEmail(user, event));
emailService.sendEmail(createConfirmedHostEmail(user, event));
bookingsService.stateTable.put(uuid, new Boolean(true));
}
else {
bookingsService.stateTable.put(uuid, new Boolean(false));
}
}
catch (Exception e) {
e.printStackTrace();
}
}
According to what I've read on the subject, methods annotated with #Transactional should commit once the method returns. When I execute the method, it does in fact print to the log that it's saving. However, I have sql debugging turned on, and it does not print any sql statements when it saves. (it does print sql statements on selects.)
The method has no problems doing the selects above, only the saves in the latter part. No exceptions are thrown, but the data doesn't appear in the tables that the entities are using. The only line that gets printed in the log for each save looks like this:
o.s.t.i.TransactionInterceptor : Completing transaction for [org.springframework.data.jpa.repository.support.SimpleJpaRepository.save]
I'm not sure if this is relevant, but this call is made by the listener class for a jms queue.
My question is, am I missing anything to enable persisting data in this way? From what I've read, #Transactional automatically has readOnly set to true, and my IDE confirms this. Did I miss something important?
For anyone reading this in the future, the root cause of the issue was that the service method call was coming from a message queue receiver class. I'm not sure why. When I moved the call directly to the web service instead of the queue receiver, the insert happened with no issues.

Can't make one to many connection between two tables

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)

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.

Categories