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

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.

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 search is not working

I am developping a java/jee application in which i am using spring boot and hibernate as frameworks i used hibernate search for full text searching but unfortunately i always got an empty list as result.I am using hibernate version 5.1 and hibernate search orm version 5.5.3.Final.Here is my code :
public void search() {
FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(this.em);
try {
fullTextEntityManager.createIndexer().startAndWait();
// create native Lucene query unsing the query DSL
// alternatively you can write the Lucene query using the Lucene
// query parser
// or the Lucene programmatic API. The Hibernate Search DSL is
// recommended though
QueryBuilder queryBuilder = fullTextEntityManager.getSearchFactory()
.buildQueryBuilder()
.forEntity(Application.class)
.get();
org.apache.lucene.search.Query luceneQuery = queryBuilder.keyword().wildcard().onField("reference").matching("di*")
.createQuery();
// wrap Lucene query in a javax.persistence.Query
javax.persistence.Query jpaQuery = fullTextEntityManager.createFullTextQuery(luceneQuery,
Application.class);
// execute search
List<Application> result = jpaQuery.getResultList();
System.out.println("your result list is "+result);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and here is my entity
package biz.picosoft.entities;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import org.hibernate.search.annotations.Analyze;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Index;
import org.hibernate.search.annotations.Indexed;
import org.hibernate.search.annotations.Store;
#Entity
#Indexed
#Table(name = "application",uniqueConstraints = {#UniqueConstraint(columnNames = "reference")})
public class Application implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Long id;
#Field(index = Index.YES, analyze = Analyze.NO, store = Store.YES)
#Column(name = "reference")
private String reference;
#Field(index = Index.YES, analyze = Analyze.NO, store = Store.YES)
#Column(name = "creationDate")
private Date creationDate;
#Field(index = Index.YES, analyze = Analyze.NO, store = Store.YES)
#Column(name = "status")
private String status;
#Field(index = Index.YES, analyze = Analyze.NO,store = Store.YES)
#Column(name = "deadLine")
private Date deadLine;
#Field(index = Index.YES, analyze = Analyze.NO,store = Store.YES)
#Column(name = "appType")
private String appType;
#Field(index = Index.YES, analyze = Analyze.NO, store = Store.YES)
#Column(name = "projectId")
private Long projectId;
#OneToMany(cascade = CascadeType.ALL)
#JoinTable(name = "App_files", joinColumns = { #JoinColumn(name = "idApp") }, inverseJoinColumns = {
#JoinColumn(name = "idFile") })
private List<FileMetadata> listePiecesJointes = new ArrayList<FileMetadata>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Date getDeadLine() {
return deadLine;
}
public void setDeadLine(Date deadLine) {
this.deadLine = deadLine;
}
public String getAppType() {
return appType;
}
public void setAppType(String appType) {
this.appType = appType;
}
public Application() {
super();
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
public Long getProjectId() {
return projectId;
}
public void setProjectId(Long projectId) {
this.projectId = projectId;
}
public List<FileMetadata> getListePiecesJointes() {
return listePiecesJointes;
}
public void setListePiecesJointes(List<FileMetadata> listePiecesJointes) {
this.listePiecesJointes = listePiecesJointes;
}
public Application(String reference, Date creationDate, String status, Date deadLine, String appType,Long projectId) {
super();
this.reference = reference;
this.creationDate = creationDate;
this.status = status;
this.deadLine = deadLine;
this.appType = appType;
this.projectId=projectId;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((appType == null) ? 0 : appType.hashCode());
result = prime * result + ((creationDate == null) ? 0 : creationDate.hashCode());
result = prime * result + ((deadLine == null) ? 0 : deadLine.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((projectId == null) ? 0 : projectId.hashCode());
result = prime * result + ((reference == null) ? 0 : reference.hashCode());
result = prime * result + ((status == null) ? 0 : status.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Application other = (Application) obj;
if (appType == null) {
if (other.appType != null)
return false;
} else if (!appType.equals(other.appType))
return false;
if (creationDate == null) {
if (other.creationDate != null)
return false;
} else if (!creationDate.equals(other.creationDate))
return false;
if (deadLine == null) {
if (other.deadLine != null)
return false;
} else if (!deadLine.equals(other.deadLine))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (projectId == null) {
if (other.projectId != null)
return false;
} else if (!projectId.equals(other.projectId))
return false;
if (reference == null) {
if (other.reference != null)
return false;
} else if (!reference.equals(other.reference))
return false;
if (status == null) {
if (other.status != null)
return false;
} else if (!status.equals(other.status))
return false;
return true;
}
#Override
public String toString() {
return "Application [id=" + id + ", reference=" + reference + ", creationDate=" + creationDate + ", status="
+ status + ", deadLine=" + deadLine + ", appType=" + appType + ", projectId=" + projectId + "]";
}
}
I have solved my problem.It was because of subclasses which were not indexed.
Did you make sure your entities are indexed before searching?
If you are using a pre-existing database, or if you initialized your database without using Hibernate ORM APIs (by using SQL directly, or by restoring a dump), your entities are probably not indexed yet.
You should have a look at the mass indexer, which makes it easy to index a lot of entities: https://docs.jboss.org/hibernate/search/5.5/reference/en-US/html_single/#search-batchindex-massindexer

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.

Mapping issue on Hibernate

I am in the middle of developing a JHipster project and I've come to a halt due to what I believe to be mapping issues
My Database has several tables, but the two that affect me here are Study and Publication, where they have a Many to Many relationship.
I need to retrieve the collection of Publications where a study can be published, hence Study is the owner of the relationship, but for some reason, Hibernate don't recognise the attributes I map the relation with.
All of this started trying to solve a lazy connection issue, yes I have been through most posts relating this and I have tried everything that made sense to me.
Here the code of Study:
#Audited
#Entity
#Table(name = "Study")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
#Document(indexName = "study")
public class Study implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "num_sites")
private Integer numSites;
#Column(name = "ref")
private String ref;
#Column(name = "study_type")
private String studyType;
#ManyToMany(fetch = FetchType.LAZY)
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
#JoinTable(name = "Pub_Study",
joinColumns = #JoinColumn(name="studies_id", referencedColumnName="id"),
inverseJoinColumns = #JoinColumn(name="publications_id", referencedColumnName="id"))
public static Set<Publication> publications = new HashSet<>();
#OneToMany(mappedBy = "study")
#JsonIgnore
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<SiteData> siteDatas = new HashSet<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getNumSites() {
return numSites;
}
public void setNumSites(Integer numSites) {
this.numSites = numSites;
}
public String getRef() {
return ref;
}
public void setRef(String ref) {
this.ref = ref;
}
public String getStudyType() {
return studyType;
}
public void setStudyType(String studyType) {
this.studyType = studyType;
}
public static Set<Publication> getPublicationss() {
return publications;
}
public void setPublicationss(Set<Publication> publications) {
this.publications = publications;
}
public Set<SiteData> getSiteDatas() {
return siteDatas;
}
public void setSiteDatas(Set<SiteData> siteDatas) {
this.siteDatas = siteDatas;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Study study = (Study) o;
if(study.id == null || id == null) {
return false;
}
return Objects.equals(id, study.id);
}
#Override
public int hashCode() {
return Objects.hashCode(id);
}
#Override
public String toString() {
return "Study{" +
"id=" + id +
", numSites='" + numSites + "'" +
", ref='" + ref + "'" +
", studyType='" + studyType + "'" +
'}';
}
Here the code of Publication:
#Audited
#Entity
#Table(name = "Publication")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
#Document(indexName = "publication")
public class Publication implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "authors")
private String authors;
#Column(name = "first_author")
private String firstAuthor;
#Column(name = "journal")
private String journal;
#Column(name = "pubMedId")
private Integer pubMedId;
#Column(name = "title")
private String title;
#Column(name = "year_publish")
private Integer yearPublish;
#Version
Integer version;
#ManyToMany(fetch = FetchType.LAZY)
#JsonIgnore
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Study> studies = new HashSet<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getAuthors() {
return authors;
}
public void setAuthors(String authors) {
this.authors = authors;
}
public String getFirstAuthor() {
return firstAuthor;
}
public void setFirstAuthor(String firstAuthor) {
this.firstAuthor = firstAuthor;
}
public String getJournal() {
return journal;
}
public void setJournal(String journal) {
this.journal = journal;
}
public Integer getPubMedId() {
return pubMedId;
}
public void setPubMedId(Integer pubMedId) {
this.pubMedId = pubMedId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Integer getYearPublish() {
return yearPublish;
}
public void setYearPublish(Integer yearPublish) {
this.yearPublish = yearPublish;
}
public Set<Study> getStudies() {
return studies;
}
public void setStudies(Set<Study> studys) {
this.studies = studys;
}
public Integer getVersion(){
return version;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Publication publication = (Publication) o;
if(publication.id == null || id == null) {
return false;
}
return Objects.equals(id, publication.id);
}
#Override
public int hashCode() {
return Objects.hashCode(id);
}
#Override
public String toString() {
return "Publication{" +
"id=" + id +
", authors='" + authors + "'" +
", firstAuthor='" + firstAuthor + "'" +
", journal='" + journal + "'" +
", pubMedId='" + pubMedId + "'" +
", title='" + title + "'" +
", yearPublish='" + yearPublish + "'" +
'}';
}
}
Here the Implementation of the query from the Repository package:
public class SiteDataRepositoryImpl implements SiteDataRepositoryCustom{
#PersistenceContext
private EntityManager em;
#Override
public List <SiteDataViewDTO> searchSiteDataByFilter(List<Filter> listFilters) {
TypedQuery<SiteData> query = buildQuery(listFilters);
Hibernate.initialize(Study.publications);
int count=0;
for (Filter filter: listFilters){
if("country".equals(filter.getName()))
query.setParameter(filter.getName(), filter.getQuery());
else if("category".equals(filter.getName()))
query.setParameter(filter.getName(), filter.getQuery());
else if("studyRef".equals(filter.getName()))
query.setParameter(filter.getName(), filter.getQuery());
else if("studyType".equals(filter.getName()))
query.setParameter(filter.getName(), filter.getQuery());
else if("pubMedId".equals(filter.getName()))
query.setParameter(filter.getName(), Integer.valueOf(filter.getQuery()));
count++;
}
List<SiteData> siteDataList = query.getResultList();
List<SiteDataViewDTO> siteDataViewDTOList=new ArrayList<SiteDataViewDTO>();
//temp variables
List<String>tempListTreatments = new ArrayList<String>();
List<String>tempListTitles = new ArrayList<String>();
List<Integer>tempListIdMed = new ArrayList<Integer>();
//filling SiteDataViewDTO list
siteDataList.stream().forEach(sd->{
SiteDataViewDTO temp = new SiteDataViewDTO();
temp.setTypeStudy(sd.getTypeStudy() + "id SiteData: " + sd.getId());
temp.setRef(sd.getStudy().getRef());
temp.setCategory(sd.getCategory().getName());
temp.setUpper95CI(sd.getUpper95CI());
temp.setYearStart(sd.getYearStart());
temp.setYearEnd(sd.getYearEnd());
Set<Publication>setPu = sd.getStudy().getPublicationss();
System.out.println("#################### In the query, size of the Publications List "+setPu.size());
setPu.stream().forEach(sp-> {
tempListTitles.add(sp.getTitle());
tempListIdMed.add(sp.getPubMedId());
});
Set<Treatment>setTr = sd.getTreatments();
/*setTr.stream().forEach(sp-> {
tempListTreatments.add(sp.getTreatmentName());
});*/
temp.setListPubObject(setPu);
temp.setListTreatObject(setTr);
siteDataViewDTOList.add(temp);
});
return siteDataViewDTOList;
}
private TypedQuery<SiteData> buildQuery(List<Filter> listFilters){
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<SiteData> cq = cb.createQuery(SiteData.class);
Root<SiteData> siteData = cq.from(SiteData.class);
Join<SiteData, Category> cat = siteData.join("category", JoinType.LEFT);
Join<SiteData, Location> loc = siteData.join("location",JoinType.LEFT);
Join<SiteData, Treatment> tre = siteData.join("treatments",JoinType.LEFT);
Join<SiteData, Study> stu = siteData.join("study",JoinType.LEFT);
Join<Study, Publication> pub = stu.join("publications",JoinType.LEFT);
List<Predicate> predicates = new ArrayList<>();
int index = 0;
for(Filter filter : listFilters){
if("country".equals(filter.getName()))
predicates.add(cb.equal(loc.get("country"), cb.parameter(String.class, filter.getName())));
else if("category".equals(filter.getName()))
predicates.add(cb.equal(cat.get("name"), cb.parameter(String.class, filter.getName())));
else if("studyRef".equals(filter.getName()))
predicates.add(cb.equal(stu.get("ref"), cb.parameter(String.class, filter.getName())));
else if("studyType".equals(filter.getName()))
predicates.add(cb.equal(stu.get("studyType"), cb.parameter(String.class, filter.getName())));
else if("pubMedId".equals(filter.getName()))
predicates.add(cb.equal(pub.get("pubMedId"), cb.parameter(Integer.class, filter.getName())));
index++;
}
cq.where(cb.and(predicates.toArray(new Predicate[0])));
return em.createQuery(cq);
}
}
So, if anyone could throw some light on to this, it would be very helpful!
I Edit to add the main exception it throws:
Caused by: org.hibernate.QueryException: could not resolve property: publications of: org.wwarn.vivax.manager.domain.Study
at org.hibernate.persister.entity.AbstractPropertyMapping.propertyException(AbstractPropertyMapping.java:83)
at org.hibernate.persister.entity.AbstractPropertyMapping.toType(AbstractPropertyMapping.java:77)
at org.hibernate.persister.entity.AbstractEntityPersister.toType(AbstractEntityPersister.java:1978)
at org.hibernate.hql.internal.ast.tree.FromElementType.getPropertyType(FromElementType.java:367)
You have a typo in your entity definition: "publicationss" instead of "publications". Since Hibernate uses JavaBeans properties for data access, it complains about getPublications() loss in your definition.
Metamodel preserves you from such typos, consider using it.

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