Persisting a table with foreign keys using EJB and JPA - java

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.

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.

For each save (update) hibernate envers creating revisions either changed in table or not

In my client server application, I am using JavaFx as client and Java hibernate as server to db connection.
Problem
I have one save button and for each click on button, envers creates one revision, whether there is no change in table values.
Basically it is not checking old data to new data, just creating revisions.
Here is my bean code
#Entity
#Audited
#Table(name = "DOMAIN")
public class Domain implements java.io.Serializable {
private Long domainId;
private String domainName;
private String dataType;
private Long valueSize;
private Long valuePrecision;
private Long valueScale;
private String valueRangeLow;
private String valueRangeHigh;
private String description;
private String comments;
private Date effectiveStartDate;
private Date effectiveEndDate;
private String status;
public Domain() {
}
public Domain(Long domainId, String domainName, String dataType,
Date effectiveStartDate, Date effectiveEndDate, String status) {
this.domainId = domainId;
this.domainName = domainName;
this.dataType = dataType;
this.effectiveStartDate = effectiveStartDate;
this.effectiveEndDate = effectiveEndDate;
this.status = status;
}
public Domain(Long domainId, String domainName, String dataType,
Long valueSize, Long valuePrecision,
Long valueScale, String valueRangeLow, String valueRangeHigh,
String description, String comments, Date effectiveStartDate,
Date effectiveEndDate, String status) {
this.domainId = domainId;
this.domainName = domainName;
this.dataType = dataType;
this.valueSize = valueSize;
this.valuePrecision = valuePrecision;
this.valueScale = valueScale;
this.valueRangeLow = valueRangeLow;
this.valueRangeHigh = valueRangeHigh;
this.description = description;
this.comments = comments;
this.effectiveStartDate = effectiveStartDate;
this.effectiveEndDate = effectiveEndDate;
this.status = status;
}
#Id
#GeneratedValue(generator = "DOMAIN_SEQ")
#SequenceGenerator(name="DOMAIN_SEQ", sequenceName="DOMAIN_SEQ",allocationSize=1)
#Column(name = "DOMAIN_ID", unique = true, nullable = false, precision = 22, scale = 0)
public Long getDomainId() {
return this.domainId;
}
public void setDomainId(Long domainId) {
this.domainId = domainId;
}
#Column(name = "DOMAIN_NAME", nullable = false, length = 50)
public String getDomainName() {
return this.domainName;
}
public void setDomainName(String domainName) {
this.domainName = domainName;
}
#Column(name = "DATA_TYPE", nullable = false, length = 50)
public String getDataType() {
return this.dataType;
}
public void setDataType(String dataType) {
this.dataType = dataType;
}
#Column(name = "VALUE_SIZE", precision = 22, scale = 0)
public Long getValueSize() {
return this.valueSize;
}
public void setValueSize(Long valueSize) {
this.valueSize = valueSize;
}
#Column(name = "VALUE_PRECISION", precision = 22, scale = 0)
public Long getValuePrecision() {
return this.valuePrecision;
}
public void setValuePrecision(Long valuePrecision) {
this.valuePrecision = valuePrecision;
}
#Column(name = "VALUE_SCALE", precision = 22, scale = 0)
public Long getValueScale() {
return this.valueScale;
}
public void setValueScale(Long valueScale) {
this.valueScale = valueScale;
}
#Column(name = "VALUE_RANGE_LOW", length = 50)
public String getValueRangeLow() {
return this.valueRangeLow;
}
public void setValueRangeLow(String valueRangeLow) {
this.valueRangeLow = valueRangeLow;
}
#Column(name = "VALUE_RANGE_HIGH", length = 50)
public String getValueRangeHigh() {
return this.valueRangeHigh;
}
public void setValueRangeHigh(String valueRangeHigh) {
this.valueRangeHigh = valueRangeHigh;
}
#Column(name = "DESCRIPTION", length = 200)
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
#Column(name = "COMMENTS")
public String getComments() {
return this.comments;
}
public void setComments(String comments) {
this.comments = comments;
}
#Temporal(TemporalType.DATE)
#Column(name = "EFFECTIVE_START_DATE", nullable = false, length = 7)
public Date getEffectiveStartDate() {
return this.effectiveStartDate;
}
public void setEffectiveStartDate(Date effectiveStartDate) {
this.effectiveStartDate = effectiveStartDate;
}
#Temporal(TemporalType.DATE)
#Column(name = "EFFECTIVE_END_DATE", nullable = false, length = 7)
public Date getEffectiveEndDate() {
return this.effectiveEndDate;
}
public void setEffectiveEndDate(Date effectiveEndDate) {
this.effectiveEndDate = effectiveEndDate;
}
#Column(name = "STATUS", nullable = false, length = 50)
public String getStatus() {
return this.status;
}
public void setStatus(String status) {
this.status = status;
}
Problem is only with client server application.
With normal standalone program it is working fine.
Could anyone help me? I stuck at this point. Am i missing any jars or anything else?
If you need more clarification about question then please tell me.
SERVER SIDE CODE
public long saveDomainFromJson(String domainJsonData) throws Exception {
long domainId = 0;
try {
// here I am setting data to bean, getting from client side
Domain domain = getDomainFromJson(domainJsonData);
Session session = HibernateUtil.currentSession();
Transaction tx = session.beginTransaction();
domainId = session.saveOrUpdate(domain);
tx.commit();
HibernateUtil.closeSession();
} catch (Exception e) {
e.printStackTrace();
throw e;
}
return domainId;
}
Json Data
{
"DOMAIN_ID":36,
"DOMAIN_NAME":"Test_Type",
"DOMAIN_DATA_TYPE":"STRING",
"DOMAIN_EFF_START_DATE":"2016-11-08",
"DOMAIN_EFF_END_DATE":"2099-12-31",
"DOMAIN_STATUS":"Draft",
"DOMAIN_DESCRIPTION":"Object Type: Added for testing purpose"
}
Sorry I didn't see this soon, but the problem is your call to session#save. From the javadocs for Session here, you'll notice the following passage:
save() and persist() result in an SQL INSERT, delete() in an SQL DELETE and update() or merge() in an SQL UPDATE. Changes to persistent instances are detected at flush time and also result in an SQL UPDATE. saveOrUpdate() and replicate() result in either an INSERT or an UPDATE.
So you basically want to use session#saveOrUpdate so that you get both insert and update semantics based on the state of your entity.
Since session#save is generating a new INSERT operation, Envers will always create a new revision for that case regardless.

Appointment App - AngularJS availability selection

I developed an application using Java Spring (backend api), mysql (DB) and Anguljar JS (frontend) that is designed to let users schedule an appointment. The endtime of each appointment is five minutes after its starttime, between 8 o’clock and 2 p.m.
In my data base I have the following information:
• A table named “turno” which contains the parameters time and date of the appointments given.
• Another table contains all the available appointments.
I want to substract both arrays so as to see which appointments have not been given yet. The objective is not to allow users to fix an appointment that has already been made by someone else.
Does anyone have any idea how to do this?
Data examples:
Java Example:
#Entity
#Table(name = "turno")
public class Turno implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String solicitante;
private String telefono;
private TipoDocumento tipoDocumento;
private String numeroDocumento;
private String email;
private Horario horario;
private String numeroTurno;
private String fecha;
private Date formatfecha;
private Date controlFecha;
#Id
#GeneratedValue
#Column(name = "id")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name = "solicitante")
public String getSolicitante() {
return solicitante;
}
public void setSolicitante(String solicitante) {
this.solicitante = solicitante;
}
#Column(name = "telefono")
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
#Column(name = "numero_documento")
public String getNumeroDocumento() {
return numeroDocumento;
}
public void setNumeroDocumento(String numeroDocumento) {
this.numeroDocumento = numeroDocumento;
}
#Column(name = "email")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#ManyToOne(cascade = CascadeType.MERGE)
#JoinColumn(name = "horario", referencedColumnName = "id")
public Horario getHorario() {
return horario;
}
public void setHorario(Horario horario) {
this.horario = horario;
}
#Column(name = "numero_turno")
public String getNumeroTurno() {
return numeroTurno;
}
public void setNumeroTurno(String numeroTurno) {
this.numeroTurno = numeroTurno;
}
#Column(name = "fecha")
public String getFecha() {
return fecha;
}
public void setFecha(String fecha) {
this.fecha = fecha;
}
#Column(insertable = false, updatable = false, name = "fecha")
public Date getFormatFecha() {
return formatfecha;
}
public void setFormatFecha(Date formatfecha) {
this.formatfecha = formatfecha;
}
#ManyToOne(cascade = CascadeType.MERGE)
#JoinColumn(name = "tipoDocumento", referencedColumnName = "id")
public TipoDocumento getTipoDocumento() {
return tipoDocumento;
}
public void setTipoDocumento(TipoDocumento tipoDocumento) {
this.tipoDocumento = tipoDocumento;
}
#Column(name = "fecha_control")
public Date getControlFecha() {
return controlFecha;
}
public void setControlFecha(Date controlFecha) {
this.controlFecha = controlFecha;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((numeroTurno == null) ? 0 : numeroTurno.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Turno other = (Turno) obj;
if (numeroTurno == null) {
if (other.numeroTurno != null)
return false;
} else if (!numeroTurno.equals(other.numeroTurno))
return false;
return true;
}
}
Updated
Heres how I fixed it in case anyone is interested:
Method in the controller:
#RequestMapping(value = "/horario/{fecha}", method = RequestMethod.GET)
#ResponseBody
public Object queryHorariosLibres(#PathVariable("fecha") Date fecha) {
List<Long> horariosLibres = null;
List<Long> turnosTomados = turnoService.getTurnosTomados(fecha);
Calendar dia = new GregorianCalendar();
dia.setTime(fecha);
Horario horario = horarioRepository.findByDia(dia.get(Calendar.DAY_OF_WEEK));
horariosLibres = horario.getHorariosLibres(turnosTomados);
if (horariosLibres == null) {
return "hola";
}
else
return horariosLibres;
}
Local methods:
#Transient
public List<Long> getHorarios(){
List<Long> horarios = new ArrayList<Long>();
for(Long i = horarioInicio; i <= horarioFin; i+=300){
horarios.add(i);
}
return horarios;
}
#Transient
public List<Long> getHorariosLibres(List<Long> horariosTomados){
List<Long> horariosLibres = getHorarios();
horariosLibres.removeAll(horariosTomados);
return horariosLibres;
}

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);

Error " java.lang.IllegalStateException: During synchronization a new object was found through a relationship that was not marked cascade PERSIST"

this is my first post, so please bear with me if i do make any errors.
I get an error " java.lang.IllegalStateException: During synchronization a new object was found through a relationship that was not marked cascade PERSIST"
whenever i want to query(add,edit,delete) the database.
The tables related are sponsors and donations. There is a one to many relationship between them. Classes below:
Sponsors
#Entity
#Table(name = "SPONSORS")
#NamedQueries({
#NamedQuery(name = "Sponsors.findAll", query = "SELECT s FROM Sponsors s")})
public class Sponsors implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "SPONSORID")
private Short sponsorid;
#Basic(optional = false)
#Column(name = "NAME")
private String name;
#Basic(optional = false)
#Column(name = "SURNAME")
private String surname;
#Basic(optional = false)
#Column(name = "ADDRESS")
private String address;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "sponsorid")
private List<Donations> donationsList;
public Sponsors() {
}
public Sponsors(Short sponsorid) {
this.sponsorid = sponsorid;
}
public Sponsors(Short sponsorid, String name, String surname, String address) {
this.sponsorid = sponsorid;
this.name = name;
this.surname = surname;
this.address = address;
}
public Short getSponsorid() {
return sponsorid;
}
public void setSponsorid(Short sponsorid) {
this.sponsorid = sponsorid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public List<Donations> getDonationsList() {
return donationsList;
}
public void setDonationsList(List<Donations> donationsList) {
this.donationsList = donationsList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (sponsorid != null ? sponsorid.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 Sponsors)) {
return false;
}
Sponsors other = (Sponsors) object;
if ((this.sponsorid == null && other.sponsorid != null) || (this.sponsorid != null && !this.sponsorid.equals(other.sponsorid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "Pat.Sponsors[ sponsorid=" + sponsorid + " ]";
}
}
Donations:
#Entity
#Table(name = "DONATIONS")
#NamedQueries({
#NamedQuery(name = "Donations.findAll", query = "SELECT d FROM Donations d")})
public class Donations implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "DONATIONID")
private Short donationid;
#Basic(optional = false)
#Column(name = "DONATIONDATE")
#Temporal(TemporalType.DATE)
private Date donationdate;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
#Column(name = "DONATIONAMOUNT")
private Double donationamount;
#JoinColumn(name = "SPONSORID", referencedColumnName = "SPONSORID")
#ManyToOne(optional = false)
private Sponsors sponsorid;
public Donations() {
}
public Donations(Short donationid) {
this.donationid = donationid;
}
public Donations(Short donationid, Date donationdate) {
this.donationid = donationid;
this.donationdate = donationdate;
}
public Short getDonationid() {
return donationid;
}
public void setDonationid(Short donationid) {
this.donationid = donationid;
}
public Date getDonationdate() {
return donationdate;
}
public void setDonationdate(Date donationdate) {
this.donationdate = donationdate;
}
public Double getDonationamount() {
return donationamount;
}
public void setDonationamount(Double donationamount) {
this.donationamount = donationamount;
}
public Sponsors getSponsorid() {
return sponsorid;
}
public void setSponsorid(Sponsors sponsorid) {
this.sponsorid = sponsorid;
}
#Override
public int hashCode() {
int hash = 0;
hash += (donationid != null ? donationid.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 Donations)) {
return false;
}
Donations other = (Donations) object;
if ((this.donationid == null && other.donationid != null) || (this.donationid != null && !this.donationid.equals(other.donationid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "Pat.Donations[ donationid=" + donationid + " ]";
}
}
The field
#ManyToOne(optional = false)
private Sponsors sponsorid;
in the Donations entity is not configured for cascading. Try changing it to:
#ManuToOne(optional = false, cascade = CascadeType.ALL)
private Sponsors sponsorid;

Categories

Resources