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.
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.
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());
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);
Here i have two JPA Classes: TimeSheet and TimeSheetDetails
In this case i have a trouble with updation of timesheet, while updation the timesheet (master table) updated smoothly, but timesheet details (child table) generate new rows instead of updation and the link table also updated with the new values.....
Here what is the re
1)TimeSheet.java
#Entity
#Table(name = AMAM_Constants.tb_name.TIMESHEET, schema = AMAM_Constants.db_name)
public class TimeSheet implements Serializable {
private long ts_Id;
private String ts_Candidate;
private Date ts_Sdate;
private Date ts_Edate;
private String active;
private String ts_Type;
private String ts_Status;
private List<TimeSheetDetails> timesheetDetails = new ArrayList<TimeSheetDetails>();
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinTable(name = AMAM_Constants.tb_name.TIMESHEET_LINK_DETAILS, joinColumns = {
#JoinColumn(name = "TS_ID")}, inverseJoinColumns = {
#JoinColumn(name = "TSD_ID")
})
public List<TimeSheetDetails> getTimesheetDetails() {
return timesheetDetails;
}
public void setTimesheetDetails(List<TimeSheetDetails> timesheetDetails) {
this.timesheetDetails = timesheetDetails;
}
#Column(name = "ACTIVE", length = 1)
public String getActive() {
return active;
}
public void setActive(String active) {
this.active = active;
}
#Column(name = "TS_CANDIDATE", length = 25)
public String getTs_Candidate() {
return ts_Candidate;
}
public void setTs_Candidate(String ts_Candidate) {
this.ts_Candidate = ts_Candidate;
}
#Column(name = "TS_EDATE")
public Date getTs_Edate() {
return ts_Edate;
}
public void setTs_Edate(Date ts_Edate) {
this.ts_Edate = ts_Edate;
}
#Id
#GeneratedValue
#Column(name = "TS_ID")
public long getTs_Id() {
return ts_Id;
}
public void setTs_Id(long ts_Id) {
this.ts_Id = ts_Id;
}
#Column(name = "TS_SDATE")
public Date getTs_Sdate() {
return ts_Sdate;
}
public void setTs_Sdate(Date ts_Sdate) {
this.ts_Sdate = ts_Sdate;
}
#Column(name = "TS_STATUS", length = 25)
public String getTs_Status() {
return ts_Status;
}
public void setTs_Status(String ts_Status) {
this.ts_Status = ts_Status;
}
#Column(name = "TS_TYPE", length = 10)
public String getTs_Type() {
return ts_Type;
}
public void setTs_Type(String ts_Type) {
this.ts_Type = ts_Type;
}
}
#Entity
#Table(name = AMAM_Constants.tb_name.TIMESHEET_DETAILS, schema = AMAM_Constants.db_name)
public class TimeSheetDetails implements Serializable {
private long tsd_Id;
private String tsd_Po;
private Date tsd_Date;
private String tsd_DayName;
private int tsd_Hours;
private String tsd_HourType;
private String tsd_DayType;
#Column(name = "TSD_DATE")
public Date getTsd_Date() {
return tsd_Date;
}
public void setTsd_Date(Date tsd_Date) {
this.tsd_Date = tsd_Date;
}
#Column(name = "TSD_DAYNAME", length = 25)
public String getTsd_DayName() {
return tsd_DayName;
}
public void setTsd_DayName(String tsd_DayName) {
this.tsd_DayName = tsd_DayName;
}
#Column(name = "TSD_DAYTYPE", length = 25)
public String getTsd_DayType() {
return tsd_DayType;
}
public void setTsd_DayType(String tsd_DayType) {
this.tsd_DayType = tsd_DayType;
}
#Column(name = "TSD_HOURTYPE", length = 25)
public String getTsd_HourType() {
return tsd_HourType;
}
public void setTsd_HourType(String tsd_HourType) {
this.tsd_HourType = tsd_HourType;
}
#Column(name = "TSD_HOURS")
public int getTsd_Hours() {
return tsd_Hours;
}
public void setTsd_Hours(int tsd_Hours) {
this.tsd_Hours = tsd_Hours;
}
#Id
#GeneratedValue
#Column(name = "TSD_ID")
public long getTsd_Id() {
return tsd_Id;
}
public void setTsd_Id(long tsd_Id) {
this.tsd_Id = tsd_Id;
}
#Column(name = "TSD_PO", length = 25)
public String getTsd_Po() {
return tsd_Po;
}
public void setTsd_Po(String tsd_Po) {
this.tsd_Po = tsd_Po;
}
}
public class TimeSheetDao extends HibDao {
public void insertTimeSheet(TimeSheet objTimeSheet) throws Exception {
try {
begin();
getSession().save(objTimeSheet);
commit();
} catch (Exception ex) {
rollback();
throw new Exception(ex.getMessage());
} finally {
flush();
close();
}
}
public void updateTimeSheet(TimeSheet objTimeSheet) throws Exception {
try {
begin();
TimeSheet obj =(TimeSheet)getSession().get(TimeSheet.class,objTimeSheet.getTs_Id());
obj.setActive("Y");
obj.setTimesheetDetails(objTimeSheet.getTimesheetDetails());
obj.setTs_Candidate(objTimeSheet.getTs_Candidate());
obj.setTs_Edate(objTimeSheet.getTs_Edate());
obj.setTs_Sdate(objTimeSheet.getTs_Sdate());
obj.setTs_Status(objTimeSheet.getTs_Status());
obj.setTs_Type(objTimeSheet.getTs_Type());
getSession().update(obj);
commit();
} catch (Exception ex) {
rollback();
throw new Exception(ex.getMessage());
} finally {
flush();
close();
}
}
}
The problem is in this line:
obj.setTimesheetDetails(objTimeSheet.getTimesheetDetails());
You should do the same to update the child to what you are doing to update the parent. I.e:
obj.getTimesheetDetails().setTsd_Date(objTimeSheet.getTimesheetDetails().getTsd_Date);
...