how do i set default value in column annotation - java

I am new in java. i created a entity class. where i wanted a default value for a field. i tried #Column(name = "ProjectStatus", nullable = false,columnDefinition = "varchar(50) default 'start'") annotaions but getting errors
my entity class is
package com.ults.hrms.model;
// default package
// Generated 17 Jan, 2017 12:04:43 PM by Hibernate Tools 3.4.0.CR1
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.ColumnDefault;
#Entity
#Table(name = "t_projectmaster", catalog = "db_hrms")
public class Projectmaster implements java.io.Serializable {
private Integer projectId;
private String projectUserIdtemp;
private String projectUserIdper;
private String projectName;
private String clentName;
private String projectDesc;
private Double projectValue;
private String projectTax;
private Date targetDate;
private Integer accountmanager;
private Integer projectManager;
private byte[] pofile;
private byte[] agreementFile;
/*#Column(name = "ProjectStatus",columnDefinition = "varchar(50) default 'ToStart'")*/
private String projectStatus;
private Boolean actvieStatus;
private Date creationDate;
private Date modifiedDate;
private Integer userId;
private String remarks;
public Projectmaster() {
}
public Projectmaster(String projectStatus) {
this.projectStatus = projectStatus;
}
public Projectmaster(String projectUserIdtemp, String projectUserIdper,
String projectName, String clentName, String projectDesc,
Double projectValue, String projectTax, Date targetDate,
Integer accountmanager, Integer projectManager, byte[] pofile,
byte[] agreementFile, String projectStatus, Boolean actvieStatus,
Date creationDate, Date modifiedDate, Integer userId, String remarks) {
this.projectUserIdtemp = projectUserIdtemp;
this.projectUserIdper = projectUserIdper;
this.projectName = projectName;
this.clentName = clentName;
this.projectDesc = projectDesc;
this.projectValue = projectValue;
this.projectTax = projectTax;
this.targetDate = targetDate;
this.accountmanager = accountmanager;
this.projectManager = projectManager;
this.pofile = pofile;
this.agreementFile = agreementFile;
this.projectStatus = projectStatus;
this.actvieStatus = actvieStatus;
this.creationDate = creationDate;
this.modifiedDate = modifiedDate;
this.userId = userId;
this.remarks = remarks;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "ProjectID", unique = true, nullable = false)
public Integer getProjectId() {
return this.projectId;
}
public void setProjectId(Integer projectId) {
this.projectId = projectId;
}
#Column(name = "ProjectUserIDTemp", length = 50)
public String getProjectUserIdtemp() {
return this.projectUserIdtemp;
}
public void setProjectUserIdtemp(String projectUserIdtemp) {
this.projectUserIdtemp = projectUserIdtemp;
}
#Column(name = "ProjectUserIDPer", length = 50)
public String getProjectUserIdper() {
return this.projectUserIdper;
}
public void setProjectUserIdper(String projectUserIdper) {
this.projectUserIdper = projectUserIdper;
}
#Column(name = "ProjectName")
public String getProjectName() {
return this.projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
#Column(name = "ClentName", length = 100)
public String getClentName() {
return this.clentName;
}
public void setClentName(String clentName) {
this.clentName = clentName;
}
#Column(name = "ProjectDesc", length = 65535)
public String getProjectDesc() {
return this.projectDesc;
}
public void setProjectDesc(String projectDesc) {
this.projectDesc = projectDesc;
}
#Column(name = "ProjectValue", precision = 22, scale = 0)
public Double getProjectValue() {
return this.projectValue;
}
public void setProjectValue(Double projectValue) {
this.projectValue = projectValue;
}
#Column(name = "ProjectTax", length = 50)
public String getProjectTax() {
return this.projectTax;
}
public void setProjectTax(String projectTax) {
this.projectTax = projectTax;
}
#Temporal(TemporalType.DATE)
#Column(name = "TargetDate", length = 10)
public Date getTargetDate() {
return this.targetDate;
}
public void setTargetDate(Date targetDate) {
this.targetDate = targetDate;
}
#Column(name = "Accountmanager")
public Integer getAccountmanager() {
return this.accountmanager;
}
public void setAccountmanager(Integer accountmanager) {
this.accountmanager = accountmanager;
}
#Column(name = "ProjectManager")
public Integer getProjectManager() {
return this.projectManager;
}
public void setProjectManager(Integer projectManager) {
this.projectManager = projectManager;
}
#Column(name = "POFile")
public byte[] getPofile() {
return this.pofile;
}
public void setPofile(byte[] pofile) {
this.pofile = pofile;
}
#Column(name = "AgreementFile")
public byte[] getAgreementFile() {
return this.agreementFile;
}
public void setAgreementFile(byte[] agreementFile) {
this.agreementFile = agreementFile;
}
#Column(name = "ProjectStatus", nullable = false,columnDefinition = "varchar(50) default 'start'")
public String getProjectStatus() {
return this.projectStatus;
}
public void setProjectStatus(String projectStatus) {
this.projectStatus = projectStatus;
}
#Column(name = "ActvieStatus")
public Boolean getActvieStatus() {
return this.actvieStatus;
}
public void setActvieStatus(Boolean actvieStatus) {
this.actvieStatus = actvieStatus;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "CreationDate",columnDefinition = "DATE DEFAULT CURRENT_DATE", length = 19)
public Date getCreationDate() {
return this.creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "ModifiedDate", length = 19)
public Date getModifiedDate() {
return this.modifiedDate;
}
public void setModifiedDate(Date modifiedDate) {
this.modifiedDate = modifiedDate;
}
#Column(name = "UserID")
public Integer getUserId() {
return this.userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
#Column(name = "Remarks", length = 65535)
public String getRemarks() {
return this.remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
}

This will work for you,
Initialise the attribute while creating object only.
private String projectStatus = "start";

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.

count rows in table using jpa

i'm trying to develop a function that count number of rows with specific arguments: for example i want to count the number of dossier which the client is 'client a' i want to get it in a table the first case contain the name of client and the second contanint the number of dossier
for example
client a |5
client b |12
....
right now i just wrote a function that returns the number of all rows
public Object countrow(){
Query query=em.createQuery("SELECT COUNT(d) FROM Dossier d");
Object resultat= query.getSingleResult();
System.out.println(resultat);
return resultat;
}
here's my entity named dossier :
package model;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#NamedQueries({ #NamedQuery(name = "Dossier.findAll", query = "select o from Dossier o") })
public class Dossier implements Serializable {
#Column(name = "CAT_PROB", length = 4000)
private String catProb;
#Column(length = 4000)
private String client;
#Column(length = 4000)
private String contact;
#Temporal(TemporalType.DATE)
#Column(name = "DATE_APPEL")
private Date dateAppel;
#Temporal(TemporalType.DATE)
#Column(name = "DATE_CREATION")
private Date dateCreation;
#Temporal(TemporalType.DATE)
#Column(name = "DATE_FERMERTURE")
private Date dateFermerture;
#Column(name = "DEP_ID", length = 4000)
private String depId;
#Column(name = "DESCRI_PROB", length = 4000)
private String descriProb;
#Column(name = "DUREE_TRAITEMENT")
private Long dureeTraitement;
#Column(length = 4000)
private String etat;
#Column(name = "FINAL", length = 4000)
private String final_;
#Column(name = "HEURE_APPEL", length = 20)
private String heureAppel;
#Column(name = "HEURE_FERMETURE", length = 20)
private String heureFermeture;
#Id
#Column(name = "ID_DOSSIER", nullable = false, length = 4000)
private String idDossier;
#Column(name = "ING_AFF", length = 4000)
private String ingAff;
#Column(length = 4000)
private String motiftemp;
#Column(name = "OUVERT_PAR", length = 4000)
private String ouvertPar;
#Column(name = "TEL_CONTACT")
private BigDecimal telContact;
#Column(name = "TYPE_DOSSIER", length = 4000)
private String typeDossier;
public Dossier() {
}
public Dossier(String catProb, String client, String contact, Date dateAppel, Date dateCreation,
Date dateFermerture, String depId, String descriProb, Long dureeTraitement, String etat,
String final_, String heureAppel, String heureFermeture, String idDossier, String ingAff,
String motiftemp, String ouvertPar, BigDecimal telContact, String typeDossier) {
this.catProb = catProb;
this.client = client;
this.contact = contact;
this.dateAppel = dateAppel;
this.dateCreation = dateCreation;
this.dateFermerture = dateFermerture;
this.depId = depId;
this.descriProb = descriProb;
this.dureeTraitement = dureeTraitement;
this.etat = etat;
this.final_ = final_;
this.heureAppel = heureAppel;
this.heureFermeture = heureFermeture;
this.idDossier = idDossier;
this.ingAff = ingAff;
this.motiftemp = motiftemp;
this.ouvertPar = ouvertPar;
this.telContact = telContact;
this.typeDossier = typeDossier;
}
public String getCatProb() {
return catProb;
}
public void setCatProb(String catProb) {
this.catProb = catProb;
}
public String getClient() {
return client;
}
public void setClient(String client) {
this.client = client;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public Date getDateAppel() {
return dateAppel;
}
public void setDateAppel(Date dateAppel) {
this.dateAppel = dateAppel;
}
public Date getDateCreation() {
return dateCreation;
}
public void setDateCreation(Date dateCreation) {
this.dateCreation = dateCreation;
}
public Date getDateFermerture() {
return dateFermerture;
}
public void setDateFermerture(Date dateFermerture) {
this.dateFermerture = dateFermerture;
}
public String getDepId() {
return depId;
}
public void setDepId(String depId) {
this.depId = depId;
}
public String getDescriProb() {
return descriProb;
}
public void setDescriProb(String descriProb) {
this.descriProb = descriProb;
}
public Long getDureeTraitement() {
return dureeTraitement;
}
public void setDureeTraitement(Long dureeTraitement) {
this.dureeTraitement = dureeTraitement;
}
public String getEtat() {
return etat;
}
public void setEtat(String etat) {
this.etat = etat;
}
public String getFinal_() {
return final_;
}
public void setFinal_(String final_) {
this.final_ = final_;
}
public String getHeureAppel() {
return heureAppel;
}
public void setHeureAppel(String heureAppel) {
this.heureAppel = heureAppel;
}
public String getHeureFermeture() {
return heureFermeture;
}
public void setHeureFermeture(String heureFermeture) {
this.heureFermeture = heureFermeture;
}
public String getIdDossier() {
return idDossier;
}
public void setIdDossier(String idDossier) {
this.idDossier = idDossier;
}
public String getIngAff() {
return ingAff;
}
public void setIngAff(String ingAff) {
this.ingAff = ingAff;
}
public String getMotiftemp() {
return motiftemp;
}
public void setMotiftemp(String motiftemp) {
this.motiftemp = motiftemp;
}
public String getOuvertPar() {
return ouvertPar;
}
public void setOuvertPar(String ouvertPar) {
this.ouvertPar = ouvertPar;
}
public BigDecimal getTelContact() {
return telContact;
}
public void setTelContact(BigDecimal telContact) {
this.telContact = telContact;
}
public String getTypeDossier() {
return typeDossier;
}
public void setTypeDossier(String typeDossier) {
this.typeDossier = typeDossier;
}
}

How to update the record by adding one more child row for exciting child by using hibernate?

Here I am going to update the record. By adding one more child for the exciting parent and here I am removing the child by iterating the child's and then I am updating the record but its giving the exception as.
EXCEPTION:org.hibernate.HibernateException: Found two representations of same collection: com.treamis.entity.LibraryBookListEntity.chield
Here is my code.
LibraryBookForm lb = (LibraryBookForm) form;
int bookid = lb.getBooklistid();
System.out.println("bookidbookidbookid" + bookid);
String[] bar = lb.getBarcode();
String[] accission = lb.getAccessno();
System.out.println("accissionaccission" + bar);
UserEntity msg;
HttpSession session = request.getSession(false);
msg = (UserEntity) session.getAttribute("user");
int catid = lb.getCategory();
Session ses = HibernateUtil.getSessionFactory().openSession();
String d1 = lb.getBilldate();
java.util.Date temp = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH).parse(d1);
java.sql.Date date = new java.sql.Date(temp.getTime());
String d2 = lb.getDateAdded();
java.util.Date temp1 = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH).parse(d2);
java.sql.Date submissionDate = new java.sql.Date(temp1.getTime());
CategoryEntity ce = (CategoryEntity) ses.get(CategoryEntity.class, catid);
LibraryBookListEntity lbl = (LibraryBookListEntity) ses.load(LibraryBookListEntity.class, bookid);
Set<LibraryBarCodeEntity> s1 = lbl.getChield();
for (LibraryBarCodeEntity lbb : s1) {
System.out.println("inside delte");
ses.delete(lbb);
}
Transaction tx = ses.beginTransaction();
lbl.setEdition(lb.getEdition());
lbl.setPublisher(lb.getPublisher());
lbl.setPlace(lb.getPlace());
lbl.setPage(lb.getPag());
lbl.setSource(lb.getSource());
lbl.setBillno(lb.getBillno());
lbl.setBilldate(date);
lbl.setPublishedyear(lb.getPublishedyear());
lbl.setCallno(lb.getCallno());
lbl.setIsbn(lb.getIsbn());
lbl.setBooktitle(lb.getBooktitle());
lbl.setRack(lb.getRack());
lbl.setAuthor(lb.getAuthor());
lbl.setPrice(lb.getPrice());
lbl.setCategoryid(ce);
lbl.setDateAdded(submissionDate);
lbl.setTcopies(lb.getTcopies());
lbl.setAddedBy(msg);
lbl.setAddedate(new Date());
lbl.setModifiedBy(null);
lbl.setModifiedDate(null);
try {
java.util.List list = Arrays.asList(bar);
Document document = new Document(new Rectangle(PageSize.A4));
File file = new File("d://" + lb.getBooktitle() + ".pdf");
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file, false));
document.open();
Paragraph para = new Paragraph();
Set<LibraryBarCodeEntity> s = new HashSet<LibraryBarCodeEntity>();
LibraryBarCodeEntity mb = null;
for (int i = 0; i < list.size(); i++) {
System.out.println("inside library model edit");
mb = new LibraryBarCodeEntity();
System.out.println("bar[i]" + bar[i]);
System.out.println("bar[i]" + accission[i]);
mb.setBarCode(bar[i]);
mb.setAccessno(accission[i]);
mb.setParent(lbl);
para.add(new Phrase(new Chunk(BarcodeDao.genarateBarcode(bar[i], writer), 0, 0, true)));
para.add(new Phrase(Chunk.NEWLINE));
para.add(new Phrase(Chunk.NEWLINE));
// s.add(mb);
ses.saveOrUpdate(lbl);
}
// lbl.setChield(s);
tx.commit();
Here is my LibraryBookListEntity Entity
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.treamis.entity;
import java.io.Serializable;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
/**
*
* #author admin
*/
#Entity
#Table(name = "LibraryBookListTable")
public class LibraryBookListEntity implements Serializable {
#Id
#GeneratedValue
#Column(name = "BookListId")
private int booklistid;
#Column(name = "ISBN", nullable = false)
private String isbn;
#Column(name = "edition", nullable = false)
private String edition;
#Column(name = "publisher", nullable = false)
private String publisher;
#Column(name = "place", nullable = false)
private String place;
#Column(name = "page", nullable = false)
private String page;
#Column(name = "source", nullable = false)
private String source;
#Column(name = "billno", nullable = false)
private String billno;
#Column(name = "callno", nullable = false)
private String callno;
#Column(name = "BookTitle", nullable = false)
private String booktitle;
#Column(name = "BookAuthor", nullable = false)
private String author;
#Column(name = "BookPrice", nullable = false)
private float price;
#Column(name = "RackNumber", nullable = false)
private String rack;
#Column(name = "PublishedYear", nullable = false)
private String publishedyear;
#Column(name = "NoofCopies", nullable = false)
private int tcopies;
#Column(name = "DateAdded", nullable = false)
private java.sql.Date dateAdded;
#Column(name = "billdate", nullable = false)
private java.sql.Date billdate;
#ManyToOne(fetch = FetchType.LAZY, targetEntity = CategoryEntity.class)
#JoinColumn(name = "category_Id", referencedColumnName = "category_Id", nullable = true)
private CategoryEntity categoryid;
#OneToOne
private UserEntity addedBy;
#OneToOne
private UserEntity modifiedBy;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "parent")
#JoinColumn(name = "BookListId", referencedColumnName = "BookListId")
#Cascade({CascadeType.SAVE_UPDATE})
private Set< LibraryBarCodeEntity> chield;
public Set<LibraryBarCodeEntity> getChield() {
return chield;
}
public void setChield(Set<LibraryBarCodeEntity> chield) {
this.chield = chield;
}
//#Column(name = "AddedDate", nullable = false)
#Temporal(javax.persistence.TemporalType.TIMESTAMP)
private java.util.Date addedate;
// #Column(name = "ModifiedDate", nullable = false)
#Temporal(javax.persistence.TemporalType.TIMESTAMP)
private java.util.Date modifiedDate;
public int getBooklistid() {
return booklistid;
}
public void setBooklistid(int booklistid) {
this.booklistid = booklistid;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getBooktitle() {
return booktitle;
}
public void setBooktitle(String booktitle) {
this.booktitle = booktitle;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getRack() {
return rack;
}
public void setRack(String rack) {
this.rack = rack;
}
public int getTcopies() {
return tcopies;
}
public void setTcopies(int tcopies) {
this.tcopies = tcopies;
}
public java.sql.Date getDateAdded() {
return dateAdded;
}
public void setDateAdded(java.sql.Date dateAdded) {
this.dateAdded = dateAdded;
}
public CategoryEntity getCategoryid() {
return categoryid;
}
public void setCategoryid(CategoryEntity categoryid) {
this.categoryid = categoryid;
}
public UserEntity getAddedBy() {
return addedBy;
}
public void setAddedBy(UserEntity addedBy) {
this.addedBy = addedBy;
}
public UserEntity getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(UserEntity modifiedBy) {
this.modifiedBy = modifiedBy;
}
public java.util.Date getAddedate() {
return addedate;
}
public void setAddedate(java.util.Date addedate) {
this.addedate = addedate;
}
public java.util.Date getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(java.util.Date modifiedDate) {
this.modifiedDate = modifiedDate;
}
// public String getAccessionnumber() {
// return accessionnumber;
// }
//
// public void setAccessionnumber(String accessionnumber) {
// this.accessionnumber = accessionnumber;
// }
public String getEdition() {
return edition;
}
public void setEdition(String edition) {
this.edition = edition;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getBillno() {
return billno;
}
public void setBillno(String billno) {
this.billno = billno;
}
public String getCallno() {
return callno;
}
public void setCallno(String callno) {
this.callno = callno;
}
public java.sql.Date getBilldate() {
return billdate;
}
public void setBilldate(java.sql.Date billdate) {
this.billdate = billdate;
}
public String getPublishedyear() {
return publishedyear;
}
public void setPublishedyear(String publishedyear) {
this.publishedyear = publishedyear;
}
// public Set< LibraryBarCodeEntity> getChield() {
// return chield;
// }
//
// public void setChield(Set< LibraryBarCodeEntity> chield) {
// this.chield = chield;
// }
}
Here is my another entity
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.treamis.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
/**
*
* #author admin
*/
#Entity
#Table(name = "LibraryBarCodeTable")
public class LibraryBarCodeEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "S_no", nullable = false)
private int S_no;
#Column(name = "BookBarCode", nullable = false)
private String barCode;
private String accessno;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "BookListId", referencedColumnName = "BookListId")
#Cascade({CascadeType.ALL})
private LibraryBookListEntity parent;
public LibraryBookListEntity getParent() {
return parent;
}
public void setParent(LibraryBookListEntity parent) {
this.parent = parent;
}
public int getS_no() {
return S_no;
}
public void setS_no(int S_no) {
this.S_no = S_no;
}
public String getBarCode() {
return barCode;
}
public void setBarCode(String barCode) {
this.barCode = barCode;
}
public String getAccessno() {
return accessno;
}
public void setAccessno(String accessno) {
this.accessno = accessno;
}
}
You formed new set . You have to set that to the parent object (that is lb1). Then if u save lb1 changes in the child set will be saved. (Make sure you have given cascede save-update or all property in mapping for the set )
for (int i = 0; i < list.size(); i++) {
System.out.println("inside library model edit");
mb = new LibraryBarCodeEntity();
System.out.println("bar[i]" + bar[i]);
System.out.println("bar[i]" + accission[i]);
mb.setBarCode(bar[i]);
mb.setAccessno(accission[i]);
mb.setParent(lbl);
para.add(new Phrase(new Chunk(BarcodeDao.genarateBarcode(bar[i], writer), 0, 0, true)));
para.add(new Phrase(Chunk.NEWLINE));
para.add(new Phrase(Chunk.NEWLINE));
s.add(mb);
}
lbl.setChield(s);
ses.saveOrUpdate(lbl);
tx.commit();

How to add series of keys on an Entity? Openjpa

I have this entity named product. Is there a way to add a series of multiple keys? Like A key for Serial Number, a key for Serial Number and Model, a key for Model etc. How can you do this? Thank you very much.
*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package lotmovement.business.entity;
import java.io.Serializable;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Version;
/**
*
* #author god-gavedmework
*/
#Entity
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long product_Id;
#Column(name = "SERIAL_NUMBER", nullable = false,length = 30)
private String serial_Number;
#Column(name = "DATE_ASSEMBLED", nullable = false,length = 10)
private String date_Assembled;
#Column(name = "TIME_ASSEMBLED", nullable = false,length = 20)
private String time_Assembled;
#Column(name = "MODEL", nullable = false,length = 20)
private String model;
#Column(name = "BATCH_ID", nullable = false,length = 6)
private int batch_Id;
#Column(name = "PROCESS_CODE", nullable = false,length = 3)
private int process_Code;
#Column(name = "DC_POWER_PCB_SERIAL", nullable = false,length = 20)
private String dc_Power_PCB_Serial;
#Column(name = "CONTROL_PWER_PCB_SERIAL", nullable = false,length = 20)
private String control_Power_PCB_Serial;
#Column(name = "MAINS_POWER_PCB_SERIAL", nullable = false,length = 20)
private String mains_Power_PCB_Serial;
#Column(name = "BLOWER_SERIAL", nullable = false,length = 20)
private String blower_Serial;
#Column(name = "HEATERPLATE_SERIAL", nullable = false,length = 20)
private String heaterPlate_Serial;
#Column(name = "LAST_PROCESS", nullable = false,length = 3)
private String last_Process;
#Column(name = "LAST_DATE", nullable = false,length = 20)
private String last_Date;
#Version
#Column(name = "LAST_UPDATED_TIME")
private java.sql.Timestamp updatedTime;
public Timestamp getUpdatedTime() {
return updatedTime;
}
public void setUpdatedTime(Timestamp updatedTime) {
this.updatedTime = updatedTime;
}
public Long getProduct_Id() {
return product_Id;
}
public void setProduct_Id(Long product_Id) {
this.product_Id = product_Id;
}
public String getSerial_Number() {
return serial_Number;
}
public void setSerial_Number(String serial_Number) {
this.serial_Number = serial_Number;
}
public String getDate_Assembled() {
return date_Assembled;
}
public void setDate_Assembled(String date_Assembled) {
this.date_Assembled = date_Assembled;
}
public String getTime_Assembled() {
return time_Assembled;
}
public void setTime_Assembled(String time_Assembled) {
this.time_Assembled = time_Assembled;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getBatch_Id() {
return batch_Id;
}
public void setBatch_Id(int batch_Id) {
this.batch_Id = batch_Id;
}
public int getProcess_Code() {
return process_Code;
}
public void setProcess_Code(int process_Code) {
this.process_Code = process_Code;
}
public String getDc_Power_PCB_Serial() {
return dc_Power_PCB_Serial;
}
public void setDc_Power_PCB_Serial(String dc_Power_PCB_Serial) {
this.dc_Power_PCB_Serial = dc_Power_PCB_Serial;
}
public String getControl_Power_PCB_Serial() {
return control_Power_PCB_Serial;
}
public void setControl_Power_PCB_Serial(String control_Power_PCB_Serial) {
this.control_Power_PCB_Serial = control_Power_PCB_Serial;
}
public String getMains_Power_PCB_Serial() {
return mains_Power_PCB_Serial;
}
public void setMains_Power_PCB_Serial(String mains_Power_PCB_Serial) {
this.mains_Power_PCB_Serial = mains_Power_PCB_Serial;
}
public String getBlower_Serial() {
return blower_Serial;
}
public void setBlower_Serial(String blower_Serial) {
this.blower_Serial = blower_Serial;
}
public String getHeaterPlate_Serial() {
return heaterPlate_Serial;
}
public void setHeaterPlate_Serial(String heaterPlate_Serial) {
this.heaterPlate_Serial = heaterPlate_Serial;
}
public String getLast_Process() {
return last_Process;
}
public void setLast_Process(String last_Process) {
this.last_Process = last_Process;
}
public String getLast_Date() {
return last_Date;
}
public void setLast_Date(String last_Date) {
this.last_Date = last_Date;
}
}
I believe what you are looking for is fundamentally incorrect. A Key should be a unique identifier for an instance of entity. In your example, you want to have a key for "Model", it simply doesn't sounds right.
If you mean something else for "Key", please clarify and we may further discuss on it.

how to compare avoid insertion of duplicate data into arraylist

i have a class where i am inserting data into a array-list based on the id provided.
I am passing a bookId into my class and by comparing bookid i am get a book object. And after getting that object(book) ,am inserting into my arraylist.
Now I do't want to insert same data more then once. If a same bookid passes in the class then only it should store once.
i am storing my arraylist into session.
please check my code. And suggest me a solution for my problem.How to avoid duplicate insertion of data into my arraylist?
AddBookToSession.java
..................
...................
...................
private Integer bid; HttpServletRequest request = ServletActionContext.getRequest();
private Map<String, Object> session;
List<Bookdetails> books = new ArrayList<Bookdetails>();
private BookdetailsDAO dao = new BookdetailsDAO();
public String execute()
{
String bookid = request.getParameter("bid");
Bookdetails book = dao.listBookDetailsById(Integer.parseInt(bookid));
int checkduplicate=1;
//getting list from session to compare with the id
List list = (List) session.get( VisionBooksConstants.USER );
Iterator itr = list.iterator();
int bidd=0;
while(itr.hasNext())
{
Bookdetails bks=(Bookdetails) itr.next();
bidd=bks.getId(); //getting bookid from arraylist,which was stored in session
if (bidd==Integer.parseInt(bookid))
{
checkduplicate=0; //returns 0 ,so that i can compare it below to avoid duplicate data
}
}
//
if (book != null && checkduplicate==1 )
{
books = sessionBooks();
HttpServletRequest request = ServletActionContext.getRequest();
books.add(book);
System.out.println("books size"+books.size());
}
return SUCCESS;
}
........................
......................
Alternative solution
HashSet() update
public String execute()
{ HashSet<Bookdetails> books = new HashSet<Bookdetails>();
String bookid = request.getParameter("bid");
Bookdetails book = dao.listBookDetailsById(Integer.parseInt(bookid));
books = (HashSet<Bookdetails>) session.get(BillTransactionBooksConstants.BOK);
if ( books == null ) books = new HashSet<Bookdetails>();
boolean already_exists = false;
books.add(book);
System.out.println("books size"+books.size());
session.put(BillTransactionBooksConstants.BOK,books);
return SUCCESS;
}
Bookdetails.java(Pojo)
package v.esoft.pojos;
// Generated Nov 5, 2012 9:37:14 PM by Hibernate Tools 3.4.0.CR1
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* Bookdetails generated by hbm2java
*/
#Entity
#Table(name = "bookdetails", catalog = "vbsoftware")
public class Bookdetails implements java.io.Serializable {
private Integer id;
private String isbn;
private String bookTitile;
private String authFirstname;
private String authLastname;
private String editionYear;
private Integer subjectId;
private Integer coverId;
private Integer languageId;
private String publisherName;
private Integer editionId;
private Float price;
private String quantity;
private String description;
private Integer locationId;
private String remarks;
private String img1;
private String img2;
private String videoUrl;
private Integer createrId;
private Date createdDate;
private Integer updateId;
private Date updatedDate;
public Bookdetails() {
}
public Bookdetails(String isbn, String bookTitile, String authFirstname,
String authLastname, String editionYear, Integer subjectId,
Integer coverId, Integer languageId, String publisherName,
Integer editionId, Float price, String quantity,
String description, Integer locationId, String remarks,
String img1, String img2, String videoUrl, Integer createrId,
Date createdDate, Integer updateId, Date updatedDate) {
this.isbn = isbn;
this.bookTitile = bookTitile;
this.authFirstname = authFirstname;
this.authLastname = authLastname;
this.editionYear = editionYear;
this.subjectId = subjectId;
this.coverId = coverId;
this.languageId = languageId;
this.publisherName = publisherName;
this.editionId = editionId;
this.price = price;
this.quantity = quantity;
this.description = description;
this.locationId = locationId;
this.remarks = remarks;
this.img1 = img1;
this.img2 = img2;
this.videoUrl = videoUrl;
this.createrId = createrId;
this.createdDate = createdDate;
this.updateId = updateId;
this.updatedDate = updatedDate;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
//###########################################################################
// FOR HASHSETS EQUALS
//###########################################################################
public Bookdetails(int i){ id = i; }
public boolean equals(Object obj){
System.err.println("called"); // Never happens
return id == ((Bookdetails)obj).id;
}
#Column(name = "isbn", length = 90)
public String getIsbn() {
return this.isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
#Column(name = "book_titile")
public String getBookTitile() {
return this.bookTitile;
}
public void setBookTitile(String bookTitile) {
this.bookTitile = bookTitile;
}
#Column(name = "auth_firstname", length = 120)
public String getAuthFirstname() {
return this.authFirstname;
}
public void setAuthFirstname(String authFirstname) {
this.authFirstname = authFirstname;
}
#Column(name = "auth_lastname", length = 120)
public String getAuthLastname() {
return this.authLastname;
}
public void setAuthLastname(String authLastname) {
this.authLastname = authLastname;
}
#Column(name = "edition_year", length = 20)
public String getEditionYear() {
return this.editionYear;
}
public void setEditionYear(String editionYear) {
this.editionYear = editionYear;
}
#Column(name = "subject_id")
public Integer getSubjectId() {
return this.subjectId;
}
public void setSubjectId(Integer subjectId) {
this.subjectId = subjectId;
}
#Column(name = "cover_id")
public Integer getCoverId() {
return this.coverId;
}
public void setCoverId(Integer coverId) {
this.coverId = coverId;
}
#Column(name = "language_id")
public Integer getLanguageId() {
return this.languageId;
}
public void setLanguageId(Integer languageId) {
this.languageId = languageId;
}
#Column(name = "publisher_name", length = 70)
public String getPublisherName() {
return this.publisherName;
}
public void setPublisherName(String publisherName) {
this.publisherName = publisherName;
}
#Column(name = "edition_id")
public Integer getEditionId() {
return this.editionId;
}
public void setEditionId(Integer editionId) {
this.editionId = editionId;
}
#Column(name = "price", precision = 12, scale = 0)
public Float getPrice() {
return this.price;
}
public void setPrice(Float price) {
this.price = price;
}
#Column(name = "quantity", length = 40)
public String getQuantity() {
return this.quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
#Column(name = "description", length = 65535)
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
#Column(name = "location_id")
public Integer getLocationId() {
return this.locationId;
}
public void setLocationId(Integer locationId) {
this.locationId = locationId;
}
#Column(name = "remarks", length = 65535)
public String getRemarks() {
return this.remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
#Column(name = "img1")
public String getImg1() {
return this.img1;
}
public void setImg1(String img1) {
this.img1 = img1;
}
#Column(name = "img2")
public String getImg2() {
return this.img2;
}
public void setImg2(String img2) {
this.img2 = img2;
}
#Column(name = "video_url", length = 65535)
public String getVideoUrl() {
return this.videoUrl;
}
public void setVideoUrl(String videoUrl) {
this.videoUrl = videoUrl;
}
#Column(name = "creater_id")
public Integer getCreaterId() {
return this.createrId;
}
public void setCreaterId(Integer createrId) {
this.createrId = createrId;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "created_date", length = 19)
public Date getCreatedDate() {
return this.createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
#Column(name = "update_id")
public Integer getUpdateId() {
return this.updateId;
}
public void setUpdateId(Integer updateId) {
this.updateId = updateId;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "updated_date", length = 19)
public Date getUpdatedDate() {
return this.updatedDate;
}
public void setUpdatedDate(Date updatedDate) {
this.updatedDate = updatedDate;
}
}
How to avoid duplicate insertion of data into my arraylist?
Use a Set instead.
Also, make sure you are implementing equals and hashcode correctly.
EDITED: It should work now.
public String execute()
{
String bookid = request.getParameter("bid");
Bookdetails book = dao.listBookDetailsById(Integer.parseInt(bookid));
books = (ArrayList) session.get( VisionBooksConstants.USER );
if ( books == null ) books = new ArrayList<Bookdetails>();
boolean already_exists = false;
for ( Bookdetails b : books ) {
if ( b.getID().equals(bookid) ) {
already_exists = true; break;
}
}
if (book != null && !already_exists )
{
books.add(book);
System.out.println("books size"+books.size());
session.put(VisionBooksConstants.USER,books);
}
return SUCCESS;
}

Categories

Resources