CASCADETYPE in EclipseLink JPA - java

I have two classess. The first class is TNota.
#Entity
#Table(name = "t_nota")
public class TNota implements Serializable {
#Id
#SequenceGenerator(name="seq_t_nota", sequenceName="seq_t_nota", initialValue=37, allocationSize=1)
#GeneratedValue(generator="seq_t_nota")
#Basic(optional = false)
#Column(name = "id_nota", nullable = false)
private double idNota;
#Basic(optional = false)
#Column(name = "nota", nullable = false, length = 255)
private String nota;
#JoinColumn(name = "id_tipo_nota", referencedColumnName = "id", nullable = false)
#ManyToOne(optional = false)
private NTipoNota nTipoNota;
public TNota() {
}
public TNota(Long idNota) {
this.idNota = idNota;
}
public double getIdNota() {
return idNota;
}
public void setIdNota(double idNota) {
this.idNota = idNota;
}
public String getNota() {
return nota;
}
public void setNota(String nota) {
this.nota = nota;
}
public NTipoNota getNTipoNota() {
return nTipoNota;
}
public void setNTipoNota(NTipoNota nTipoNota) {
this.nTipoNota = nTipoNota;
}
}
and the other class is NtipoNota..
#Entity
#Table(name = "n_tipo_nota")
public class NTipoNota implements Serializable {
#Id
#Basic(optional = false)
#Column(name = "id", nullable = false)
private Integer id;
#Basic(optional = false)
#Column(name = "nombre", nullable = false, length = 255)
private String nombre;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "nTipoNota",fetch=FetchType.LAZY)
private List<TNota> tNotaList;
public NTipoNota() {
}
public NTipoNota(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public List<TNota> getTNotaList() {
return tNotaList;
}
public void setTNotaList(List<TNota> tNotaList) {
this.tNotaList = tNotaList;
}
}
I have all type of notes stored in database. I just want to persist a new TNota as follows, but I got an error because it persists a new NTipoNota with id= 5 which already exists in database. Using TopLink I never had this trouble:
TNota note = new TNota();
note.setNota("Hola mundo");
note.setNTipoNota(new NTipoNota(5));
manager.persist(note);
I fixed as follow:
TNota note = new TNota();
note.setNota("Hola mundo");
note.setNTipoNota(manager.find(NTipoNota.class, 5);
manager.persist(note);
I would like not to have to change all code due to this problem. Is there any form to make that do not persist the objects when we create a new instance of them?.
Thanks for all.

You new code is correct, and your previous code is not correct. You could also call merge to resolve the relationship.

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.

Hibernate OneToMany creating many records

I have this two object Input and IndisponibleSegment with a relation one to many respectively:
#Entity
#Table(name= "input")
public class Input {
private long _id;
private String _name;
private Set<IndisponibleSegment> _indisponibleSegments;
#Column(name = "name", unique = true, nullable = false, length = 25)
public String getName() {
return _name;
}
public void setName(String inName) {
this._name = inName;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public long getId() {
return _id;
}
public void setId(long inId) {
this._id = inId;
}
#OneToMany(fetch = FetchType.EAGER, mappedBy = "input", cascade = CascadeType.ALL, orphanRemoval = true)
public Set<IndisponibleSegment> getIndisponibleSegments() {
return _indisponibleSegments;
}
public void setIndisponibleSegments(Set<IndisponibleSegment> inIndisponibleSegments) {
this._indisponibleSegments = inIndisponibleSegments;
}
}
And:
#Entity
#Table(name = "indisponible_segment")
public class IndisponibleSegment {
private Lane _lane;
private int _id;
private Input _input;
#ManyToOne(fetch=FetchType.EAGER)
#Cascade(value={org.hibernate.annotations.CascadeType.ALL})
#JoinColumn(name="input_id")
public Input getInput() {
return _input;
}
public void setInput(Input inInput) {
this._input = inInput;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id")
public int getId() {
return _id;
}
public void setId(int inId) {
this._id = inId;
}
#Enumerated(EnumType.STRING)
#Column(name = "lane", nullable = false)
public Lane getLane() {
return _lane;
}
public void setLane(Lane inLane) {
this._lane = inLane;
}
}
My problem is that everytime run a code like:
DAO dao = new DAO();
Input input = dao.get(Input.class, new Long(1));
if(input==null) {
input = new Input();
input.setName("Input 1");
}
Set<IndisponibleSegment> islist = new HashSet<>();
IndisponibleSegment is = new IndisponibleSegment();
is.setInput(input);
is.setLane(Lane.LANE_FAST);
islist.add(is);
input.setIndisponibleSegments(islist);
dao.saveOrUpdate(input);
I get a new entry in the indisponible_segments table and the old is not removed, thus still there.
I have tried all combinations I can think of: Cascade, delete-orphans, unique constranits... all. What am I doing wrong? All I want is that if I set a new the indisponibleSegments the old ones are deleted.

Composite primary Key and Data truncation error

I'm using Hibernate and MySql and today I setted a composite primary key in one of my table, so below:
DefSelfLearning
And this entity is OneToMany with SelfLearning:
This is my java entity:
#Entity
#Table(name = "defselflearning", catalog = "ats")
public class DefSelfLearning implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#EmbeddedId
private DefSelfLearningKeys defSelfLearningKeys;
private Ecu ecu;
private String excelColumn;
#JsonIgnore
private Set<SelfLearning> selfLearnings = new HashSet<SelfLearning>(0);
public DefSelfLearning() {
}
public DefSelfLearning(DefSelfLearningKeys defSelfLearningKeys, Ecu ecu) {
this.defSelfLearningKeys = defSelfLearningKeys;
this.ecu = ecu;
}
public DefSelfLearning(Ecu ecu, DefSelfLearningKeys defSelfLearningKeys, String excelColumn, Set<SelfLearning> selfLearnings) {
this.ecu = ecu;
this.defSelfLearningKeys = defSelfLearningKeys;
this.excelColumn = excelColumn;
this.selfLearnings = selfLearnings;
}
#Id
public DefSelfLearningKeys getDefSelfLearningKeys() {
return this.defSelfLearningKeys;
}
public void setDefSelfLearningKeys(DefSelfLearningKeys defSelfLearningKeys) {
this.defSelfLearningKeys = defSelfLearningKeys;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "id_ecu", nullable = false)
public Ecu getEcu() {
return this.ecu;
}
public void setEcu(Ecu ecu) {
this.ecu = ecu;
}
#Column(name = "excelColumn", length = 2)
public String getExcelColumn() {
return this.excelColumn;
}
public void setExcelColumn(String excelColumn) {
this.excelColumn = excelColumn;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "defSelfLearning")
public Set<SelfLearning> getSelfLearnings() {
return this.selfLearnings;
}
public void setSelfLearnings(Set<SelfLearning> selfLearnings) {
this.selfLearnings = selfLearnings;
}
}
the class for the composite key:
#Embeddable
public class DefSelfLearningKeys implements Serializable {
private static final long serialVersionUID = 1L;
protected String parName;
protected String description;
protected String note;
public DefSelfLearningKeys() {}
public DefSelfLearningKeys(String parName, String description, String note) {
this.parName = parName;
this.description = description;
this.note = note;
}
#Column(name = "parName", nullable = false, length = 15)
public String getParName() {
return this.parName;
}
public void setParName(String parName) {
this.parName = parName;
}
#Column(name = "description", nullable = false, length = 100)
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
#Column(name = "note", nullable = false, length = 100)
public String getNote() {
return this.note;
}
public void setNote(String note) {
this.note = note;
}
}
and SelfLearning class:
#Entity
#Table(name = "selflearning", catalog = "ats")
public class SelfLearning implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int idSelfLearning;
private Acquisition acquisition;
private DefSelfLearning defSelfLearning;
private String value;
public SelfLearning() {
}
public SelfLearning(int idSelfLearning, Acquisition acquisition, DefSelfLearning defSelfLearning) {
this.idSelfLearning = idSelfLearning;
this.acquisition = acquisition;
this.defSelfLearning = defSelfLearning;
}
public SelfLearning(int idSelfLearning, Acquisition acquisition, DefSelfLearning defSelfLearning, String value) {
this.idSelfLearning = idSelfLearning;
this.acquisition = acquisition;
this.defSelfLearning = defSelfLearning;
this.value = value;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id_selfLearning", unique = true, nullable = false)
public int getIdSelfLearning() {
return this.idSelfLearning;
}
public void setIdSelfLearning(int idSelfLearning) {
this.idSelfLearning = idSelfLearning;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "id_acquisition", nullable = false)
public Acquisition getAcquisition() {
return this.acquisition;
}
public void setAcquisition(Acquisition acquisition) {
this.acquisition = acquisition;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumns({
#JoinColumn(name = "id_parName", nullable = false),
#JoinColumn(name = "id_description", nullable = false),
#JoinColumn(name = "id_note", nullable = false)
})
public DefSelfLearning getDefSelfLearning() {
return this.defSelfLearning;
}
public void setDefSelfLearning(DefSelfLearning defSelfLearning) {
this.defSelfLearning = defSelfLearning;
}
#Column(name = "value")
public String getValue() {
return this.value;
}
public void setValue(String value) {
this.value = value;
}
}
but when I create a defSelfLearning all work fine, but when I create a SelfLearning I receive MysqlDataTruncation exception:
Caused by: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column 'id_parName' at row 1
This error is enough explined, but I don't find where is the problem, this is the code for SelfLearning creation:
for (DefSelfLearning defSelfLearning:defSelfLearningList){
SelfLearning selfLearning=new SelfLearning();
String key = defSelfLearning.getExcelColumn()+index;
String value = actualRowValues.get(key);
selfLearning.setAcquisition(findByCarAndExcelRow(carServices.findById(acquisitionForm.getCar()), index));
selfLearning.setDefSelfLearning(defSelfLearning);
selfLearning.setValue(value);
System.out.println(selfLearning.getDefSelfLearning().getDefSelfLearningKeys().getParName());
selfLearningServices.create(selfLearning);
}
Do you find where is the problem?Thanks
This is the first row of defSelfLearning and it's where the code fails
if I set manually this it works:
This is a screen of java debug of first code, that fails:
You try to insert a char which is longer than 15 in the column "id_parName"
On your Entities, you have to choose between field and getter. And all the annotations should be on fields, or they should all be on getters, you can't mix both approaches (except if you use the #AccessType annotation).
Hibernate / Jpa will pick up the used approch from the annotation on Id.
Change #Id on the first Embeddable entity to #EmbeddedId and make sure it is on the getter.
SelfLearning wrong mappings the columns, id_parName= id_description, id_description= id_note and id_note=id_parName, but why?
So I read:
When the JoinColumns annotation is used, both the name and the
referencedColumnName elements must be specified in each such
JoinColumn annotation.
I have added this element so:
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumns({
#JoinColumn(name = "id_parName", referencedColumnName="parName", nullable = false),
#JoinColumn(name = "id_description", referencedColumnName="description", nullable = false),
#JoinColumn(name = "id_note", referencedColumnName="note", nullable = false)
})
public DefSelfLearning getDefSelfLearning() {
return this.defSelfLearning;
}
And it works

Jpa + Spring Data : cascading of a collection with compound key

I'm currently working on a small shop application for my School.
I have 2 objects I want to save :
Order.java
#Entity
#Table(name = "ORDERS")
public class Order {
private Integer id;
private Date orderDate;
private MailingAddress mailingAddress;
private User user;
private Collection<OrderLine> orderLines;
#Id
#Column(name = "ID")
#GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Basic
#Column(name = "ORDER_DATE")
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
#ManyToOne
#JoinColumn(name = "SHIPPING_ADR_ID", referencedColumnName = "ID")
public MailingAddress getMailingAddress() {
return mailingAddress;
}
public void setMailingAddress(MailingAddress mailingAddressByShippingAdrId) {
this.mailingAddress = mailingAddressByShippingAdrId;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "USER_ID", referencedColumnName = "LOGIN")
public User getUser() {
return user;
}
public void setUser(User userByUserId) {
this.user = userByUserId;
}
#OneToMany(mappedBy = "order", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
public Collection<OrderLine> getOrderLines() {
return orderLines;
}
public void setOrderLines(Collection<OrderLine> orderLinesesById) {
this.orderLines = orderLinesesById;
}
}
OrderLine.java
#Entity
#Table(name = "ORDER_LINES", schema = "")
#IdClass(OrderLinesPK.class)
public class OrderLine {
private int quantity;
private Integer orderId;
private String bookId;
private Book book;
private Order order;
#Basic
#Column(name = "QUANTITY")
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
#Id
#Column(name = "ORDERS_ID", insertable = false, updatable = false)
public Integer getOrderId() {
return orderId;
}
public void setOrderId(Integer ordersId) {
this.orderId = ordersId;
}
#Id
#Column(name = "BOOKS_ID", insertable = false, updatable = false)
public String getBookId() {
return bookId;
}
public void setBookId(String booksId) {
this.bookId = booksId;
}
#ManyToOne
#JoinColumn(name = "BOOKS_ID", referencedColumnName = "ISBN13", nullable = false, insertable = false, updatable = false)
public Book getBook() {
return book;
}
public void setBook(Book booksByBookId) {
this.book = booksByBookId;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "ORDERS_ID", referencedColumnName = "ID", nullable = false, insertable = false, updatable = false)
public Order getOrder() {
return order;
}
public void setOrder(Order ordersByOrderId) {
this.order = ordersByOrderId;
}
}
OrderLinesPK.java
public class OrderLinesPK implements Serializable {
private int ordersId;
private String booksId;
#Column(name = "ORDERS_ID")
#Id
public int getOrderId() {
return ordersId;
}
public void setOrderId(int ordersId) {
this.ordersId = ordersId;
}
#Column(name = "BOOKS_ID")
#Id
public String getBookId() {
return booksId;
}
public void setBookId(String booksId) {
this.booksId = booksId;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
OrderLinesPK that = (OrderLinesPK) o;
if (ordersId != that.ordersId) return false;
if (booksId != null ? !booksId.equals(that.booksId) : that.booksId != null) return false;
return true;
}
#Override
public int hashCode() {
int result = ordersId;
result = 31 * result + (booksId != null ? booksId.hashCode() : 0);
return result;
}
}
An order contains a collection of order lines.
I'm trying to save the order + the order lines in one call to OrderRepository.
But when I do that, I get the error
org.hibernate.PropertyAccessException: Null value was assigned to a property of primitive type setter of edu.flst.bookstore.domaine.bo.OrderLinesPK.orderId
which is pretty logic (I know the Id of the order is unknow at this stage, because the primary key of order is auto-incremented (I use MySQL)).
I don't know how to make this work with one call to orderService (without saving orderLines with orderLinesRepository first). Is it even possible ?
Regards
An Order can contain many Books and a Book can appear in many Order(s). So the many-to-many relation is your OrderLine object essentially. I would set an id (autogenerated) and two many-to-one relations in OrderLine. Then you discard the OrderLinesPK class, you save the Order, Book and OrderLine objects in this order in the same transaction.In this way, your model is simpler and you only need to save an extra id (with no physical meaning) in the database (the id of the OrderLine object)

Hibernate: save a new parent with the children inside without editing auto-generated bean and xml

I have this bean that is auto-generated from DB:
#Entity
#Table(name = "richiesta", catalog = "gestione_utenza")
public class Richiesta implements java.io.Serializable {
private Integer idRichiesta;
private MessaggiErrore messaggiErrore;
private Stato stato;
private Date dataInserimento;
private Date dataElaborazione;
private String nota;
private String usernameAssegnato;
private String utenteAutorizzante;
private String urlattivazione;
private Anagrafica anagrafica;
private Set<RichiestaApplicazione> richiestaApplicaziones = new HashSet<RichiestaApplicazione>(
0);
public Richiesta() {
}
public Richiesta(Stato stato, Date dataInserimento) {
this.stato = stato;
this.dataInserimento = dataInserimento;
}
public Richiesta(MessaggiErrore messaggiErrore, Stato stato,
Date dataInserimento, Date dataElaborazione, String nota,
String usernameAssegnato, String utenteAutorizzante,
String urlattivazione, Anagrafica anagrafica,
Set<RichiestaApplicazione> richiestaApplicaziones) {
this.messaggiErrore = messaggiErrore;
this.stato = stato;
this.dataInserimento = dataInserimento;
this.dataElaborazione = dataElaborazione;
this.nota = nota;
this.usernameAssegnato = usernameAssegnato;
this.utenteAutorizzante = utenteAutorizzante;
this.urlattivazione = urlattivazione;
this.anagrafica = anagrafica;
this.richiestaApplicaziones = richiestaApplicaziones;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "idRichiesta", unique = true, nullable = false)
public Integer getIdRichiesta() {
return this.idRichiesta;
}
public void setIdRichiesta(Integer idRichiesta) {
this.idRichiesta = idRichiesta;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "codiceErrore")
public MessaggiErrore getMessaggiErrore() {
return this.messaggiErrore;
}
public void setMessaggiErrore(MessaggiErrore messaggiErrore) {
this.messaggiErrore = messaggiErrore;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "stato", nullable = false)
public Stato getStato() {
return this.stato;
}
public void setStato(Stato stato) {
this.stato = stato;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "dataInserimento", nullable = false, length = 19)
public Date getDataInserimento() {
return this.dataInserimento;
}
public void setDataInserimento(Date dataInserimento) {
this.dataInserimento = dataInserimento;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "dataElaborazione", length = 19)
public Date getDataElaborazione() {
return this.dataElaborazione;
}
public void setDataElaborazione(Date dataElaborazione) {
this.dataElaborazione = dataElaborazione;
}
#Column(name = "nota", length = 256)
public String getNota() {
return this.nota;
}
public void setNota(String nota) {
this.nota = nota;
}
#Column(name = "usernameAssegnato", length = 20)
public String getUsernameAssegnato() {
return this.usernameAssegnato;
}
public void setUsernameAssegnato(String usernameAssegnato) {
this.usernameAssegnato = usernameAssegnato;
}
#Column(name = "utenteAutorizzante", length = 20)
public String getUtenteAutorizzante() {
return this.utenteAutorizzante;
}
public void setUtenteAutorizzante(String utenteAutorizzante) {
this.utenteAutorizzante = utenteAutorizzante;
}
#Column(name = "URLattivazione", length = 80)
public String getUrlattivazione() {
return this.urlattivazione;
}
public void setUrlattivazione(String urlattivazione) {
this.urlattivazione = urlattivazione;
}
#OneToOne(fetch = FetchType.LAZY, mappedBy = "richiesta")
public Anagrafica getAnagrafica() {
return this.anagrafica;
}
public void setAnagrafica(Anagrafica anagrafica) {
this.anagrafica = anagrafica;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "richiesta")
public Set<RichiestaApplicazione> getRichiestaApplicaziones() {
return this.richiestaApplicaziones;
}
public void setRichiestaApplicaziones(
Set<RichiestaApplicazione> richiestaApplicaziones) {
this.richiestaApplicaziones = richiestaApplicaziones;
}
}
I want to add a new Richiesta, with his childs, but with the code that I wrote I'm able to add only a new row in the table Richiesta:
Richiesta ric = new Richiesta();
Stato st = new Stato();
st.setIdStato(1);
ric.setStato(st);
ric.setDataInserimento(new Date());
Integer[] appId = getApplicazioniSelezionateDefault();
for (int k=0; k<appId.length; k++)
{
Applicazione ap = new Applicazione();
ap.setIdApplicazione(appId[k]);
ric.getRichiestaApplicaziones().add( new RichiestaApplicazione( ap, ric));
}
Ufficio uf = new Ufficio();
uf.setIdufficio(this.getUfficioVDR());
Qualifica qu = new Qualifica();
qu.setIdQualifica( CommonUtil.getIndexInteger(getQualificaSelezionataVDR()) );
ric.setAnagrafica(new Anagrafica(uf, qu, ric, getCognomeVDR(), getNomeVDR(), getDataNascitaVDR(), getTelefonoVDR(), getEmailVDR(), getIpVDR()));
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.save(ric);
session.getTransaction().commit();
I would like to have a new row in the table Anagrafica, and "N" news rows in the table RichiestaApplicazione.
#Entity
#Table(name = "anagrafica", catalog = "gestione_utenza")
public class Anagrafica implements java.io.Serializable {
private Integer idRichiesta;
private Ufficio ufficio;
private Qualifica qualifica;
private Richiesta richiesta;
private String cognome;
private String nome;
private Date dataNascita;
private String telefono;
private String email;
private String ip;
[...]
#GenericGenerator(name = "generator", strategy = "foreign", parameters = #Parameter(name = "property", value = "richiesta"))
#Id
#GeneratedValue(generator = "generator")
#Column(name = "idRichiesta", unique = true, nullable = false)
public Integer getIdRichiesta() {
return this.idRichiesta;
}
[...]
}
I read to add the CASCADE attribute to the xml/annotation, is it possible to make it without editing annotation/xml? For example adding something in the code.
To become persistent, a new entity instance must be added to the persistent context with session.persist(newEntity) or session.save(newEntity). You haven't called this method on anything except ric. So all the other created entities are still not persistent.

Categories

Resources