Not able to retrieve grand children in hibernate JPA - java

Configuration has article type as children and article types may have different article types as children.
I am trying to retrieve all configuration and its children (all article type for a configuration).
I don't get parent and child article type here.
I want to retrieve all grant children by using Configuration entity.
This is my configuration entity :-
#Entity
#Table(name = "tbl_configuration")
#XmlRootElement
public class Configuration extends BaseEntity implements Serializable
{
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "config_index")
private Integer configIndex;
#Column(name = "config_nom")
private String configNom;
#Column(name = "config_revision")
private String configRevision;
#JsonManagedReference(value="configuration-article-type")
#OneToMany(mappedBy = "artTypPcIndexConfig", fetch = FetchType.EAGER)
private Collection<ArticleTypeParentChild> articleTypeParentChildCollection;
public Configuration()
{
}
public Configuration(Integer configIndex)
{
this.configIndex = configIndex;
}
public Integer getConfigIndex()
{
return configIndex;
}
public void setConfigIndex(Integer configIndex)
{
this.configIndex = configIndex;
}
public String getConfigNom()
{
return configNom;
}
public void setConfigNom(String configNom)
{
this.configNom = configNom;
}
public String getConfigRevision()
{
return configRevision;
}
public void setConfigRevision(String configRevision)
{
this.configRevision = configRevision;
}
public Collection<ArticleTypeParentChild> getArticleTypeParentChildCollection()
{
return articleTypeParentChildCollection;
}
public void setArticleTypeParentChildCollection(Collection<ArticleTypeParentChild> articleTypeParentChildCollection)
{
this.articleTypeParentChildCollection = articleTypeParentChildCollection;
}
}
ArticleTypeParentChild Table Entity
#Entity
#Table(name = "tbl_article_type_parent_child")
#XmlRootElement
public class ArticleTypeParentChild extends BaseEntity implements Serializable
{
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "art_type_pc_index")
private Integer artTypePcIndex;
#JsonBackReference(value="child-article-type")
#JoinColumn(name = "art_typ_child_index", referencedColumnName = "art_typ_index")
#ManyToOne(fetch = FetchType.EAGER)
private ArticleType artTypChildIndex;
#JsonBackReference(value="parent-article-type")
#JoinColumn(name = "art_typ_parent_index", referencedColumnName = "art_typ_index")
#ManyToOne(fetch = FetchType.EAGER)
private ArticleType artTypParentIndex;
#JsonBackReference(value="configuration-article-type")
#JoinColumn(name = "art_typ_pc_index_config", referencedColumnName = "config_index")
#ManyToOne(fetch = FetchType.EAGER)
private Configuration artTypPcIndexConfig;
public ArticleTypeParentChild()
{
}
public ArticleTypeParentChild(Integer artTypePcIndex)
{
this.artTypePcIndex = artTypePcIndex;
}
public Integer getArtTypePcIndex()
{
return artTypePcIndex;
}
public void setArtTypePcIndex(Integer artTypePcIndex)
{
this.artTypePcIndex = artTypePcIndex;
}
public ArticleType getArtTypChildIndex()
{
return artTypChildIndex;
}
public void setArtTypChildIndex(ArticleType artTypChildIndex)
{
this.artTypChildIndex = artTypChildIndex;
}
public ArticleType getArtTypParentIndex()
{
return artTypParentIndex;
}
public void setArtTypParentIndex(ArticleType artTypParentIndex)
{
this.artTypParentIndex = artTypParentIndex;
}
public Configuration getArtTypPcIndexConfig()
{
return artTypPcIndexConfig;
}
public void setArtTypPcIndexConfig(Configuration artTypPcIndexConfig)
{
this.artTypPcIndexConfig = artTypPcIndexConfig;
}
}
ArticleType Table Entity:-
public class ArticleType extends BaseEntity implements Serializable
{
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "art_typ_index")
private Integer artTypIndex;
#Basic(optional = false)
#Column(name = "art_typ_index_designation")
private int artTypIndexDesignation;
#Basic(optional = false)
#Column(name = "art_typ_code")
private String artTypCode;
#Basic(optional = false)
#Column(name = "art_typ_code_effectivite")
private String artTypCodeEffectivite;
#Basic(optional = false)
#Column(name = "art_typ_numero_serie")
private boolean artTypNumeroSerie;
#Basic(optional = false)
#Column(name = "art_typ_version_materiel")
private boolean artTypVersionMateriel;
#Basic(optional = false)
#Column(name = "art_typ_version_logiciel")
private boolean artTypVersionLogiciel;
#Column(name = "art_typ_index_description")
private String artTypIndexDescription;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "atrIndexArticleType")
private Collection<ArticleTypeReseau> articleTypeReseauCollection;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "atvIndexArticleType")
private Collection<ArticleTypeVariante> articleTypeVarianteCollection;
#JoinColumn(name = "art_typ_index_option", referencedColumnName = "opt_art_index")
#ManyToOne
private OptionArticle artTypIndexOption;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "atpIndexArticleType")
private Collection<ArticleTypeProjet> articleTypeProjetCollection;
#OneToMany(mappedBy = "atvoIndexArticleType")
private Collection<ArticleTypeVarianteOption> articleTypeVarianteOptionCollection;
#JsonManagedReference(value="child-article-type")
#OneToMany(mappedBy = "artTypChildIndex", fetch = FetchType.EAGER)
private Collection<ArticleTypeParentChild> articleTypeChildCollection;
#JsonManagedReference(value="parent-article-type")
#OneToMany(mappedBy = "artTypParentIndex", fetch = FetchType.EAGER)
private Collection<ArticleTypeParentChild> articleTypeParentCollection;
#OneToMany(mappedBy = "atoIndexArtType")
private Collection<ArticleTypeOption> articleTypeOptionCollection;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "locIndexArticleType")
private Collection<Localisation> localisationCollection;
#OneToMany(mappedBy = "atlIndexArticleType")
private Collection<ArticleTypeLocalisation> articleTypeLocalisationCollection;
public ArticleType()
{
}
public ArticleType(Integer artTypIndex)
{
this.artTypIndex = artTypIndex;
}
public ArticleType(Integer artTypIndex, int artTypIndexDesignation, String artTypCode, String artTypCodeEffectivite, boolean artTypNumeroSerie, boolean artTypVersionMateriel, boolean artTypVersionLogiciel)
{
this.artTypIndex = artTypIndex;
this.artTypIndexDesignation = artTypIndexDesignation;
this.artTypCode = artTypCode;
this.artTypCodeEffectivite = artTypCodeEffectivite;
this.artTypNumeroSerie = artTypNumeroSerie;
this.artTypVersionMateriel = artTypVersionMateriel;
this.artTypVersionLogiciel = artTypVersionLogiciel;
}
public Integer getArtTypIndex()
{
return artTypIndex;
}
public void setArtTypIndex(Integer artTypIndex)
{
this.artTypIndex = artTypIndex;
}
public int getArtTypIndexDesignation()
{
return artTypIndexDesignation;
}
public void setArtTypIndexDesignation(int artTypIndexDesignation)
{
this.artTypIndexDesignation = artTypIndexDesignation;
}
public String getArtTypCode()
{
return artTypCode;
}
public void setArtTypCode(String artTypCode)
{
this.artTypCode = artTypCode;
}
public String getArtTypCodeEffectivite()
{
return artTypCodeEffectivite;
}
public void setArtTypCodeEffectivite(String artTypCodeEffectivite)
{
this.artTypCodeEffectivite = artTypCodeEffectivite;
}
public boolean getArtTypNumeroSerie()
{
return artTypNumeroSerie;
}
public void setArtTypNumeroSerie(boolean artTypNumeroSerie)
{
this.artTypNumeroSerie = artTypNumeroSerie;
}
public boolean getArtTypVersionMateriel()
{
return artTypVersionMateriel;
}
public void setArtTypVersionMateriel(boolean artTypVersionMateriel)
{
this.artTypVersionMateriel = artTypVersionMateriel;
}
public boolean getArtTypVersionLogiciel()
{
return artTypVersionLogiciel;
}
public void setArtTypVersionLogiciel(boolean artTypVersionLogiciel)
{
this.artTypVersionLogiciel = artTypVersionLogiciel;
}
public String getArtTypIndexDescription()
{
return artTypIndexDescription;
}
public void setArtTypIndexDescription(String artTypIndexDescription)
{
this.artTypIndexDescription = artTypIndexDescription;
}
#XmlTransient
public Collection<ArticleTypeReseau> getArticleTypeReseauCollection()
{
return articleTypeReseauCollection;
}
public void setArticleTypeReseauCollection(Collection<ArticleTypeReseau> articleTypeReseauCollection)
{
this.articleTypeReseauCollection = articleTypeReseauCollection;
}
#XmlTransient
public Collection<ArticleTypeVariante> getArticleTypeVarianteCollection()
{
return articleTypeVarianteCollection;
}
public void setArticleTypeVarianteCollection(Collection<ArticleTypeVariante> articleTypeVarianteCollection)
{
this.articleTypeVarianteCollection = articleTypeVarianteCollection;
}
public OptionArticle getArtTypIndexOption()
{
return artTypIndexOption;
}
public void setArtTypIndexOption(OptionArticle artTypIndexOption)
{
this.artTypIndexOption = artTypIndexOption;
}
#XmlTransient
public Collection<ArticleTypeProjet> getArticleTypeProjetCollection()
{
return articleTypeProjetCollection;
}
public void setArticleTypeProjetCollection(Collection<ArticleTypeProjet> articleTypeProjetCollection)
{
this.articleTypeProjetCollection = articleTypeProjetCollection;
}
#XmlTransient
public Collection<ArticleTypeVarianteOption> getArticleTypeVarianteOptionCollection()
{
return articleTypeVarianteOptionCollection;
}
public void setArticleTypeVarianteOptionCollection(Collection<ArticleTypeVarianteOption> articleTypeVarianteOptionCollection)
{
this.articleTypeVarianteOptionCollection = articleTypeVarianteOptionCollection;
}
// #XmlTransient
public Collection<ArticleTypeParentChild> getArticleTypeParentChildCollection()
{
return articleTypeChildCollection;
}
public void setArticleTypeParentChildCollection(Collection<ArticleTypeParentChild> articleTypeParentChildCollection)
{
this.articleTypeChildCollection = articleTypeParentChildCollection;
}
// #XmlTransient
public Collection<ArticleTypeParentChild> getArticleTypeParentChildCollection1()
{
return articleTypeParentCollection;
}
public void setArticleTypeParentChildCollection1(Collection<ArticleTypeParentChild> articleTypeParentChildCollection1)
{
this.articleTypeParentCollection = articleTypeParentChildCollection1;
}
#XmlTransient
public Collection<ArticleTypeOption> getArticleTypeOptionCollection()
{
return articleTypeOptionCollection;
}
public void setArticleTypeOptionCollection(Collection<ArticleTypeOption> articleTypeOptionCollection)
{
this.articleTypeOptionCollection = articleTypeOptionCollection;
}
#XmlTransient
public Collection<Localisation> getLocalisationCollection()
{
return localisationCollection;
}
public void setLocalisationCollection(Collection<Localisation> localisationCollection)
{
this.localisationCollection = localisationCollection;
}
#XmlTransient
public Collection<ArticleTypeLocalisation> getArticleTypeLocalisationCollection()
{
return articleTypeLocalisationCollection;
}
public void setArticleTypeLocalisationCollection(Collection<ArticleTypeLocalisation> articleTypeLocalisationCollection)
{
this.articleTypeLocalisationCollection = articleTypeLocalisationCollection;
}
}

Related

Issues with JPA and Hibernate library when perform count statement

For the previous week or so, I have been fruitlessly trying to get this JPA library to work.
I can perform simple queries, e.g. find entity by id, or get a collection of entities, etc, however, when I try to perform more complex queries, I always seem to be encounter an error. Can someone please help with debugging this COUNT statement which produces the following stack trace of errors:
Caused by: org.hibernate.query.sqm.InterpretationException: Error interpreting query [SELECT COUNT(a.id) FROM AgreementEntity a]; this may indicate a semantic (user query) problem or a bug in the parser
Caused by: java.lang.NullPointerException
Here is the code which causes the error:
EntityManager em = getFirstEntityManager();
Session session = em.unwrap(Session.class);
// The following line of code causes an error
session.createQuery("SELECT COUNT(a.id) FROM AgreementEntity a");
And here is the entire AgreementEntity class:
package com.profectus.rdm.entities;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.Objects;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "agreement", schema = "rdm_demovendorxa_prod", catalog = "")
public class AgreementEntity {
private Long id;
private Long version;
private String agreementType;
private Boolean autoextend;
private Boolean isAutoextendAgreement;
private Long parentAgreementId;
private String comments;
private Timestamp creationDate;
private String datasource;
private String description;
private Timestamp endDate;
private String fEmail;
private String fName;
private String fPhone;
private Boolean journal;
private Boolean pdfemail;
private String sEmail;
private String sName;
private String sPhone;
private Timestamp startDate;
private String status;
private String terms;
private String termsAmendments;
private Boolean vendorClaims;
private String notifyEmail;
private Timestamp ceaseDate;
private String sTitle;
private String sMobile;
private String sFax;
private String fTitle;
private String fMobile;
private String fFax;
private String ceaseReason;
private Boolean isCeasedAlerted;
private Integer isExpiringAlerted;
private Timestamp contractEndDate;
private String contractReference;
private String confidenceLevel;
private String collectionMethod;
private Boolean autoextended;
private String arNumber;
private String journalPostingCompanyCode;
private Long marketingEventId;
private UsersEntity usersByLeadBuyerId;
private UsersEntity usersByBuyerId;
private RetailerVendorEntity retailerVendorByRetailerVendorId;
private RetailerVendorEntity retailerVendorByDistributorRetailerVendorId;
private UsersEntity usersByUserId;
private CountryEntity countryByCountryId;
private CountryEntity countryByCountryId_0;
private Collection<AgreementAttachmentEntity> agreementAttachmentsById;
private Collection<AgreementCommentEntity> agreementCommentsById;
private Collection<AgreementCopyEntity> agreementCopiesById;
private Collection<AgreementCopyEntity> agreementCopiesById_0;
// private Collection<AgreementDistributorRetailerVendorEntity> agreementDistributorRetailerVendorsById;
// private Collection<AgreementDistributorVendorGroupEntity> agreementDistributorVendorGroupsById;
private Collection<AgreementHistoryEntity> agreementHistoriesById;
private Collection<AgreementImportEntity> agreementImportsById;
private Collection<AgreementNoteEntity> agreementNotesById;
private Collection<AttachmentEntity> attachmentsById;
private Collection<RuleEntity> rulesById;
private Collection<TierReportResultEntity> tierReportResultsById;
#Id
#Column(name = "id", nullable = false)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Basic
#Column(name = "version", nullable = true)
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
#Basic
#Column(name = "agreement_type", nullable = true, length = 255)
public String getAgreementType() {
return agreementType;
}
public void setAgreementType(String agreementType) {
this.agreementType = agreementType;
}
#Basic
#Column(name = "autoextend", nullable = false)
public Boolean getAutoextend() {
return autoextend;
}
public void setAutoextend(Boolean autoextend) {
this.autoextend = autoextend;
}
#Basic
#Column(name = "is_autoextend_agreement", nullable = true)
public Boolean getAutoextendAgreement() {
return isAutoextendAgreement;
}
public void setAutoextendAgreement(Boolean autoextendAgreement) {
isAutoextendAgreement = autoextendAgreement;
}
#Basic
#Column(name = "parent_agreement_id", nullable = true)
public Long getParentAgreementId() {
return parentAgreementId;
}
public void setParentAgreementId(Long parentAgreementId) {
this.parentAgreementId = parentAgreementId;
}
#Basic
#Column(name = "comments", nullable = true, length = -1)
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
#Basic
#Column(name = "creation_date", nullable = false)
public Timestamp getCreationDate() {
return creationDate;
}
public void setCreationDate(Timestamp creationDate) {
this.creationDate = creationDate;
}
#Basic
#Column(name = "datasource", nullable = false, length = 255)
public String getDatasource() {
return datasource;
}
public void setDatasource(String datasource) {
this.datasource = datasource;
}
#Basic
#Column(name = "description", nullable = true, length = 255)
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Basic
#Column(name = "end_date", nullable = true)
public Timestamp getEndDate() {
return endDate;
}
public void setEndDate(Timestamp endDate) {
this.endDate = endDate;
}
#Basic
#Column(name = "fEmail", nullable = true, length = 255)
public String getfEmail() {
return fEmail;
}
public void setfEmail(String fEmail) {
this.fEmail = fEmail;
}
#Basic
#Column(name = "fName", nullable = true, length = 255)
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
#Basic
#Column(name = "fPhone", nullable = true, length = 255)
public String getfPhone() {
return fPhone;
}
public void setfPhone(String fPhone) {
this.fPhone = fPhone;
}
#Basic
#Column(name = "journal", nullable = false)
public Boolean getJournal() {
return journal;
}
public void setJournal(Boolean journal) {
this.journal = journal;
}
#Basic
#Column(name = "pdfemail", nullable = false)
public Boolean getPdfemail() {
return pdfemail;
}
public void setPdfemail(Boolean pdfemail) {
this.pdfemail = pdfemail;
}
#Basic
#Column(name = "sEmail", nullable = true, length = 255)
public String getsEmail() {
return sEmail;
}
public void setsEmail(String sEmail) {
this.sEmail = sEmail;
}
#Basic
#Column(name = "sName", nullable = true, length = 255)
public String getsName() {
return sName;
}
public void setsName(String sName) {
this.sName = sName;
}
#Basic
#Column(name = "sPhone", nullable = true, length = 255)
public String getsPhone() {
return sPhone;
}
public void setsPhone(String sPhone) {
this.sPhone = sPhone;
}
#Basic
#Column(name = "start_date", nullable = true)
public Timestamp getStartDate() {
return startDate;
}
public void setStartDate(Timestamp startDate) {
this.startDate = startDate;
}
#Basic
#Column(name = "status", nullable = false, length = 255)
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Basic
#Column(name = "terms", nullable = true, length = -1)
public String getTerms() {
return terms;
}
public void setTerms(String terms) {
this.terms = terms;
}
#Basic
#Column(name = "terms_amendments", nullable = true, length = -1)
public String getTermsAmendments() {
return termsAmendments;
}
public void setTermsAmendments(String termsAmendments) {
this.termsAmendments = termsAmendments;
}
#Basic
#Column(name = "vendorClaims", nullable = false)
public Boolean getVendorClaims() {
return vendorClaims;
}
public void setVendorClaims(Boolean vendorClaims) {
this.vendorClaims = vendorClaims;
}
#Basic
#Column(name = "notify_email", nullable = true, length = 512)
public String getNotifyEmail() {
return notifyEmail;
}
public void setNotifyEmail(String notifyEmail) {
this.notifyEmail = notifyEmail;
}
#Basic
#Column(name = "cease_date", nullable = true)
public Timestamp getCeaseDate() {
return ceaseDate;
}
public void setCeaseDate(Timestamp ceaseDate) {
this.ceaseDate = ceaseDate;
}
#Basic
#Column(name = "sTitle", nullable = true, length = 255)
public String getsTitle() {
return sTitle;
}
public void setsTitle(String sTitle) {
this.sTitle = sTitle;
}
#Basic
#Column(name = "sMobile", nullable = true, length = 255)
public String getsMobile() {
return sMobile;
}
public void setsMobile(String sMobile) {
this.sMobile = sMobile;
}
#Basic
#Column(name = "sFax", nullable = true, length = 255)
public String getsFax() {
return sFax;
}
public void setsFax(String sFax) {
this.sFax = sFax;
}
#Basic
#Column(name = "fTitle", nullable = true, length = 255)
public String getfTitle() {
return fTitle;
}
public void setfTitle(String fTitle) {
this.fTitle = fTitle;
}
#Basic
#Column(name = "fMobile", nullable = true, length = 255)
public String getfMobile() {
return fMobile;
}
public void setfMobile(String fMobile) {
this.fMobile = fMobile;
}
#Basic
#Column(name = "fFax", nullable = true, length = 255)
public String getfFax() {
return fFax;
}
public void setfFax(String fFax) {
this.fFax = fFax;
}
#Basic
#Column(name = "cease_reason", nullable = true, length = 255)
public String getCeaseReason() {
return ceaseReason;
}
public void setCeaseReason(String ceaseReason) {
this.ceaseReason = ceaseReason;
}
#Basic
#Column(name = "is_ceased_alerted", nullable = true)
public Boolean getCeasedAlerted() {
return isCeasedAlerted;
}
public void setCeasedAlerted(Boolean ceasedAlerted) {
isCeasedAlerted = ceasedAlerted;
}
#Basic
#Column(name = "is_expiring_alerted", nullable = true)
public Integer getIsExpiringAlerted() {
return isExpiringAlerted;
}
public void setIsExpiringAlerted(Integer isExpiringAlerted) {
this.isExpiringAlerted = isExpiringAlerted;
}
#Basic
#Column(name = "contract_end_date", nullable = true)
public Timestamp getContractEndDate() {
return contractEndDate;
}
public void setContractEndDate(Timestamp contractEndDate) {
this.contractEndDate = contractEndDate;
}
#Basic
#Column(name = "contract_reference", nullable = true, length = 50)
public String getContractReference() {
return contractReference;
}
public void setContractReference(String contractReference) {
this.contractReference = contractReference;
}
#Basic
#Column(name = "confidence_level", nullable = true, length = 50)
public String getConfidenceLevel() {
return confidenceLevel;
}
public void setConfidenceLevel(String confidenceLevel) {
this.confidenceLevel = confidenceLevel;
}
#Basic
#Column(name = "collection_method", nullable = true, length = 2)
public String getCollectionMethod() {
return collectionMethod;
}
public void setCollectionMethod(String collectionMethod) {
this.collectionMethod = collectionMethod;
}
#Basic
#Column(name = "autoextended", nullable = true)
public Boolean getAutoextended() {
return autoextended;
}
public void setAutoextended(Boolean autoextended) {
this.autoextended = autoextended;
}
#Basic
#Column(name = "ar_number", nullable = true, length = 50)
public String getArNumber() {
return arNumber;
}
public void setArNumber(String arNumber) {
this.arNumber = arNumber;
}
#Basic
#Column(name = "journal_posting_company_code", nullable = true, length = 50)
public String getJournalPostingCompanyCode() {
return journalPostingCompanyCode;
}
public void setJournalPostingCompanyCode(String journalPostingCompanyCode) {
this.journalPostingCompanyCode = journalPostingCompanyCode;
}
#Basic
#Column(name = "marketing_event_id", nullable = true)
public Long getMarketingEventId() {
return marketingEventId;
}
public void setMarketingEventId(Long marketingEventId) {
this.marketingEventId = marketingEventId;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AgreementEntity that = (AgreementEntity) o;
return Objects.equals(id, that.id) &&
Objects.equals(version, that.version) &&
Objects.equals(agreementType, that.agreementType) &&
Objects.equals(autoextend, that.autoextend) &&
Objects.equals(isAutoextendAgreement, that.isAutoextendAgreement) &&
Objects.equals(parentAgreementId, that.parentAgreementId) &&
Objects.equals(comments, that.comments) &&
Objects.equals(creationDate, that.creationDate) &&
Objects.equals(datasource, that.datasource) &&
Objects.equals(description, that.description) &&
Objects.equals(endDate, that.endDate) &&
Objects.equals(fEmail, that.fEmail) &&
Objects.equals(fName, that.fName) &&
Objects.equals(fPhone, that.fPhone) &&
Objects.equals(journal, that.journal) &&
Objects.equals(pdfemail, that.pdfemail) &&
Objects.equals(sEmail, that.sEmail) &&
Objects.equals(sName, that.sName) &&
Objects.equals(sPhone, that.sPhone) &&
Objects.equals(startDate, that.startDate) &&
Objects.equals(status, that.status) &&
Objects.equals(terms, that.terms) &&
Objects.equals(termsAmendments, that.termsAmendments) &&
Objects.equals(vendorClaims, that.vendorClaims) &&
Objects.equals(notifyEmail, that.notifyEmail) &&
Objects.equals(ceaseDate, that.ceaseDate) &&
Objects.equals(sTitle, that.sTitle) &&
Objects.equals(sMobile, that.sMobile) &&
Objects.equals(sFax, that.sFax) &&
Objects.equals(fTitle, that.fTitle) &&
Objects.equals(fMobile, that.fMobile) &&
Objects.equals(fFax, that.fFax) &&
Objects.equals(ceaseReason, that.ceaseReason) &&
Objects.equals(isCeasedAlerted, that.isCeasedAlerted) &&
Objects.equals(isExpiringAlerted, that.isExpiringAlerted) &&
Objects.equals(contractEndDate, that.contractEndDate) &&
Objects.equals(contractReference, that.contractReference) &&
Objects.equals(confidenceLevel, that.confidenceLevel) &&
Objects.equals(collectionMethod, that.collectionMethod) &&
Objects.equals(autoextended, that.autoextended) &&
Objects.equals(arNumber, that.arNumber) &&
Objects.equals(journalPostingCompanyCode, that.journalPostingCompanyCode) &&
Objects.equals(marketingEventId, that.marketingEventId);
}
#Override
public int hashCode() {
return Objects.hash(id, version, agreementType, autoextend, isAutoextendAgreement, parentAgreementId, comments, creationDate, datasource, description, endDate, fEmail, fName, fPhone, journal, pdfemail, sEmail, sName, sPhone, startDate, status, terms, termsAmendments, vendorClaims, notifyEmail, ceaseDate, sTitle, sMobile, sFax, fTitle, fMobile, fFax, ceaseReason, isCeasedAlerted, isExpiringAlerted, contractEndDate, contractReference, confidenceLevel, collectionMethod, autoextended, arNumber, journalPostingCompanyCode, marketingEventId);
}
#ManyToOne
#JoinColumn(name = "lead_buyer_id", referencedColumnName = "id")
public UsersEntity getUsersByLeadBuyerId() {
return usersByLeadBuyerId;
}
public void setUsersByLeadBuyerId(UsersEntity usersByLeadBuyerId) {
this.usersByLeadBuyerId = usersByLeadBuyerId;
}
#ManyToOne
#JoinColumn(name = "buyer_id", referencedColumnName = "id")
public UsersEntity getUsersByBuyerId() {
return usersByBuyerId;
}
public void setUsersByBuyerId(UsersEntity usersByBuyerId) {
this.usersByBuyerId = usersByBuyerId;
}
#ManyToOne
#JoinColumn(name = "retailer_vendor_id", referencedColumnName = "id")
public RetailerVendorEntity getRetailerVendorByRetailerVendorId() {
return retailerVendorByRetailerVendorId;
}
public void setRetailerVendorByRetailerVendorId(RetailerVendorEntity retailerVendorByRetailerVendorId) {
this.retailerVendorByRetailerVendorId = retailerVendorByRetailerVendorId;
}
#ManyToOne
#JoinColumn(name = "distributor_retailer_vendor_id", referencedColumnName = "id")
public RetailerVendorEntity getRetailerVendorByDistributorRetailerVendorId() {
return retailerVendorByDistributorRetailerVendorId;
}
public void setRetailerVendorByDistributorRetailerVendorId(RetailerVendorEntity retailerVendorByDistributorRetailerVendorId) {
this.retailerVendorByDistributorRetailerVendorId = retailerVendorByDistributorRetailerVendorId;
}
#ManyToOne
#JoinColumn(name = "user_id", referencedColumnName = "id")
public UsersEntity getUsersByUserId() {
return usersByUserId;
}
public void setUsersByUserId(UsersEntity usersByUserId) {
this.usersByUserId = usersByUserId;
}
#ManyToOne
#JoinColumn(name = "country_id", referencedColumnName = "id")
public CountryEntity getCountryByCountryId() {
return countryByCountryId;
}
public void setCountryByCountryId(CountryEntity countryByCountryId) {
this.countryByCountryId = countryByCountryId;
}
#ManyToOne
#JoinColumn(name = "country_id", referencedColumnName = "id", insertable = false, updatable = false)
public CountryEntity getCountryByCountryId_0() {
return countryByCountryId_0;
}
public void setCountryByCountryId_0(CountryEntity countryByCountryId_0) {
this.countryByCountryId_0 = countryByCountryId_0;
}
#OneToMany(mappedBy = "agreementByAgreementId")
public Collection<AgreementAttachmentEntity> getAgreementAttachmentsById() {
return agreementAttachmentsById;
}
public void setAgreementAttachmentsById(Collection<AgreementAttachmentEntity> agreementAttachmentsById) {
this.agreementAttachmentsById = agreementAttachmentsById;
}
#OneToMany(mappedBy = "agreementByAgreementId")
public Collection<AgreementCommentEntity> getAgreementCommentsById() {
return agreementCommentsById;
}
public void setAgreementCommentsById(Collection<AgreementCommentEntity> agreementCommentsById) {
this.agreementCommentsById = agreementCommentsById;
}
#OneToMany(mappedBy = "agreementByParentAgreementId")
public Collection<AgreementCopyEntity> getAgreementCopiesById() {
return agreementCopiesById;
}
public void setAgreementCopiesById(Collection<AgreementCopyEntity> agreementCopiesById) {
this.agreementCopiesById = agreementCopiesById;
}
#OneToMany(mappedBy = "agreementByChildAgreementId")
public Collection<AgreementCopyEntity> getAgreementCopiesById_0() {
return agreementCopiesById_0;
}
public void setAgreementCopiesById_0(Collection<AgreementCopyEntity> agreementCopiesById_0) {
this.agreementCopiesById_0 = agreementCopiesById_0;
}
// #OneToMany(mappedBy = "agreementByAgreementId")
// public Collection<AgreementDistributorRetailerVendorEntity> getAgreementDistributorRetailerVendorsById() {
// return agreementDistributorRetailerVendorsById;
// }
//
// public void setAgreementDistributorRetailerVendorsById(Collection<AgreementDistributorRetailerVendorEntity> agreementDistributorRetailerVendorsById) {
// this.agreementDistributorRetailerVendorsById = agreementDistributorRetailerVendorsById;
// }
//
// #OneToMany(mappedBy = "agreementByAgreementId")
// public Collection<AgreementDistributorVendorGroupEntity> getAgreementDistributorVendorGroupsById() {
// return agreementDistributorVendorGroupsById;
// }
//
// public void setAgreementDistributorVendorGroupsById(Collection<AgreementDistributorVendorGroupEntity> agreementDistributorVendorGroupsById) {
// this.agreementDistributorVendorGroupsById = agreementDistributorVendorGroupsById;
// }
#OneToMany(mappedBy = "agreementByAgreementId")
public Collection<AgreementHistoryEntity> getAgreementHistoriesById() {
return agreementHistoriesById;
}
public void setAgreementHistoriesById(Collection<AgreementHistoryEntity> agreementHistoriesById) {
this.agreementHistoriesById = agreementHistoriesById;
}
#OneToMany(mappedBy = "agreementByAgreementId")
public Collection<AgreementImportEntity> getAgreementImportsById() {
return agreementImportsById;
}
public void setAgreementImportsById(Collection<AgreementImportEntity> agreementImportsById) {
this.agreementImportsById = agreementImportsById;
}
#OneToMany(mappedBy = "agreementByAgreementId")
public Collection<AgreementNoteEntity> getAgreementNotesById() {
return agreementNotesById;
}
public void setAgreementNotesById(Collection<AgreementNoteEntity> agreementNotesById) {
this.agreementNotesById = agreementNotesById;
}
#OneToMany(mappedBy = "agreementByAgreementId")
public Collection<AttachmentEntity> getAttachmentsById() {
return attachmentsById;
}
public void setAttachmentsById(Collection<AttachmentEntity> attachmentsById) {
this.attachmentsById = attachmentsById;
}
#OneToMany(mappedBy = "agreementByAgreementId")
public Collection<RuleEntity> getRulesById() {
return rulesById;
}
public void setRulesById(Collection<RuleEntity> rulesById) {
this.rulesById = rulesById;
}
#OneToMany(mappedBy = "agreementByAgreementId")
public Collection<TierReportResultEntity> getTierReportResultsById() {
return tierReportResultsById;
}
public void setTierReportResultsById(Collection<TierReportResultEntity> tierReportResultsById) {
this.tierReportResultsById = tierReportResultsById;
}
}
You can try count(a) instead of a.id
EntityManager em = getFirstEntityManager();
Session session = em.unwrap(Session.class);
// The following line of code causes an error
session.createQuery("select count(a) from AgreementEntity a ");
Same problem here with count function and group by. I downgraded to 5.4.10.Final version to make it work.
The issue was that I was using an alpha build of the hibernate library instead of a stable build.

Persisting a table with foreign keys using EJB and JPA

I am new to JavaEE and I am having a problem with persisting a table that has foreign keys pointing to the primary key of another table using entity classes and ejb's entity manager. I am using Netbeans.
I have an entity called 'property' and have another entity called 'offer' which holds the foreign key pointing to the primary key of the property. So basically, the logic is that one property can have many offers. Therefore, I am trying to add new offers in the 'offer' table using the entity manager but I am not being able to do it. You can look at the code and see what I maybe missing.
Property entity:
#Entity
#Table(name = "PROPERTY")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Property.findAll", query = "SELECT p FROM Property p")})
public class Property implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "PROPERTYID")
private Integer propertyid;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 500)
#Column(name = "DESCRIPTION")
private String description;
#Size(max = 50)
#Column(name = "TYPE")
private String type;
#Column(name = "NUMBEROFBEDROOM")
private Integer numberofbedroom;
#Column(name = "NUMBEROFBATHROOM")
private Integer numberofbathroom;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 10)
#Column(name = "ISFURNISHED")
private String isfurnished;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 10)
#Column(name = "HASGARDEN")
private String hasgarden;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 20)
#Column(name = "SIZE")
private String size;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 100)
#Column(name = "PRICE")
private String price;
#Basic(optional = false)
#NotNull
#Column(name = "ENTEREDDATE")
#Temporal(TemporalType.DATE)
private Date entereddate;
#Basic(optional = false)
#NotNull
#Column(name = "ENTEREDTIME")
#Temporal(TemporalType.TIME)
private Date enteredtime;
#OneToOne(cascade = CascadeType.ALL, mappedBy = "property")
private Paddress paddress;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "propertyid")
private Collection<Offer> offerCollection;
#JoinColumn(name = "PROPERTYOWNERID", referencedColumnName = "PROPERTYOWNERID")
#ManyToOne(optional = false)
private Propertyowner propertyownerid;
#JoinColumn(name = "REALESTATEAGENTID", referencedColumnName = "REALESTATEAGENTID")
#ManyToOne(optional = false)
private Realestateagent realestateagentid;
public Property() {
}
public Property(Integer propertyid) {
this.propertyid = propertyid;
}
public Property(Integer propertyid, String description, String isfurnished, String hasgarden, String size, String price, Date entereddate, Date enteredtime) {
this.propertyid = propertyid;
this.description = description;
this.isfurnished = isfurnished;
this.hasgarden = hasgarden;
this.size = size;
this.price = price;
this.entereddate = entereddate;
this.enteredtime = enteredtime;
}
public Integer getPropertyid() {
return propertyid;
}
public void setPropertyid(Integer propertyid) {
this.propertyid = propertyid;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Integer getNumberofbedroom() {
return numberofbedroom;
}
public void setNumberofbedroom(Integer numberofbedroom) {
this.numberofbedroom = numberofbedroom;
}
public Integer getNumberofbathroom() {
return numberofbathroom;
}
public void setNumberofbathroom(Integer numberofbathroom) {
this.numberofbathroom = numberofbathroom;
}
public String getIsfurnished() {
return isfurnished;
}
public void setIsfurnished(String isfurnished) {
this.isfurnished = isfurnished;
}
public String getHasgarden() {
return hasgarden;
}
public void setHasgarden(String hasgarden) {
this.hasgarden = hasgarden;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public Date getEntereddate() {
return entereddate;
}
public void setEntereddate(Date entereddate) {
this.entereddate = entereddate;
}
public Date getEnteredtime() {
return enteredtime;
}
public void setEnteredtime(Date enteredtime) {
this.enteredtime = enteredtime;
}
public Paddress getPaddress() {
return paddress;
}
public void setPaddress(Paddress paddress) {
this.paddress = paddress;
}
#XmlTransient
public Collection<Offer> getOfferCollection() {
return offerCollection;
}
public void setOfferCollection(Collection<Offer> offerCollection) {
this.offerCollection = offerCollection;
}
public Propertyowner getPropertyownerid() {
return propertyownerid;
}
public void setPropertyownerid(Propertyowner propertyownerid) {
this.propertyownerid = propertyownerid;
}
public Realestateagent getRealestateagentid() {
return realestateagentid;
}
public void setRealestateagentid(Realestateagent realestateagentid) {
this.realestateagentid = realestateagentid;
}
public String dateToString()
{
DateFormat df = new SimpleDateFormat("dd/MM/yy");
return df.format(entereddate);
}
public String timeToString()
{
DateFormat df = new SimpleDateFormat("HH:mm:ss");
return df.format(enteredtime);
}
#Override
public int hashCode() {
int hash = 0;
hash += (propertyid != null ? propertyid.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Property)) {
return false;
}
Property other = (Property) object;
if ((this.propertyid == null && other.propertyid != null) || (this.propertyid != null && !this.propertyid.equals(other.propertyid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.sushan.model.Property[ propertyid=" + propertyid + " ]";
}
}
EJB PropertyDAO:
#Stateless
public class PropertyDAO implements PropertyDAOLocal {
#PersistenceContext(unitName="RealEstateWebsite-ejbPU")
private EntityManager em;
#Override
public void AddProperty(Property property) {
em.persist(property);
}
#Override
public void EditProperty(Property property) {
em.merge(property);
}
#Override
public void DeleteProperty(int propertyId) {
em.remove(GetProperty(propertyId));
}
#Override
public List<Property> GetAllProperty() {
return em.createNamedQuery("Property.findAll").getResultList();
}
#Override
public Property GetProperty(int propertyId) {
return em.find(Property.class, propertyId);
}
#Override
public void EditPropertyAddress(Paddress propertyAddress) {
em.merge(propertyAddress);
}
}
Offer entity:
#Entity
#Table(name = "OFFER")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Offer.findAll", query = "SELECT o FROM Offer o")})
public class Offer implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "OFFERID")
private Integer offerid;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 100)
#Column(name = "OFFERSTATUS")
private String offerstatus;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 100)
#Column(name = "ORIGINALOFFER")
private String originaloffer;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 100)
#Column(name = "OFFERINGBP")
private String offeringbp;
#Basic(optional = false)
#NotNull
#Column(name = "OFFEREDDATE")
#Temporal(TemporalType.DATE)
private Date offereddate;
#Basic(optional = false)
#NotNull
#Column(name = "OFFEREDTIME")
#Temporal(TemporalType.TIME)
private Date offeredtime;
#JoinColumn(name = "BUYERID", referencedColumnName = "BUYERID")
#ManyToOne(optional = false)
private Buyer buyerid;
#JoinColumn(name = "PROPERTYID", referencedColumnName = "PROPERTYID")
#ManyToOne(optional = false)
private Property propertyid;
public Offer() {
}
public Offer(Integer offerid) {
this.offerid = offerid;
}
public Offer(String offerstatus, String originaloffer, String offeringbp, Date offereddate, Date offeredtime, Buyer buyerid, Property propertyid) {
this.offerstatus = offerstatus;
this.originaloffer = originaloffer;
this.offeringbp = offeringbp;
this.offereddate = offereddate;
this.offeredtime = offeredtime;
this.buyerid = buyerid;
this.propertyid = propertyid;
}
public Integer getOfferid() {
return offerid;
}
public void setOfferid(Integer offerid) {
this.offerid = offerid;
}
public String getOfferstatus() {
return offerstatus;
}
public void setOfferstatus(String offerstatus) {
this.offerstatus = offerstatus;
}
public String getOriginaloffer() {
return originaloffer;
}
public void setOriginaloffer(String originaloffer) {
this.originaloffer = originaloffer;
}
public String getOfferingbp() {
return offeringbp;
}
public void setOfferingbp(String offeringbp) {
this.offeringbp = offeringbp;
}
public Date getOffereddate() {
return offereddate;
}
public void setOffereddate(Date offereddate) {
this.offereddate = offereddate;
}
public Date getOfferedtime() {
return offeredtime;
}
public void setOfferedtime(Date offeredtime) {
this.offeredtime = offeredtime;
}
public Buyer getBuyerid() {
return buyerid;
}
public void setBuyerid(Buyer buyerid) {
this.buyerid = buyerid;
}
public Property getPropertyid() {
return propertyid;
}
public void setPropertyid(Property propertyid) {
this.propertyid = propertyid;
}
#Override
public int hashCode() {
int hash = 0;
hash += (offerid != null ? offerid.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Offer)) {
return false;
}
Offer other = (Offer) object;
if ((this.offerid == null && other.offerid != null) || (this.offerid != null && !this.offerid.equals(other.offerid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.sushan.model.Offer[ offerid=" + offerid + " ]";
}
EJB OfferDAO:
#Stateless
public class OfferDAO implements OfferDAOLocal {
#PersistenceContext(unitName="RealEstateWebsite-ejbPU")
EntityManager em;
#Override
public void EditOffer(Offer offer) {
em.merge(offer);
}
#Override
public List<Offer> GetAllOffer(int propertyId) {
return em.createNamedQuery("Offer.findByPropertyID").setParameter("propertyID", propertyId).getResultList();
}
#Override
public List<Offer> GetAllOffer() {
return em.createNamedQuery("Offer.findAll").getResultList();
}
#Override
public void Add(Offer offer) {
em.persist(offer);
}
}
Servlet that connects the JSP with the EJB:
String action = request.getParameter("action");
String currencyType = request.getParameter("ddlCurrencyType");
String amount = request.getParameter("offerAmount");
String propertyIdStr = request.getParameter("hdnbt");
if ("Offer".equalsIgnoreCase(action))
{
if ("".equals(action) & !"".equals(currencyType) & !"".equals(amount) & !"".equals(propertyIdStr))
{
DateFormat df = new SimpleDateFormat("dd/MM/yy");
DateFormat df1 = new SimpleDateFormat("HH:mm:ss");
Date currentDate = new Date();
Date currentTime = new Date();
int propertyId = Integer.parseInt(propertyIdStr);
try {
currentDate = df.parse(df.format(currentDate));
currentTime = df1.parse(df1.format(currentTime));
} catch (ParseException e) {
}
Buyer buyer = buyerDAO.GetBuyer(1);
Property property = propertyDAO.GetProperty(propertyId);
Offer offer = new Offer("Pending", amount, amount, currentDate, currentTime, buyer, property);
offerDAO.Add(offer);
}
else
{
}
}
request.setAttribute("allProperty", propertyDAO.GetAllProperty());
request.getRequestDispatcher("AdministerProperty.jsp").forward(request, response);
Am I missing something here? I have followed a tutorial which didn't have a foreign key guidance but tried to use my own logic to go around it but it didn't work. I cannot find a reliable source that uses the method similar to me. Most of the resources I find are for Hibernate but I am using EJB.
It seems that the method which retrieves the Property and the method that persists the Offer are run in a separate transactions (DAOs being the Stateless session beans).
That would mean that the Offer is populated and persisted with a detached Property, so the persistence provider is not aware of it.
Not sure why an exception is not raised but you would have to merge the Property first or do the query in the same transaction as you persist the Offer:
#Override
public void Add(Offer offer, int peropertyId) {
Property property = em.find(Property.class, propertyId);
offer.setPeropertyId(property);
em.persist(offer);
}
or
#Override
public void Add(Offer offer, Property peroperty) {
Property managedProperty = em.merge(property);
offer.setPeropertyId(managedProperty);
em.persist(offer);
}
I fixed it. If you look at the code for servlet, it was the problem with my if condition that checks the action parameter. It was meant to be if action is not empty but it checks if action is empty. I found this issue by creating an integer that increments itself when it reaches certain stages within the code.
I think you were right on the fact that I had to do the getting property id and buyer id on the same transaction. Otherwise that would have been the next issue for me. Thank you.

Columns are not populating in tableview on javafx

I have been trying to make the columns show a string of paciente and empleado but still they show empty, the other columns are fine, they show what they supposed to show, but these 2 (paciente and empleado) are still empty. I thought it was because of their properties, that they have different names, i tried that and still they came up empty, can i have some tips on how to do it the right way?
columnaCitasFecha.setCellValueFactory(new PropertyValueFactory<Cita, Date>("fecha"));
columnaCitasHora.setCellValueFactory(new PropertyValueFactory<Cita, Time>("hora"));
columnaCitasPaciente.setCellValueFactory(new PropertyValueFactory<Paciente, String>("nombrePaciente"));
columnaCitasDentista.setCellValueFactory(new PropertyValueFactory<Empleado, String>("nombreEmpleado"));
columnaCitasTratamiento.setCellValueFactory(new PropertyValueFactory<Cita, Set<Tratamiento>>("listaTratamientos"));
#Entity
#Table(name = "CITA")
public class Cita implements Serializable{
private long id;
private Date fecha;
private Time hora;
private Paciente paciente;
private Empleado empleado;
private Set<Tratamiento> listaTratamientos;
public Cita() {
fecha = null;
hora = null;
paciente = null;
empleado = null;
listaTratamientos = null;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "CITA_ID", nullable = false)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
#Column(name = "FECHA", nullable = false)
public Date getFecha() {
return fecha;
}
public void setFecha(Date fecha) {
this.fecha = fecha;
}
#Column(name = "HORA", nullable = false)
public Time getHora() {
return hora;
}
public void setHora(Time hora) {
this.hora = hora;
}
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "PACIENTE_ID")
public Paciente getPaciente() {
return paciente;
}
public void setPaciente(Paciente paciente) {
this.paciente = paciente;
}
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "EMPLEADO_ID")
public Empleado getEmpleado() {
return empleado;
}
public void setEmpleado(Empleado empleado) {
this.empleado = empleado;
}
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinTable(name = "CITA_TRATAMIENTO", joinColumns = {#JoinColumn(name = "CITA_ID", referencedColumnName = "CITA_ID")}, inverseJoinColumns = {#JoinColumn(name = "TRATAMIENTO_ID", referencedColumnName = "T_ID", unique = true)})
public Set<Tratamiento> getListaTratamientos() {
return listaTratamientos;
}
public void setListaTratamientos(Set<Tratamiento> listaTratamientos) {
this.listaTratamientos = listaTratamientos;
}
}
The 2 columns that are not populating are Persona and Paciente, here are the classes:
#Entity
#Table(name = "PERSONA")
#Inheritance(strategy = InheritanceType.JOINED)
public class Persona implements Serializable{
private long id;
private String nombre;
private String apellido;
private Sexo sexo;
private Date fechaNacimiento;
private String estadoCivil;
private String ocupacion;
private String nacionalidad;
private String telefono;
private String celular;
private String direccion;
private String correoElectronico;
private Date fechaRegistrado;
private Date fechaActualizado;
public Persona(){
nombre = "";
apellido = "";
sexo = null;
fechaNacimiento = null;
estadoCivil = "";
ocupacion = "";
nacionalidad = "";
telefono = "";
celular = "";
direccion = "";
correoElectronico = "";
fechaRegistrado = null;
fechaActualizado = null;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "ID", nullable = false)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
#Column(name = "NOMBRE", nullable = false)
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
#Column(name = "APELLIDO", nullable = false)
public String getApellido() {
return apellido;
}
public void setApellido(String apellido) {
this.apellido = apellido;
}
#Enumerated(EnumType.STRING)
#Column(name = "SEXO", nullable = false)
public Sexo getSexo() {
return sexo;
}
public void setSexo(Sexo sexo) {
this.sexo = sexo;
}
#Column(name = "FECHA_NACIMIENTO", nullable = false)
public Date getFechaNacimiento() {
return fechaNacimiento;
}
public void setFechaNacimiento(Date fechaNacimiento) {
this.fechaNacimiento = fechaNacimiento;
}
#Column(name = "ESTADO_CIVIL")
public String getEstadoCivil() {
return estadoCivil;
}
public void setEstadoCivil(String estadoCivil) {
this.estadoCivil = estadoCivil;
}
#Column(name = "OCUPACION")
public String getOcupacion() {
return ocupacion;
}
public void setOcupacion(String ocupacion) {
this.ocupacion = ocupacion;
}
#Column(name = "NACIONALIDAD")
public String getNacionalidad() {
return nacionalidad;
}
public void setNacionalidad(String nacionalidad) {
this.nacionalidad = nacionalidad;
}
#Column(name = "TELEFONO")
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
#Column(name = "CELULAR")
public String getCelular() {
return celular;
}
public void setCelular(String celular) {
this.celular = celular;
}
#Column(name = "DIRECCION")
public String getDireccion() {
return direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
#Column(name = "CORREO_ELECTRONICO")
public String getCorreoElectronico() {
return correoElectronico;
}
public void setCorreoElectronico(String correoElectronico) {
this.correoElectronico = correoElectronico;
}
#Column(name = "FECHA_REGISTRADO", nullable = false)
public Date getFechaRegistrado() {
return fechaRegistrado;
}
public void setFechaRegistrado(Date fechaRegistrado) {
this.fechaRegistrado = fechaRegistrado;
}
#Column(name = "FECHA_ACTUALIZADO", nullable = false)
public Date getFechaActualizado() {
return fechaActualizado;
}
public void setFechaActualizado(Date fechaActualizado) {
this.fechaActualizado = fechaActualizado;
}
}
#Entity
#Table(name = "PACIENTE")
#PrimaryKeyJoinColumn(name = "PACIENTE_ID")
public class Paciente extends Persona implements Serializable {
private String nombrePaciente;
public Paciente() {
super();
}
#Transient
public String getNombrePaciente() {
return this.getNombre() + " " + this.getApellido();
}
public void setNombrePaciente(String nombrePaciente) {
this.nombrePaciente = nombrePaciente;
}
}
#Entity
#Table(name = "EMPLEADO")
#PrimaryKeyJoinColumn(name = "EMPLEADO_ID")
public class Empleado extends Persona implements Serializable {
private TipoEmpleado tipoEmpleado;
private String nombreEmpleado;
public Empleado(){
super();
tipoEmpleado = null;
}
#Column(name = "TIPO_EMPLEADO", nullable = false)
#Enumerated(EnumType.STRING)
public TipoEmpleado getTipoEmpleado() {
return tipoEmpleado;
}
public void setTipoEmpleado(TipoEmpleado tipoEmpleado) {
this.tipoEmpleado = tipoEmpleado;
}
#Transient
public String getNombreEmpleado() {
return this.getNombre() + " " + this.getApellido();
}
public void setNombreEmpleado(String nombreEmpleado) {
this.nombreEmpleado = nombreEmpleado;
}
}
You need:
TableColumn<Cita, String> columnaCitasPaciente ;
// ...
columnaCitasPaciente.setCellValueFactory(cellData ->
new SimpleStringProperty(cellData.getValue().getPaciente().getNombrePaciente()));
columnaCitasDentista.setCellValueFactory(cellData ->
new SimpleStringProperty(cellData.getValue().getEmpleado().getNombreEmpleado());

How to persist a Many to Many relationship using JPA

I very confused on how to save data in the database. I'll take the data from a table and then save.
A figure of my relationship is below
How i can save a list of Layoutsos into Ordemservico?
And here is my my class.
public class Ordemservico implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "idordemservico")
private Integer idordemservico;
#Column(name = "identificadoros")
private Integer identificadoros;
#Column(name = "mes")
private Integer mes;
#Column(name = "ano")
private Integer ano;
#Column(name = "assunto")
private String assunto;
#Basic(optional = false)
#Column(name = "publicitario")
private String publicitario;
#Basic(optional = false)
#Column(name = "layoutos")
private String layoutos;
#Basic(optional = false)
#Column(name = "dataincio")
#Temporal(TemporalType.DATE)
private Date dataincio;
#Column(name = "datafim")
#Temporal(TemporalType.DATE)
private Date datafim;
#Column(name = "dataevento")
#Temporal(TemporalType.DATE)
private Date dataevento;
#Column(name = "producao")
private String producao;
#Lob
#Column(name = "discricao")
private String discricao;
#Column(name = "responsavelos")
private String responsavelos;
#Column(name = "materiajornal")
private String materiajornal;
#ManyToMany(mappedBy = "ordemservicoList")
private List<Ordemproducao> ordemproducaoList;
#ManyToMany(mappedBy = "ordemservicoList")
private List<Layoutsos> layoutsosList;
#JoinTable(name = "ordemservico_has_usuario", joinColumns = {
#JoinColumn(name = "ordemservico_idordemservico", referencedColumnName = ` ` "idordemservico")}, inverseJoinColumns = {
#JoinColumn(name = "usuario_idusuario", referencedColumnName = ` ` ` ` ` ` ` ` "idusuario")})
#ManyToMany
private List<Usuario> usuarioList;
#JoinColumn(name = "secretaria_idsecretaria", referencedColumnName = ` ` ` ` ` ` "idsecretaria")
#ManyToOne(optional = false)
private Secretaria secretariaIdsecretaria;
#OneToMany(cascade = CascadeType.ALL, mappedBy = ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` `"ordemservicoIdordemservico")
private List<Materiajornal> materiajornalList;
public Ordemservico() {
}
public Ordemservico(Integer idordemservico) {
this.idordemservico = idordemservico;
}
public Ordemservico(Integer idordemservico, String publicitario, String ` ` layoutos, Date dataincio) {
this.idordemservico = idordemservico;
this.publicitario = publicitario;
this.layoutos = layoutos;
this.dataincio = dataincio;
}
public Integer getIdordemservico() {
return idordemservico;
}
public void setIdordemservico(Integer idordemservico) {
this.idordemservico = idordemservico;
}
public Integer getIdentificadoros() {
return identificadoros;
}
public void setIdentificadoros(Integer identificadoros) {
this.identificadoros = identificadoros;
}
public Integer getMes() {
return mes;
}
public void setMes(Integer mes) {
this.mes = mes;
}
public Integer getAno() {
return ano;
}
public void setAno(Integer ano) {
this.ano = ano;
}
public String getAssunto() {
return assunto;
}
public void setAssunto(String assunto) {
this.assunto = assunto;
}
public String getPublicitario() {
return publicitario;
}
public void setPublicitario(String publicitario) {
this.publicitario = publicitario;
}
public String getLayoutos() {
return layoutos;
}
public void setLayoutos(String layoutos) {
this.layoutos = layoutos;
}
public Date getDataincio() {
return dataincio;
}
public void setDataincio(Date dataincio) {
this.dataincio = dataincio;
}
public Date getDatafim() {
return datafim;
}
public void setDatafim(Date datafim) {
this.datafim = datafim;
}
public Date getDataevento() {
return dataevento;
}
public void setDataevento(Date dataevento) {
this.dataevento = dataevento;
}
public String getProducao() {
return producao;
}
public void setProducao(String producao) {
this.producao = producao;
}
public String getDiscricao() {
return discricao;
}
public void setDiscricao(String discricao) {
this.discricao = discricao;
}
public String getResponsavelos() {
return responsavelos;
}
public void setResponsavelos(String responsavelos) {
this.responsavelos = responsavelos;
}
public String getMateriajornal() {
return materiajornal;
}
public void setMateriajornal(String materiajornal) {
this.materiajornal = materiajornal;
}
#XmlTransient
public List<Ordemproducao> getOrdemproducaoList() {
return ordemproducaoList;
}
public void setOrdemproducaoList(List<Ordemproducao> ordemproducaoList) {
this.ordemproducaoList = ordemproducaoList;
}
#XmlTransient
public List<Layoutsos> getLayoutsosList() {
return layoutsosList;
}
public void setLayoutsosList(List<Layoutsos> layoutsosList) {
this.layoutsosList = layoutsosList;
}
#XmlTransient
public List<Usuario> getUsuarioList() {
return usuarioList;
}
public void setUsuarioList(List<Usuario> usuarioList) {
this.usuarioList = usuarioList;
}
public Secretaria getSecretariaIdsecretaria() {
return secretariaIdsecretaria;
}
public void setSecretariaIdsecretaria(Secretaria secretariaIdsecretaria) {
this.secretariaIdsecretaria = secretariaIdsecretaria;
}
#XmlTransient
public List<Materiajornal> getMateriajornalList() {
return materiajornalList;
}
public void setMateriajornalList(List<Materiajornal> materiajornalList) {
this.materiajornalList = materiajornalList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idordemservico != null ? idordemservico.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
if (!(object instanceof Ordemservico)) {
return false;
}
Ordemservico other = (Ordemservico) object;
if ((this.idordemservico == null && other.idordemservico != null) || ` ` ` ` (this.idordemservico != null && ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` `enter code here`!this.idordemservico.equals(other.idordemservico))) {
return false;
}
return true;
}
#Override
public String toString() {
return assunto ;
}
}
Code of the other entity
But how do I grab the list of items that I select from Jtable and save. That table has all the Layouts, and now I want to save some layouts into the ordemserviço
public class Layoutsos implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "idlayoutsos")
private Integer idlayoutsos;
#Column(name = "nome")
private String nome;
#Column(name = "medidas")
private String medidas;
#JoinTable(name = "ordemservico_has_layoutsos", joinColumns = {
#JoinColumn(name = "layoutsos_idlayoutsos", referencedColumnName = "idlayoutsos")}, inverseJoinColumns = {
#JoinColumn(name = "ordemservico_idordemservico", referencedColumnName = "idordemservico")})
#ManyToMany
private List<Ordemservico> ordemservicoList;
public Layoutsos() {
}
public Layoutsos(Integer idlayoutsos) {
this.idlayoutsos = idlayoutsos;
}
public Integer getIdlayoutsos() {
return idlayoutsos;
}
public void setIdlayoutsos(Integer idlayoutsos) {
this.idlayoutsos = idlayoutsos;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getMedidas() {
return medidas;
}
public void setMedidas(String medidas) {
this.medidas = medidas;
}
#XmlTransient
public List<Ordemservico> getOrdemservicoList() {
return ordemservicoList;
}
public void setOrdemservicoList(List<Ordemservico> ordemservicoList) {
this.ordemservicoList = ordemservicoList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idlayoutsos != null ? idlayoutsos.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Layoutsos)) {
return false;
}
Layoutsos other = (Layoutsos) object;
if ((this.idlayoutsos == null && other.idlayoutsos != null) || (this.idlayoutsos != null && !this.idlayoutsos.equals(other.idlayoutsos))) {
return false;
}
return true;
}
#Override
public String toString() {
return "br.app.com.classes.Layoutsos[ idlayoutsos=" + idlayoutsos + " ]";
}
}
Assuming you have an object variable layoutsos of type Layoutsos that has been persisted to the DB or retrieved from the DB. Here's how your code should look like when persisting the Ordemservico entity.
Ordemservico o = new Ordemservico();
o.getOrdemproducaoList().add(layoutsos);
em.persist(o);
If this is a bi-directional relationship, you should set both side of the relationship before persisting.
Layoutsos layoutsos = new Layoutsos();
Ordemservico o = new Ordemservico();
o.getOrdemproducaoList().add(layoutsos);
layoutsos.getOrdermserviceoList().add(o);
em.persist(layoutsos);
em.persist(o);

How to prevent endless loop in hibernate

I have a rest server and client which uses this API. I have a list of hotels and it had passed well until I added bidirectional dependencies to other entities.After that I start receive an endless array of entities which just repeat the same row in database.
It is my first project with hibernate so may be I made trivial mistakes of novice.
Hotel:
#Entity
#Table(name = "hotels", schema = "", catalog = "mydb")
public class HotelsEntity implements HospitalityEntity{
private int idHotel;
private String name;
private String region;
private String description;
// private byte[] photo;
private HotelPropertyEntity property;
private List<RoomEntity> rooms;
#OneToOne(mappedBy = "hotel")
public HotelPropertyEntity getProperty() {
return property;
}
public void setProperty(HotelPropertyEntity property) {
this.property = property;
}
#OneToMany(mappedBy = "hotel")
public List<RoomEntity> getRooms() {
return rooms;
}
public void setRooms(List<RoomEntity> rooms) {
this.rooms = rooms;
}
#Id
#Column(name = "id_hotel", unique = true)
#GeneratedValue(strategy=GenerationType.AUTO)
public int getIdHotel() {
return idHotel;
}
public void setIdHotel(int idHotel) {
this.idHotel = idHotel;
}
#Basic
#Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Basic
#Column(name = "region")
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
#Basic
#Column(name = "description")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
HotelProperty
#Entity
#Table(name = "hotel_property", schema = "", catalog = "mydb")
public class HotelPropertyEntity {
private int idHotelProperty;
private byte hasPool;
private byte hasTennisCourt;
private byte hasWaterslides;
private HotelsEntity hotel;
#Id
#Column(name = "id_hotel_property", unique = true)
#GeneratedValue(strategy=GenerationType.AUTO)
public int getIdHotelProperty() {
return idHotelProperty;
}
public void setIdHotelProperty(int idHotelProperty) {
this.idHotelProperty = idHotelProperty;
}
#Basic
#Column(name = "has_pool", columnDefinition = "BIT", length = 1)
public byte getHasPool() {
return hasPool;
}
public void setHasPool(byte hasPool) {
this.hasPool = hasPool;
}
#Basic
#Column(name = "has_tennis_court", columnDefinition = "BIT", length = 1)
public byte getHasTennisCourt() {
return hasTennisCourt;
}
public void setHasTennisCourt(byte hasTennisCourt) {
this.hasTennisCourt = hasTennisCourt;
}
#Basic
#Column(name = "has_waterslides", columnDefinition = "BIT", length = 1)
public byte getHasWaterslides() {
return hasWaterslides;
}
public void setHasWaterslides(byte hasWaterslides) {
this.hasWaterslides = hasWaterslides;
}
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "id_hotel_property")
public HotelsEntity getHotel() {
return hotel;
}
public void setHotel(HotelsEntity hotel) {
this.hotel = hotel;
}
Room:
#Entity
#Table(name = "room", schema = "", catalog = "mydb")
public class RoomEntity {
private int idRoom;
private String roomType;
private int peopleCapacity;
private Boolean booked;
private Boolean locked;
private HotelsEntity hotel;
private InventoriesEntity inventory;
private RoomPropertyEntity roomProperty;
#OneToOne(mappedBy = "room")
public RoomPropertyEntity getRoom() {
return roomProperty;
}
public void setRoom(RoomPropertyEntity roomProperty) {
this.roomProperty = roomProperty;
}
#OneToOne
#JoinColumn(name = "id_room")
public InventoriesEntity getInventory() {
return inventory;
}
public void setInventory(InventoriesEntity inventory) {
this.inventory = inventory;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "id_hotel")
public HotelsEntity getHotel() {
return hotel;
}
public void setHotel(HotelsEntity hotel) {
this.hotel = hotel;
}
#Id
#Column(name = "id_room")
public int getIdRoom() {
return idRoom;
}
public void setIdRoom(int idRoom) {
this.idRoom = idRoom;
}
#Basic
#Column(name = "room_type")
public String getRoomType() {
return roomType;
}
public void setRoomType(String roomType) {
this.roomType = roomType;
}
#Basic
#Column(name = "people_capacity")
public int getPeopleCapacity() {
return peopleCapacity;
}
public void setPeopleCapacity(int peopleCapacity) {
this.peopleCapacity = peopleCapacity;
}
#Basic
#Column(name = "booked", columnDefinition = "BIT", length = 1)
public Boolean getBooked() {
return booked;
}
public void setBooked(Boolean booked) {
this.booked = booked;
}
#Basic
#Column(name = "locked", columnDefinition = "BIT", length = 1)
public Boolean getLocked() {
return locked;
}
public void setLocked(Boolean locked) {
this.locked = locked;
}
Could you please advise what is a way or ways to tell hibernate to stop this cycle?
p.s
This code contains another one issue. I f I remove one to one dependency and remain only one to many I receive failed to lazily initialize a collection of role: com.example.model.HotelsEntity.rooms, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->com.example.model.HotelsEntity["rooms"])
You need to mark entity as not serializable for JSON. Please use #JsonIgnore or #JsonIgnoreProperties("field") on one of the sides of the relations (the annotation is class-level).

Categories

Resources