Hibernate error: found shared references - java

Request processing failed; nested exception is
org.springframework.orm.hibernate5.HibernateSystemException: Found
shared references to a collection:
sabeja.entity.ClassificatorObject.apartmentPayers; nested exception is
org.hibernate.HibernateException: Found shared references to a
collection: sabeja.entity.ClassificatorObject.apartmentPayers
I have been searching solution for 2 days. I found solutions in the stackoverflow, but they didn't help for me. I disabled parts of code, but I haven't caught problem.
ClassificatorObject Entity
package xm.entity;
import java.io.Serializable;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.OrderBy;
import javax.persistence.Table;
#Entity
#Table(name="managment_responsibilities_object")
public class ClassificatorObject implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="responsibility_id")
private int responsibilityId;
#Column(name="object_id")
private int objectId;
#Column(name="is_enabled")
private int isEnabled;
#Column(name="by_area")
private int byArea;
#Column(name="by_people")
private int byPeople;
#Column(name="by_flat")
private int byFlat;
#Column(name="is_general")
private int isGeneral;
#Column(name="sort")
private int sort;
#Column(name="not_counting")
private int notCounting;
// #OneToMany(fetch = FetchType.LAZY, mappedBy = "classificatorObject", cascade = CascadeType.ALL)
// #OrderBy("month")
// private Set<ServicePeriod> periods;
#OneToMany(fetch = FetchType.LAZY)
#JoinColumn(name = "service_id", insertable=false, updatable=false)
private Set<ServiceOption> options;
#OneToMany(fetch = FetchType.LAZY)
//#JoinColumn(name = "service_id", insertable=false, updatable=false)
#JoinColumn(
name = "object_id",
referencedColumnName = "object_id",
insertable=false, updatable=false
)
private Set<ApartmentPayer> apartmentPayers;
public Set<ApartmentPayer> getApartmentPayers() {
return apartmentPayers;
}
public void setApartmentPayers(Set<ApartmentPayer> apartmentPayers) {
this.apartmentPayers = apartmentPayers;
}
#Column(name="parent_service_id")
private int parentServiceId;
#Column(name="has_children")
private int hasChildren;
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name="responsibility_id", insertable=false, updatable=false)
private Classificator classificator;
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name="parent_service_id", insertable=false, updatable=false)
private ClassificatorObject parentService;
//CONSTRUCTORS:
public ClassificatorObject() {
}
public ClassificatorObject(int responsibilityId, int objectId, int isEnabled, int byArea, int byPeople, int byFlat,
int isGeneral, int sort, int notCounting, Set<ServicePeriod> periods, Set<ServiceOption> options,
int parentServiceId, int hasChildren, Classificator classificator) {
super();
this.responsibilityId = responsibilityId;
this.objectId = objectId;
this.isEnabled = isEnabled;
this.byArea = byArea;
this.byPeople = byPeople;
this.byFlat = byFlat;
this.isGeneral = isGeneral;
this.sort = sort;
this.notCounting = notCounting;
// this.periods = periods;
this.options = options;
this.parentServiceId = parentServiceId;
this.hasChildren = hasChildren;
this.classificator = classificator;
}
//GETTERS SETTERS:
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getResponsibilityId() {
return responsibilityId;
}
public void setResponsibilityId(int responsibilityId) {
this.responsibilityId = responsibilityId;
}
public int getObjectId() {
return objectId;
}
public void setObjectId(int objectId) {
this.objectId = objectId;
}
public int getIsEnabled() {
return isEnabled;
}
public void setIsEnabled(int isEnabled) {
this.isEnabled = isEnabled;
}
public int getByArea() {
return byArea;
}
public void setByArea(int byArea) {
this.byArea = byArea;
}
public int getByPeople() {
return byPeople;
}
public void setByPeople(int byPeople) {
this.byPeople = byPeople;
}
public int getByFlat() {
return byFlat;
}
public void setByFlat(int byFlat) {
this.byFlat = byFlat;
}
public int getIsGeneral() {
return isGeneral;
}
public void setIsGeneral(int isGeneral) {
this.isGeneral = isGeneral;
}
public int getSort() {
return sort;
}
public void setSort(int sort) {
this.sort = sort;
}
public int getNotCounting() {
return notCounting;
}
public void setNotCounting(int notCounting) {
this.notCounting = notCounting;
}
// public Set<ServicePeriod> getPeriods() {
// return periods;
// }
//
// public void setPeriods(Set<ServicePeriod> periods) {
// this.periods = periods;
// }
public Set<ServiceOption> getOptions() {
return options;
}
public void setOptions(Set<ServiceOption> options) {
this.options = options;
}
public int getParentServiceId() {
return parentServiceId;
}
public void setParentServiceId(int parentServiceId) {
this.parentServiceId = parentServiceId;
}
public int getHasChildren() {
return hasChildren;
}
public void setHasChildren(int hasChildren) {
this.hasChildren = hasChildren;
}
public Classificator getClassificator() {
return classificator;
}
public void setClassificator(Classificator classificator) {
this.classificator = classificator;
}
public ClassificatorObject getParentService() {
return parentService;
}
public void setParentService(ClassificatorObject parentService) {
this.parentService = parentService;
}
#Override
public String toString() {
return "ClassificatorObject [id=" + id + ", responsibilityId=" + responsibilityId + ", objectId=" + objectId
+ ", isEnabled=" + isEnabled + ", byArea=" + byArea + ", byPeople=" + byPeople + ", byFlat=" + byFlat
+ ", isGeneral=" + isGeneral + ", sort=" + sort + ", notCounting=" + notCounting + ", parentServiceId="
+ parentServiceId + ", hasChildren=" + hasChildren + "]";
}
}
ApartmentPayer Entity
package sabeja.entity;
import java.math.BigDecimal;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name="sb_flat_payers")
public class ApartmentPayer {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private Integer id;
#Column(name="flat_id")
private int flatId;
#Column(name="payer_id")
private int payerId;
#Column(name="object_id")
private int objectId;
#Column(name="area", columnDefinition="Decimal(12,2)")
private BigDecimal area;
#Column(name="people_number")
private int peopleNumber;
#OneToMany(fetch = FetchType.LAZY)
#JoinColumn(name="flatPayer_id", insertable=false, updatable=false)
private Set<ServiceOption> options;
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name="payer_id", insertable= false, updatable= false)
private User user;
// #ManyToOne(fetch = FetchType.LAZY)
// #JoinColumn(name="object_id", insertable=false, updatable=false)
// private TheObject theObject;
public ApartmentPayer() {
super();
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Set<ServiceOption> getOptions() {
return options;
}
public void setOptions(Set<ServiceOption> options) {
this.options = options;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public int getFlatId() {
return flatId;
}
public void setFlatId(int flatId) {
this.flatId = flatId;
}
public int getPayerId() {
return payerId;
}
public void setPayerId(int payerId) {
this.payerId = payerId;
}
public BigDecimal getArea() {
return area;
}
public void setArea(BigDecimal area) {
this.area = area;
}
public int getPeopleNumber() {
return peopleNumber;
}
public void setPeopleNumber(int peopleNumber) {
this.peopleNumber = peopleNumber;
}
public int getObjectId() {
return objectId;
}
public void setObjectId(int objectId) {
this.objectId = objectId;
}
// public TheObject getTheObject() {
// return theObject;
// }
//
//
//
// public void setTheObject(TheObject theObject) {
// this.theObject = theObject;
// }
#Override
public String toString() {
return "ApartmentPayer [id=" + id + ", flatId=" + flatId + ", payerId=" + payerId + ", area=" + area
+ ", peopleNumber=" + peopleNumber + "]";
}
}
DAOIMPL
Query<Apartment> queryResult2 = currentSession
.createQuery("SELECT DISTINCT a FROM Apartment a "
+ "JOIN FETCH a.theObject o "
+ "JOIN FETCH o.services s "
+ "JOIN FETCH s.apartmentPayers ap "
// + "LEFT JOIN FETCH s.options op "
// + "JOIN ServicePeriod p ON s.id = p.responsibilities_object_id "
// + "JOIN FETCH ap.user u "
+ "WHERE a.houseId = :object_id "
// + "AND (op.flatPayerId = ap.id OR op.id is NULL) "
//+ "AND (SELECT count(*) FROM DisabledPayer di WHERE di.serviceId = s.id AND di.flatPayerId = ap.id) = 0"
// + "AND (CASE WHEN op.is_disabled = 0 THEN 1 WHEN op.is_disabled = 1 "
// + "THEN 0 END) = 1) OR op.id IS NULL"
, Apartment.class);

This error can happen in some specific cases when you have kind of a 'loop' reference, but in this case you don't have a class with a field that uses this same class.
So the error has to be in a call to the method setApartmentPayers(), you need to check all the calls to the method and ensure that you are not assigning the same collection to two different entities.

Related

how to fetch all data from database using one to many relation hibernate query

I have two table Parent table is Credit in that table only one row of data is there and another one is child table Debit that contains multiple row of data. how to fetch data from two table which has to match id of parent class and child class and no duplicate is shown from parent class.
I have try with (from Credit,debit) but that can display with duplicate and not properly data is shown based on id.
package com.rojmat.entity;
import java.util.ArrayList;
import java.util.Arrays;
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 org.springframework.core.annotation.Order;
#Entity
#Table(name="credit")
public class Credit extends BaseEntity{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private long cid;
#Column #Order
private long openingbalance;
#Column
private Date date;
#Column #Order
private long debittotal;
#Column #Order
private long drawertotal;
#Column #Order
private long debittotalplusdrawertotal;
#Column #Order
private long todaybusiness;
#OneToMany(cascade={CascadeType.ALL})
#JoinTable(name="credit_debit",
joinColumns=#JoinColumn(name="c_id"),
inverseJoinColumns=#JoinColumn(name="d_id"))
/*#JoinColumn(name="cid", referencedColumnName="cid")*/
private List<Debit> debits = new ArrayList<Debit>(Arrays.asList());
public Credit() {
}
public Credit(long cid, long openingbalance, Date date, long debittotal, long drawertotal,
long debittotalplusdrawertotal, long todaybusiness, List<Debit> debits) {
super();
this.cid = cid;
this.openingbalance = openingbalance;
this.date = date;
this.debittotal = debittotal;
this.drawertotal = drawertotal;
this.debittotalplusdrawertotal = debittotalplusdrawertotal;
this.todaybusiness = todaybusiness;
this.debits = debits;
}
public long getCid() {
return cid;
}
public void setCid(long cid) {
this.cid = cid;
}
public long getOpeningbalance() {
return openingbalance;
}
public void setOpeningbalance(long openingbalance) {
this.openingbalance = openingbalance;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public long getDebittotal() {
return debittotal;
}
public void setDebittotal(long debittotal) {
this.debittotal = debittotal;
}
public long getDrawertotal() {
return drawertotal;
}
public void setDrawertotal(long drawertotal) {
this.drawertotal = drawertotal;
}
public long getDebittotalplusdrawertotal() {
return debittotalplusdrawertotal;
}
public void setDebittotalplusdrawertotal(long debittotalplusdrawertotal) {
this.debittotalplusdrawertotal = debittotalplusdrawertotal;
}
public long getTodaybusiness() {
return todaybusiness;
}
public void setTodaybusiness(long todaybusiness) {
this.todaybusiness = todaybusiness;
}
public List<Debit> getDebit() {
return debits;
}
public void setDebit(List<Debit> debit) {
this.debits = debits;
}
/*#Override
public String toString() {
return "Credit [cid=" + cid + ", openingbalance =" + openingbalance + ", date=" + date + ", debittotal= " + debittotal + ", debittotalplusdrawertotal=" + debittotalplusdrawertotal + ", todaybusiness=" + todaybusiness + "]";
}*/
}
package com.rojmat.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="debit")
public class Debit {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private long did;
#Column
private String amount;
#Column
private String description;
public Debit() {
}
public Debit(String amount, String description) {
super();
this.amount = amount;
this.description = description;
}
public long getDid() {
return did;
}
public void setDid(long did) {
this.did = did;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "Debit [did=" + did + ", amount =" + amount + ", description=" + description + "]";
}
}
1.CreditDaoImpl.java
package com.rojmat.daoImpl;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.rojmat.dao.CreditDao;
import com.rojmat.entity.Credit;
#Repository
public class CreditDaoImpl implements CreditDao{
#Autowired
private SessionFactory sessionFactory;
#Override
public void addCreditDebit(Credit credit) {
try {
sessionFactory.getCurrentSession().saveOrUpdate(credit);
} catch(Exception e) {
e.printStackTrace();
}
}
#Override
public void deleteCreditDebit(int cid) {
/*Credit credit = (Credit)sessionFactory.getCurrentSession().createQuery("from Credit as c LEFT JOIN FETCH c.Debit where c.cid="+cid).uniqueResult();
List<Debit> debits = credit.getDebit();
sessionFactory.getCurrentSession().delete(credit);
debits.forEach((debit) -> {
sessionFactory.getCurrentSession().delete(debit);
});*/
}
#SuppressWarnings("unchecked")
#Override
public List<Credit> getAllCreditDebit() {
List<Credit> credit = sessionFactory.getCurrentSession().createQuery("from Credit,Debit").list();
return credit;
}
}
try this example: you put "distinct" before the property you do not want to be duplicated
//SQL query
select distinct credit.idCredit as idCredit from Credit credit Left Join Debit debit on credit.idCredit= debit.idCredit
//HQL query
#Entity(name = "Credit")
#Table(name = "Credit")
public class Credit{
//if you put #Id --> HQL Query "select credit from Credit credit"
#Column(name = "idCredit")
private Long idCredit;
#Column(name = "label")
private String label;
#OneToMany
#JoinColumns({#JoinColumn(name = "idCredit" ,referencedColumnName = "idCredit")})
List<Debit> debits;
...
}
public class Debit{
....
#Column(name = "idCredit")
private Long idCredit;
...
}
Query query = getSession().createQuery("select distinct credit.idCredit as idCredit, credit.label as label, credit.debits as debits from Credit credit ");
query.setResultTransformer(Transformers.aliasToBean(Credit.class));
return query.list();
package com.rojmat.entity;
import java.util.ArrayList;
import java.util.Arrays;
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 org.springframework.core.annotation.Order;
#Entity
#Table(name="credit")
public class Credit extends BaseEntity{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private long cid;
#Column #Order
private long openingbalance;
#Column
private Date date;
#Column #Order
private long debittotal;
#Column #Order
private long drawertotal;
#Column #Order
private long debittotalplusdrawertotal;
#Column #Order
private long todaybusiness;
#OneToMany(cascade={CascadeType.ALL})
#JoinTable(name="credit_debit",
joinColumns=#JoinColumn(name="c_id"),
inverseJoinColumns=#JoinColumn(name="d_id"))
/*#JoinColumn(name="cid", referencedColumnName="cid")*/
private List<Debit> debits = new ArrayList<Debit>(Arrays.asList());
public Credit() {
}
public Credit(long cid, long openingbalance, Date date, long debittotal, long drawertotal,
long debittotalplusdrawertotal, long todaybusiness, List<Debit> debits) {
super();
this.cid = cid;
this.openingbalance = openingbalance;
this.date = date;
this.debittotal = debittotal;
this.drawertotal = drawertotal;
this.debittotalplusdrawertotal = debittotalplusdrawertotal;
this.todaybusiness = todaybusiness;
this.debits = debits;
}
public long getCid() {
return cid;
}
public void setCid(long cid) {
this.cid = cid;
}
public long getOpeningbalance() {
return openingbalance;
}
public void setOpeningbalance(long openingbalance) {
this.openingbalance = openingbalance;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public long getDebittotal() {
return debittotal;
}
public void setDebittotal(long debittotal) {
this.debittotal = debittotal;
}
public long getDrawertotal() {
return drawertotal;
}
public void setDrawertotal(long drawertotal) {
this.drawertotal = drawertotal;
}
public long getDebittotalplusdrawertotal() {
return debittotalplusdrawertotal;
}
public void setDebittotalplusdrawertotal(long debittotalplusdrawertotal) {
this.debittotalplusdrawertotal = debittotalplusdrawertotal;
}
public long getTodaybusiness() {
return todaybusiness;
}
public void setTodaybusiness(long todaybusiness) {
this.todaybusiness = todaybusiness;
}
public List<Debit> getDebit() {
return debits;
}
public void setDebit(List<Debit> debit) {
this.debits = debits;
}
/*#Override
public String toString() {
return "Credit [cid=" + cid + ", openingbalance =" + openingbalance + ", date=" + date + ", debittotal= " + debittotal + ", debittotalplusdrawertotal=" + debittotalplusdrawertotal + ", todaybusiness=" + todaybusiness + "]";
}*/
}
package com.rojmat.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="debit")
public class Debit {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private long did;
#Column
private String amount;
#Column
private String description;
public Debit() {
}
public Debit(String amount, String description) {
super();
this.amount = amount;
this.description = description;
}
public long getDid() {
return did;
}
public void setDid(long did) {
this.did = did;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
/*#Override
public String toString() {
return "Debit [did=" + did + ", amount =" + amount + ", description=" + description + "]";
}*/
}

Select key from jsonb postgreSQL using Hibernate Criteria query in Java

I am writing the criteria query to get results for jsonb in postgres.I can query the jsonb column through hibernate.I am unable to fetch jsonb specific keys.I am not able to find a way.
I have tried native query but i want some wayout in hibernate criteria query.The commonjson argument is the jsonb in postgresql is this --
{"appl_id": 726516, "applied_by": "pankajkumarnnl94#gmail.com", "service_id": 9880004, "version_no": 4, "appl_ref_no": "BSEH/2018/00728", "sub_version": 1, "payment_date": "2018-12-04T11:54:20.24+05:30", "payment_mode": "PayUbizz", "reference_no": "7726929249", "service_name": "Migration Certificate Board of School Education Haryana, Bhiwani", "department_id": 784, "location_value": 1218758, "base_service_id": 988, "department_name": " Board of School Education Haryana", "registration_id": "", "submission_date": "2018-12-04", "submission_mode": "online", "no_of_attachment": 2, "submission_location": "1578947~1218758~Board of School Education Haryana"}
Model Class ->ApplInfoJson
package com.saral.reporting.model;
import java.util.Map;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Type;
import com.fasterxml.jackson.annotation.JsonProperty;
#Entity
#Table(name = "r_app_json",schema="saral1", catalog="saral1")
public class ApplInfoJson {
#Id
#Column(name = "aid")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long aid;
#Column(name = "id")
private Long id;
#JsonProperty("appl_info")
#Column(name = "appl_info")
private String applInfo;
#Column(name = "application_form_attributes")
private String applicationFormAttributes;
#Column(name = "enclosure_data")
private String enclosureData;
#Column(name = "service_id")
private Long serviceId;
#Column(name = "combined_json")
#Type(type = "JsonDataUserType")
private Map<String , Object> combinedJson;
#Column(name ="location_value")
private Long locationValue;
public Long getLocationValue() {
return locationValue;
}
public void setLocationValue(Long locationValue) {
this.locationValue = locationValue;
}
public Long getServiceId() {
return serviceId;
}
public void setServiceId(Long serviceId) {
this.serviceId = serviceId;
}
public Long getAid() {
return aid;
}
public void setAid(Long aid) {
this.aid = aid;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getApplInfo() {
return applInfo;
}
public void setApplInfo(String applInfo) {
this.applInfo = applInfo;
}
public String getApplicationFormAttributes() {
return applicationFormAttributes;
}
public void setApplicationFormAttributes(String applicationFormAttributes) {
this.applicationFormAttributes = applicationFormAttributes;
}
public String getEnclosureData() {
return enclosureData;
}
public void setEnclosureData(String enclosureData) {
this.enclosureData = enclosureData;
}
public Map<String, Object> getCombinedJson() {
return combinedJson;
}
public void setCombinedJson(Map<String, Object> combinedJson) {
this.combinedJson = combinedJson;
}
#Override
public String toString() {
return "ApplInfoJson [aid=" + aid + ", id=" + id + ", applInfo=" + applInfo + ", applicationFormAttributes="
+ applicationFormAttributes + ", enclosureData=" + enclosureData + ", serviceId=" + serviceId
+ ", combinedJson=" + combinedJson + ", locationValue=" + locationValue + "]";
}
}
Function Used->
public List<ApplInfoJson> findByCombinedJson(String commonJson) {
DetachedCriteria criteria = DetachedCriteria.forClass(ApplInfoJson.class);
List<ApplInfoJson> results = (List<ApplInfoJson>) getHibernateTemplate().findByCriteria(criteria);
return results;
}
I want some thing to pass key name and get data with specific key.

Persistence entities not serializable

I am getting following error:
SEVERE: null
javax.jms.MessageFormatException: [C4017]: Invalid message format.
at com.sun.messaging.jmq.jmsclient.MapMessageImpl.checkValidObjectType(MapMessageImpl.java:653)
at com.sun.messaging.jmq.jmsclient.MapMessageImpl.setObject(MapMessageImpl.java:632)
at buyer.Main.sendCart(Main.java:287)
after I try to send Persistence object through MapMessage in JMS system. And I am not quite sure why it happens since MapMessage accepts only serializable objects for value, and Persistence entities are serializable. I would appreciate any help! My Java code is following.
package entities;
import java.io.Serializable;
import java.util.List;
import java.util.Objects;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
#Entity
#Table(name = "carts")
#NamedQuery(
name = "carts.findAll",
query = "select c from Cart c"
)
public class Cart implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "buyer_id")
private Long buyerId;
#Column(name = "card_id")
private Long cardId;
#Column(name = "successful")
private boolean successful;
#ManyToOne(cascade = CascadeType.REFRESH, fetch = FetchType.EAGER)
#PrimaryKeyJoinColumn(name = "buyer_id")
private Buyer buyer;
#ManyToOne(cascade = CascadeType.REFRESH, fetch = FetchType.EAGER)
#PrimaryKeyJoinColumn(name = "card_id")
private Card card;
#OneToMany(mappedBy = "cart", cascade = CascadeType.REFRESH, fetch = FetchType.EAGER)
private List<CartItem> cartItems;
public Cart() {
}
public Cart(Long buyerId, Long cardId, boolean successful) {
this.buyerId = buyerId;
this.cardId = cardId;
this.successful = successful;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getBuyerId() {
return buyerId;
}
public void setBuyerId(Long buyerId) {
this.buyerId = buyerId;
}
public Long getCardId() {
return cardId;
}
public void setCardId(Long cardId) {
this.cardId = cardId;
}
public boolean isSuccessful() {
return successful;
}
public void setSuccessful(boolean successful) {
this.successful = successful;
}
public Buyer getBuyer() {
return buyer;
}
public void setBuyer(Buyer buyer) {
this.buyer = buyer;
}
public Card getCard() {
return card;
}
public void setCard(Card card) {
this.card = card;
}
public List<CartItem> getCartItems() {
return cartItems;
}
public void setCartItems(List<CartItem> cartItems) {
this.cartItems = cartItems;
}
#Override
public int hashCode() {
int hash = 7;
hash = 53 * hash + Objects.hashCode(this.id);
hash = 53 * hash + Objects.hashCode(this.buyerId);
hash = 53 * hash + Objects.hashCode(this.cardId);
hash = 53 * hash + (this.successful ? 1 : 0);
return hash;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Cart other = (Cart) obj;
if (this.successful != other.successful) {
return false;
}
if (!Objects.equals(this.id, other.id)) {
return false;
}
if (!Objects.equals(this.buyerId, other.buyerId)) {
return false;
}
if (!Objects.equals(this.cardId, other.cardId)) {
return false;
}
return true;
}
#Override
public String toString() {
return "Cart{" + "id=" + id + ", buyerId=" + buyerId + ", cardId=" + cardId + ", successful=" + successful + '}';
}
}
Relevant method that sends message.
private static Buyer sendCart(Cart cart, String tempId, Buyer buyer) {
JMSContext context = connectionFactory.createContext(2);
try {
Destination queue = context.createQueue("mediator");
JMSProducer producer = context.createProducer();
MapMessage message = context.createMapMessage();
message.setObject("data", cart);
message.setObject("tempid", tempId);
message.setObject("type", MessageType.BUYER_SENDING_CART);
producer.send(queue, message);
} catch (JMSException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
The Problem is the MapMessage. According to JavaDoc:
A MapMessage object is used to send a set of name-value pairs. The
names are String objects, and the values are primitive data types in
the Java programming language. The names must have a value that is not
null, and not an empty string. The entries can be accessed
sequentially or randomly by name. The order of the entries is
undefined. MapMessage inherits from the Message interface and adds a
message body that contains a Map.
And:
They may also be read or written generically as objects.
So even if MapMessage offers an "setObject" Method, the parameter used must be a primitive Type.
To pass non-primitive Types use ObjectMessage

hibernate relations in mysql

I am trying to map the pojo class to my mysql database, but i always get an error when i want to get users:
java.sql.SQLSyntaxErrorException: Unknown column 'user0_.Report_id' in 'field list'
This is how the database looks like this:
database
And these are the pojo classes:
Order
package com.latinon.reportator.model;
import java.math.BigInteger;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* #author sistemas
*
*/
#Entity
#Table(name="Order")
public class Order {
private Integer id;
private Date startDate;
private Date endDate;
private BigInteger imperssions;
private String zone;
private int monetization;
private String adUnit;
private String unit;
private String adFormat;
private Double totalAmount;
private Integer platform;
private Double value;
private String valueMesure;
private Set<Device> orderDevices = new HashSet<Device>(0);
private Set<Product> orderProducts = new HashSet<Product>(0);
private Set<Report> orderReport = new HashSet<Report>(0);
private Set<User> orderUsers = new HashSet<User>(0);
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="Order_id")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Temporal(TemporalType.DATE)
#Column(name="Order_start_date", nullable=false)
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
#Temporal(TemporalType.DATE)
#Column(name="Order_end_date")
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
#Column(name="Order_impressions", nullable=false)
public BigInteger getImperssions() {
return imperssions;
}
public void setImperssions(BigInteger imperssions) {
this.imperssions = imperssions;
}
#Column(name="Order_zone")
public String getZone() {
return zone;
}
public void setZone(String zone) {
this.zone = zone;
}
#Column(name="Order_monetization",nullable=false)
public int getMonetization() {
return monetization;
}
public void setMonetization(int monetization) {
this.monetization = monetization;
}
#Column(name="Order_ad_unit")
public String getAdUnit() {
return adUnit;
}
public void setAdUnit(String adUnit) {
this.adUnit = adUnit;
}
#Column(name="Order_unit",nullable=false)
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
#Column(name="Order_ad_format", nullable=false)
public String getAdFormat() {
return adFormat;
}
public void setAdFormat(String adFormat) {
this.adFormat = adFormat;
}
#Column(name="Order_total_amount", nullable=false)
public Double getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(Double totalAmount) {
this.totalAmount = totalAmount;
}
#Column(name="Order_platform", nullable=false)
public Integer getPlatform() {
return platform;
}
public void setPlatform(Integer platform) {
this.platform = platform;
}
#Column(name="Order_value", nullable=false)
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
#Column(name="Order_value_mesure",nullable=false)
public String getValueMesure() {
return valueMesure;
}
public void setValueMesure(String valueMesure) {
this.valueMesure = valueMesure;
}
#ManyToMany(fetch=FetchType.LAZY)
#JoinTable(name="Order_Device", joinColumns={
#JoinColumn(name="Order_Device_Order_id")
})
public Set<Device> getOrderDevices() {
return orderDevices;
}
public void setOrderDevices(Set<Device> orderDevices) {
this.orderDevices = orderDevices;
}
#ManyToMany(fetch=FetchType.LAZY)
#JoinTable(name="Order_Product", joinColumns={
#JoinColumn(name="Order_Product_Order_id")
})
public Set<Product> getOrderProducts() {
return orderProducts;
}
public void setOrderProducts(Set<Product> orderProducts) {
this.orderProducts = orderProducts;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "orderId")
public Set<Report> getOrderReport() {
return orderReport;
}
public void setOrderReport(Set<Report> orderReport) {
this.orderReport = orderReport;
}
#ManyToMany(fetch=FetchType.LAZY, mappedBy="userOrders")
public Set<User> getOrderUsers() {
return orderUsers;
}
public void setOrderUsers(Set<User> orderUsers) {
this.orderUsers = orderUsers;
}
#Override
public String toString() {
return "Order [id=" + id + ", startDate=" + startDate + ", endDate=" + endDate + ", imperssions=" + imperssions
+ ", zone=" + zone + ", monetization=" + monetization + ", adUnit=" + adUnit + ", unit=" + unit
+ ", adFormat=" + adFormat + ", totalAmount=" + totalAmount + ", platform=" + platform + ", value="
+ value + ", valueMesure=" + valueMesure + "]";
}
}
Report pojo:
package com.latinon.reportator.model;
import java.math.BigInteger;
import java.util.Date;
import javax.persistence.*;
/**
* #author sistemas
*
*/
#Entity
#Table(name="User")
public class Report {
private Integer id;
private BigInteger impressions;
private Date date;
private Double grossRevenue;
private Double latinonRevenue;
private Double userRevenue;
private Double fillRate;
private BigInteger completion25;
private BigInteger completion50;
private BigInteger completion75;
private BigInteger completion100;
private BigInteger requests;
private String zone;
private Double cpm;
private Order orderId;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="Report_id")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name="Report_impressions")
public BigInteger getImpressions() {
return impressions;
}
public void setImpressions(BigInteger impressions) {
this.impressions = impressions;
}
#Temporal(TemporalType.DATE)
#Column(name="Report_date")
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
#Column(name="Report_gross_revenue")
public Double getGrossRevenue() {
return grossRevenue;
}
public void setGrossRevenue(Double grossRevenue) {
this.grossRevenue = grossRevenue;
}
#Column(name="Report_latinon_revenue")
public Double getLatinonRevenue() {
return latinonRevenue;
}
public void setLatinonRevenue(Double latinonRevenue) {
this.latinonRevenue = latinonRevenue;
}
#Column(name="Report_user_revenue")
public Double getUserRevenue() {
return userRevenue;
}
public void setUserRevenue(Double userRevenue) {
this.userRevenue = userRevenue;
}
#Column(name="Report_fill_rate")
public Double getFillRate() {
return fillRate;
}
public void setFillRate(Double fillRate) {
this.fillRate = fillRate;
}
#Column(name="Report_completion_25")
public BigInteger getCompletion25() {
return completion25;
}
public void setCompletion25(BigInteger completion25) {
this.completion25 = completion25;
}
#Column(name="Report_completion_50")
public BigInteger getCompletion50() {
return completion50;
}
public void setCompletion50(BigInteger completion50) {
this.completion50 = completion50;
}
#Column(name="Report_completion_75")
public BigInteger getCompletion75() {
return completion75;
}
public void setCompletion75(BigInteger completion75) {
this.completion75 = completion75;
}
#Column(name="Report_completion_100")
public BigInteger getCompletion100() {
return completion100;
}
public void setCompletion100(BigInteger completion100) {
this.completion100 = completion100;
}
#Column(name="Report_request")
public BigInteger getRequests() {
return requests;
}
public void setRequests(BigInteger requests) {
this.requests = requests;
}
#Column(name="Report_zone")
public String getZone() {
return zone;
}
public void setZone(String zone) {
this.zone = zone;
}
#Column(name="Report_cpm")
public Double getCpm() {
return cpm;
}
public void setCpm(Double cpm) {
this.cpm = cpm;
}
#ManyToOne
#JoinColumn(name="Order_Order_id")
public Order getOrderId() {
return orderId;
}
public void setOrderId(Order orderId) {
this.orderId = orderId;
}
#Override
public String toString() {
return "Report [id=" + id + ", impressions=" + impressions + ", date=" + date + ", grossRevenue=" + grossRevenue
+ ", latinonRevenue=" + latinonRevenue + ", userRevenue=" + userRevenue + ", fillRate=" + fillRate
+ ", completion25=" + completion25 + ", completion50=" + completion50 + ", completion75=" + completion75
+ ", completion100=" + completion100 + ", requests=" + requests + ", zone=" + zone + ", cpm=" + cpm
+ ", orderId=" + orderId + "]";
}
}
User pojo:
package com.latinon.reportator.model;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="User")
#Inheritance(strategy=InheritanceType.JOINED)
public class User {
private int id;
private String login;
private String password;
private String email;
private Set<Domain> userDomains = new HashSet<Domain>(0);
private Set<Order> userOrders = new HashSet<Order>(0);
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="User_id",nullable=false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name="User_login", length=45)
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
#Column(name="User_password", length=45)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Column(name="User_mail", length=45)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#ManyToMany(fetch=FetchType.LAZY)
public Set<Domain> getUserDomains() {
return userDomains;
}
public void setUserDomains(Set<Domain> userDomains) {
this.userDomains = userDomains;
}
#ManyToMany(fetch=FetchType.LAZY)
public Set<Order> getUserOrders() {
return userOrders;
}
public void setUserOrders(Set<Order> userOrders) {
this.userOrders = userOrders;
}
#Override
public String toString() {
return "User [id=" + id + ", login=" + login + ", password=" + password + ", email=" + email + "]";
}
}
You have in you Report class #Table(name="User"). is this a typo?

How to use OneToMany and ManyToOne with two entities that result from named queries in JPA

I have this two clases:
package cu.jpa.entities.views;
import cu.jpa.entities.BaseEntity;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import java.util.List;
#Entity
#NamedQuery(
name="SubstanceDescriptionEntity.findAll",
query="select " +
" new cu.jpa.entities.views.SubstanceDescriptionEntity(S.id, S.substanceId) " +
"from " +
" SubstanceEntity S "
)
public class SubstanceDescriptionEntity extends BaseEntity {
private int id;
private String substanceId;
private List<PatternDescriptionEntity> patterns;
public SubstanceDescriptionEntity(int id, String substanceId){
this.id = id;
this.substanceId = substanceId;
}
public SubstanceDescriptionEntity(){
}
#Id
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSubstanceId() {
return substanceId;
}
public void setSubstanceId(String substanceId) {
this.substanceId = substanceId;
}
#OneToMany(mappedBy = "substance")
public List<PatternDescriptionEntity> getPatterns() {
return patterns;
}
public void setPatterns(List<PatternDescriptionEntity> patterns) {
this.patterns = patterns;
}
}
This is class 2:
package cu.jpa.entities.views;
import cu.jpa.entities.BaseEntity;
import javax.persistence.*;
#Entity
#NamedQuery(
name="PatternDescriptionEntity.findAll",
query="select " +
" new cu.jpa.entities.views.PatternDescriptionEntity(P.id, " +
" E.encounterId, " +
" P.patternId, " +
" E.substanceId) " +
"from " +
" PatternEntity P " +
" inner join " +
" P.encounterByEncounterId E " +
" where P.encounterId = E.id "
)
public class PatternDescriptionEntity extends BaseEntity {
private int id;
private String patternId;
private String encounterId;
private int substanceId;
private SubstanceDescriptionEntity substance;
public PatternDescriptionEntity(int id, String encounterId, String patternId, int substanceId){
this.id = id;
this.patternId = patternId;
this.encounterId = encounterId;
this.substanceId = substanceId;
}
public PatternDescriptionEntity(){
}
#Id
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPatternId() {
return patternId;
}
public void setPatternId(String patternId) {
this.patternId = patternId;
}
public String getEncounterId() {
return encounterId;
}
public void setEncounterId(String encounterId) {
this.encounterId = encounterId;
}
public int getSubstanceId() {
return substanceId;
}
public void setSubstanceId(int substanceId) {
this.substanceId = substanceId;
}
#ManyToOne
#JoinColumn(name = "substanceId", insertable = false, updatable = false, referencedColumnName = "substanceId")
public SubstanceDescriptionEntity getSubstance() {
return substance;
}
public void setSubstance(SubstanceDescriptionEntity substance) {
this.substance = substance;
}
}
Both classes are the result of a named query execution. I can get all the elements correctly using this:
#Override
public List<PatternDescriptionEntity> findAll(){
Query query = entityManager.createNamedQuery("PatternDescriptionEntity.findAll",PatternDescriptionEntity.class);
List<PatternDescriptionEntity> items = query.getResultList();
return items;
}
The problem is that I would like to get the reference to the SubstanceDescriptionEntity that corresponds to the PatternDescriptionEntity, according to the details I think I should have placed in #ManyToOne annotation. Both entities are the result of a named query, not of a table mapping. That is why I am having troubles. Because when I execute this test:
#Autowired
PatternDescriptionService service;
#Test
public void test_count_with_filters() throws Exception {
List<PatternDescriptionEntity> patterns = service.findAll();
}
I can see the patterns list with values, but each individual instance of the list has the property substance in null, which means the mapping have some sort of trouble, which I can quite figure it out.
So the question is:
I have these two JPA Entities (not mapped to database tables, but to to named queries result). How can I define the relations of ManyToOne and OneToMany?

Categories