TableView not showing values when using two Objects JAVAFX with Hibernate - java

I am trying to create a TableView in JavaFX, but after many attempts values are not showing without giving any Errors.
If i create a TableView with only one Object declared (TableView) it works properly.
I already tried to create a "helper" class, which contained both objects as it's attributes, but still the same problem no errors just TableView not working.
Any suggestions how to fix this?
Here is what i am trying to do:
public TableColumn<CarEntity, String> HistoryBrand;
public TableColumn<CarEntity, String> HistoryColor;
public TableColumn<CarEntity, Date> HistoryDate;
public TableColumn<CarEntity,String> HistoryCategory;
public TableColumn<CarEntity,Double> HistoryPrice;
public TableColumn<OrdersArchiveEntity, Integer> HistoryCarScore;
public TableColumn<OrdersArchiveEntity, Integer> HistoryOrderScore;
public TableColumn<OrdersArchiveEntity, Date> HistoryRentalDate;
public TableColumn<OrdersArchiveEntity, Date> HistoryReturnDate;
public TableView HistoryTable;
HistoryBrand.setCellValueFactory(new PropertyValueFactory<CarEntity, String>("mark"));
HistoryColor.setCellValueFactory(new PropertyValueFactory<CarEntity,String>("color"));
HistoryDate.setCellValueFactory(new PropertyValueFactory<CarEntity, Date>("productionDate"));
HistoryCategory.setCellValueFactory(new PropertyValueFactory<CarEntity, String>("category"));
HistoryPrice.setCellValueFactory(new PropertyValueFactory<CarEntity, Double>("price"));
HistoryCarScore.setCellValueFactory(new PropertyValueFactory<OrdersArchiveEntity,Integer>("carScore"));
HistoryOrderScore.setCellValueFactory(new PropertyValueFactory<OrdersArchiveEntity,Integer>("orderScore"));
HistoryRentalDate.setCellValueFactory(new PropertyValueFactory<OrdersArchiveEntity,Date>("rentalDate"));
HistoryReturnDate.setCellValueFactory(new PropertyValueFactory<OrdersArchiveEntity,Date>("returnDate"));
Query queryHist = session.createQuery("select c, o from OrdersArchiveEntity o, CarEntity c where c.id=o.carByCarId.id");
List HistoryList = queryHist.list();
ObservableList Historia = FXCollections.observableArrayList(HistoryList);
HistoryTable.setItems(Historia);
And here are my Classes
package DataBase;
import javax.persistence.*;
import java.sql.Date;
import java.util.Objects;
#Entity
#Table(name = "Car", schema = "dbo", catalog = "master")
public class CarEntity {
private int id;
private RentalBaseEntity RentalBaseEntityByRentalBaseId;
public String mark;
public String color;
public Date productionDate;
public double price;
private String category;
#Id
#Column(name = "ID", nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Basic
#Column(name = "Mark", nullable = false, length = 20)
public String getMark() {
return mark;
}
public void setMark(String mark) {
this.mark = mark;
}
#Basic
#Column(name = "Color", nullable = false, length = 20)
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
#Basic
#Column(name = "Production_Date", nullable = false)
public Date getProductionDate() {
return productionDate;
}
public void setProductionDate(Date productionDate) {
this.productionDate = productionDate;
}
#Basic
#Column(name = "Price", nullable = false, precision = 0)
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
#Basic
#Column(name = "Category", nullable = false, length = 20)
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CarEntity carEntity = (CarEntity) o;
return id == carEntity.id &&
Double.compare(carEntity.price, price) == 0 &&
Objects.equals(mark, carEntity.mark) &&
Objects.equals(color, carEntity.color) &&
Objects.equals(productionDate, carEntity.productionDate) &&
Objects.equals(category, carEntity.category);
}
#Override
public int hashCode() {
return Objects.hash(id, mark, color, productionDate, price, category);
}
#ManyToOne
#JoinColumn(name = "RentalBase_Id", referencedColumnName = "ID", nullable = false)
public RentalBaseEntity getRentalBaseEntityByRentalBaseId() {
return RentalBaseEntityByRentalBaseId;
}
public void setRentalBaseEntityByRentalBaseId(RentalBaseEntity here) {
this.RentalBaseEntityByRentalBaseId = here;
}
}
package DataBase;
import javax.persistence.*;
import java.sql.Date;
import java.util.Objects;
#Entity
#Table(name = "OrdersArchive", schema = "dbo", catalog = "master")
public class OrdersArchiveEntity {
private int id;
private int orderScore;
private int carScore;
private Date rentalDate;
private Date returnDate;
private CarEntity carByCarId;
private SellerEntity sellerBySellerId;
private ClientEntity clientByClientId;
private RentalBaseEntity RentalBaseEntitybyID;
private int Orders_Id;
#Id
#Column(name = "ID", nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Basic
#Column(name = "Order_Score", nullable = false)
public int getOrderScore() {
return orderScore;
}
public void setOrderScore(int orderScore) {
this.orderScore = orderScore;
}
#Basic
#Column(name = "Orders_Id", nullable = false)
public int getOrders_Id() {
return Orders_Id;
}
public void setOrders_Id(int Orders_Id) {
this.Orders_Id = Orders_Id;
}
#Basic
#Column(name = "Car_Score", nullable = false)
public int getCarScore() {
return carScore;
}
public void setCarScore(int carScore) {
this.carScore = carScore;
}
#Basic
#Column(name = "Rental_Date", nullable = false)
public Date getRentalDate() {
return rentalDate;
}
public void setRentalDate(Date rentalDate) {
this.rentalDate = rentalDate;
}
#Basic
#Column(name = "Return_Date", nullable = false)
public Date getReturnDate() {
return returnDate;
}
public void setReturnDate(Date returnDate) {
this.returnDate = returnDate;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
OrdersArchiveEntity that = (OrdersArchiveEntity) o;
return id == that.id &&
orderScore == that.orderScore &&
carScore == that.carScore && Objects.equals(rentalDate, that.rentalDate) &&
Objects.equals(returnDate, that.returnDate) ;
}
#Override
public int hashCode() {
return Objects.hash(id, orderScore, carScore, rentalDate, returnDate);
}
#ManyToOne
#JoinColumn(name = "id_Base", referencedColumnName = "ID", nullable = false)
public RentalBaseEntity getRentalBaseEntitybyID() {
return RentalBaseEntitybyID;
}
public void setRentalBaseEntitybyID(RentalBaseEntity RentalBaseEntitybyID) {
this.RentalBaseEntitybyID = RentalBaseEntitybyID;
}
#ManyToOne
#JoinColumn(name = "Car_Id", referencedColumnName = "ID", nullable = false)
public CarEntity getCarByCarId() {
return carByCarId;
}
public void setCarByCarId(CarEntity carByCarId) {
this.carByCarId = carByCarId;
}
#ManyToOne
#JoinColumn(name = "Seller_Id", referencedColumnName = "ID")
public SellerEntity getSellerBySellerId() {
return sellerBySellerId;
}
public void setSellerBySellerId(SellerEntity sellerBySellerId) {
this.sellerBySellerId = sellerBySellerId;
}
#ManyToOne
#JoinColumn(name = "Client_Id", referencedColumnName = "ID", nullable = false)
public ClientEntity getClientByClientId() {
return clientByClientId;
}
public void setClientByClientId(ClientEntity clientByClientId) {
this.clientByClientId = clientByClientId;
}
}

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.

Repeated column in mapping for entity error in Spring-MVC project

I connected my MySql database to my Java project (using Spring-MVC) with Entities.
When I try to run the application, I get this error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Repeated column in mapping for entity: com.example.WebAppProcess20.Entities.OrdersitemsEntity column: order_id (should be mapped with insert="false" update="false")
OrdersItems Entity:
package com.example.WebAppProcess20.Entities;
import javax.persistence.*;
import java.util.Objects;
#Entity
#Table(name = "ordersitems", schema = "theprocess", catalog = "")
#IdClass(OrdersitemsEntityPK.class)
public class OrdersitemsEntity {
private String productId;
private String orderId;
private Integer qunatity;
private ProductsEntity productsByProductId;
private OrdersEntity ordersByOrderId;
#Id
#Column(name = "product_id")
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
#Id
#Column(name = "orderId", nullable = false, insertable = false, updatable = false)
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
#Basic
#Column(name = "qunatity")
public Integer getQunatity() {
return qunatity;
}
public void setQunatity(Integer qunatity) {
this.qunatity = qunatity;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
OrdersitemsEntity that = (OrdersitemsEntity) o;
return Objects.equals(productId, that.productId) &&
Objects.equals(orderId, that.orderId) &&
Objects.equals(qunatity, that.qunatity);
}
#Override
public int hashCode() {
return Objects.hash(productId, orderId, qunatity);
}
#ManyToOne
#JoinColumn(name = "product_id", referencedColumnName = "product_id", nullable = false)
public ProductsEntity getProductsByProductId() {
return productsByProductId;
}
public void setProductsByProductId(ProductsEntity productsByProductId) {
this.productsByProductId = productsByProductId;
}
#ManyToOne
#JoinColumn(name = "orderId", referencedColumnName = "orderId", nullable = false)
public OrdersEntity getOrdersByOrderId() {
return ordersByOrderId;
}
public void setOrdersByOrderId(OrdersEntity ordersByOrderId) {
this.ordersByOrderId = ordersByOrderId;
}
}
Orders Entity:
package com.example.WebAppProcess20.Entities;
import javax.persistence.*;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.Objects;
#Entity
#Table(name = "orders", schema = "theprocess", catalog = "")
public class OrdersEntity {
private String orderId;
private String notesFromClient;
private Timestamp orderDate;
private String orderStatus;
private String totalSum;
private ClientsEntity clientsByClientId;
private Collection<OrdersitemsEntity> ordersitemsByOrderId;
#Id
#Column(name = "orderId")
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
#Basic
#Column(name = "notes_from_client")
public String getNotesFromClient() {
return notesFromClient;
}
public void setNotesFromClient(String notesFromClient) {
this.notesFromClient = notesFromClient;
}
#Basic
#Column(name = "order_date")
public Timestamp getOrderDate() {
return orderDate;
}
public void setOrderDate(Timestamp orderDate) {
this.orderDate = orderDate;
}
#Basic
#Column(name = "order_status")
public String getOrderStatus() {
return orderStatus;
}
public void setOrderStatus(String orderStatus) {
this.orderStatus = orderStatus;
}
#Basic
#Column(name = "totalSum")
public String getTotalSum() {
return totalSum;
}
public void setTotalSum(String totalSum) {
this.totalSum = totalSum;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
OrdersEntity that = (OrdersEntity) o;
return Objects.equals(orderId, that.orderId) &&
Objects.equals(notesFromClient, that.notesFromClient) &&
Objects.equals(orderDate, that.orderDate) &&
Objects.equals(orderStatus, that.orderStatus) &&
Objects.equals(totalSum, that.totalSum);
}
#Override
public int hashCode() {
return Objects.hash(orderId, notesFromClient, orderDate, orderStatus, totalSum);
}
#ManyToOne
#JoinColumn(name = "client_id", referencedColumnName = "client_id", nullable = false)
public ClientsEntity getClientsByClientId() {
return clientsByClientId;
}
public void setClientsByClientId(ClientsEntity clientsByClientId) {
this.clientsByClientId = clientsByClientId;
}
#OneToMany(mappedBy = "ordersByOrderId")
public Collection<OrdersitemsEntity> getOrdersitemsByOrderId() {
return ordersitemsByOrderId;
}
public void setOrdersitemsByOrderId(Collection<OrdersitemsEntity> ordersitemsByOrderId) {
this.ordersitemsByOrderId = ordersitemsByOrderId;
}
}
OrdersItemsPK class:
package com.example.WebAppProcess20.Entities;
import javax.persistence.Column;
import javax.persistence.Id;
import java.io.Serializable;
import java.util.Objects;
public class OrdersitemsEntityPK implements Serializable {
private String productId;
private String orderId;
#Column(name = "product_id")
#Id
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
#Column(name = "orderId")
#Id
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
OrdersitemsEntityPK that = (OrdersitemsEntityPK) o;
return Objects.equals(productId, that.productId) &&
Objects.equals(orderId, that.orderId);
}
#Override
public int hashCode() {
return Objects.hash(productId, orderId);
}
}
Products Entity:
package com.example.WebAppProcess20.Entities;
import javax.persistence.*;
import java.util.Collection;
import java.util.Objects;
#Entity
#Table(name = "products", schema = "theprocess", catalog = "")
public class ProductsEntity {
private String productId;
private Integer availableInStock;
private String brand;
private String image;
private Integer price;
private String productCategoryTree;
private String productName;
private Integer rating;
private Collection<OrdersitemsEntity> ordersitemsByProductId;
#Id
#Column(name = "product_id")
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
#Basic
#Column(name = "available_in_stock")
public Integer getAvailableInStock() {
return availableInStock;
}
public void setAvailableInStock(Integer availableInStock) {
this.availableInStock = availableInStock;
}
#Basic
#Column(name = "brand")
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
#Basic
#Column(name = "image")
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
#Basic
#Column(name = "price")
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
#Basic
#Column(name = "product_category_tree")
public String getProductCategoryTree() {
return productCategoryTree;
}
public void setProductCategoryTree(String productCategoryTree) {
this.productCategoryTree = productCategoryTree;
}
#Basic
#Column(name = "product_name")
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
#Basic
#Column(name = "rating")
public Integer getRating() {
return rating;
}
public void setRating(Integer rating) {
this.rating = rating;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ProductsEntity that = (ProductsEntity) o;
return Objects.equals(productId, that.productId) &&
Objects.equals(availableInStock, that.availableInStock) &&
Objects.equals(brand, that.brand) &&
Objects.equals(image, that.image) &&
Objects.equals(price, that.price) &&
Objects.equals(productCategoryTree, that.productCategoryTree) &&
Objects.equals(productName, that.productName) &&
Objects.equals(rating, that.rating);
}
#Override
public int hashCode() {
return Objects.hash(productId, availableInStock, brand, image, price, productCategoryTree, productName, rating);
}
#OneToMany(mappedBy = "productsByProductId")
public Collection<OrdersitemsEntity> getOrdersitemsByProductId() {
return ordersitemsByProductId;
}
public void setOrdersitemsByProductId(Collection<OrdersitemsEntity> ordersitemsByProductId) {
this.ordersitemsByProductId = ordersitemsByProductId;
}
}
Ordersitems connects between Orders and Products - it contains the products of each order, so productId and orderId both foreign keys in Orderitems.
I think I understand the error, if I'm not wrong, the reapeted column error refers to:
#Id
#Column(name = "orderId", nullable = false, insertable = false, updatable = false)
public String getOrderId() {
return orderId;
}
and:
#ManyToOne
#JoinColumn(name = "orderId", referencedColumnName = "orderId", nullable = false)
public OrdersEntity getOrdersByOrderId() {
return ordersByOrderId;
}
public void setOrdersByOrderId(OrdersEntity ordersByOrderId) {
this.ordersByOrderId = ordersByOrderId;
}
But whatever I tried to do didn't solve the problem or even added other errors.
Can you please help me to solve this problem?
Thanks!

HIbernate - JPA: foreign key not set in ManyToOne relationship

I know this might be a common problem but so far I couldn't find any solution.
I have the following 2 entities: Mission and Representation. Both entities have composed primary keys, respectively:
MissionId [idImpXml, code, categorie]
RepresentationId [idImpXml, codeRepresentation]
There's a one-to-many relationship between Representation and Mission, meaning that each mission has a single representation and each representation can be used in different missions.
I use JPA repositories to persist the entities in my database:
public interface RepresentationDao extends JpaRepository <Representation, RepresentationId>
public interface MissionDao extends JpaRepository <Mission, MissionId>
I need to save first a set of representations, and THEN a set of missions.
The representations work correctly, but when I try to save a mission the foreign key to the representation remains empty.
This is my code:
// here representations are already persisted (in a separate transaction)..
RepresentationId representationId = new RepresentationId(idImpXml, codeRepresentation);
Representation representation = representationDao.findOne(representationId);
// representation is retrieved correctly
MissionId missionId = new MissionId(idImpXml, code, categorie);
Mission mission = new Mission(missionId, representation, label);
// I try to save the mission
missionDao.saveAndFlush(mission);
// THE FOREIGN KEY THAT SHOULD REFERENCE THE REPRESENTATION (CODE_REPRESENTATION) REMAINS NULL
Mission
#Entity
#Table(name = "MISSION", schema = "dbo", catalog ="TEST")
public class Mission implements java.io.Serializable {
private MissionId id;
private Representation representation;
private String label;
public Mission() {
}
public Mission(MissionId id, Representation representation, String label) {
this.id = id;
this.representation = representation;
this.label = label;
}
#EmbeddedId
#AttributeOverrides({
#AttributeOverride(name = "idImpXml", column = #Column(name = "ID_IMP_XML", nullable = false, precision = 38, scale = 0)),
#AttributeOverride(name = "code", column = #Column(name = "CODE", nullable = false)),
#AttributeOverride(name = "categorie", column = #Column(name = "CATEGORIE", nullable = false)) })
public MissionId getId() {
return this.id;
}
public void setId(MissionId id) {
this.id = id;
}
#MapsId("ID_IMP_XML")
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumns(
value={ #JoinColumn(name = "ID_IMP_XML", referencedColumnName = "ID_IMP_XML", updatable=false),
#JoinColumn(name = "CODE_REPRESENTATION", referencedColumnName = "CODE_REPRESENTATION", insertable=true, updatable=true)
})
public Representation getRepresentation() {
return this.representation;
}
public void setRepresentation(Representation representation) {
this.representation = representation;
}
#Column(name = "LABEL", nullable = false)
public String getLabel() {
return this.label;
}
public void setLabel(String label) {
this.label = label;
}
}
MissionId
#Embeddable
public class MissionId implements java.io.Serializable {
private Long idImpXml;
private String code;
private int categorie;
public MissionId() {
}
public MissionId(Long idImpXml, String code, int categorie) {
this.idImpXml = idImpXml;
this.code = code;
this.categorie = categorie;
}
#Column(name = "ID_IMP_XML", nullable = false, precision = 38, scale = 0)
public Long getIdImpXml() {
return this.idImpXml;
}
public void setIdImpXml(Long idImpXml) {
this.idImpXml = idImpXml;
}
#Column(name = "CODE", nullable = false)
public String getCode() {
return this.code;
}
public void setCode(String code) {
this.code = code;
}
#Column(name = "CATEGORIE", nullable = false)
public int getCategorie() {
return this.categorie;
}
public void setCategorie(int categorie) {
this.categorie = categorie;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof MissionId))
return false;
MissionId castOther = (MissionId) other;
return ((this.getIdImpXml() == castOther.getIdImpXml()) || (this.getIdImpXml() != null
&& castOther.getIdImpXml() != null && this.getIdImpXml().equals(castOther.getIdImpXml())))
&& ((this.getCode() == castOther.getCode()) || (this.getCode() != null && castOther.getCode() != null
&& this.getCode().equals(castOther.getCode())))
&& (this.getCategorie() == castOther.getCategorie());
}
public int hashCode() {
int result = 17;
result = 37 * result + (getIdImpXml() == null ? 0 : this.getIdImpXml().hashCode());
result = 37 * result + (getCode() == null ? 0 : this.getCode().hashCode());
result = 37 * result + this.getCategorie();
return result;
}
}
Representation
#Entity
#Table(name = "REPRESENTATION", schema = "dbo", catalog ="TEST")
public class Representation implements Serializable {
private RepresentationId id;
private Long colorPattern;
private String typePattern;
private Integer thickness;
public Representation() {
}
public Representation(RepresentationId id) {
this.id = id;
}
public Representation(RepresentationId id, Long colorPattern, String typePattern,
Integer thickness, Long codeCouleurPattern2, String typePattern2, Integer epaisseurPattern2) {
this.id = id;
this.colorPattern = colorPattern;
this.typePattern = typePattern;
this.thickness = thickness;
}
#EmbeddedId
#AttributeOverrides({
#AttributeOverride(name = "idImpXml", column = #Column(name = "ID_IMP_XML", nullable = false, precision = 38, scale = 0)),
#AttributeOverride(name = "codeRepresentation", column = #Column(name = "CODE_REPRESENTATION", nullable = false)) })
public RepresentationId getId() {
return this.id;
}
public void setId(RepresentationId id) {
this.id = id;
}
#Column(name = "COLOR_PATTERN")
public Long getColorPattern() {
return this.colorPattern;
}
public void setColorPattern(Long colorPattern) {
this.colorPattern = colorPattern;
}
#Column(name = "TYPE_PATTERN")
public String getTypePattern() {
return this.typePattern;
}
public void setTypePattern(String typePattern) {
this.typePattern = typePattern;
}
#Column(name = "THICKNESS")
public Integer getThickness() {
return this.thickness;
}
public void setThickness(Integer thickness) {
this.thickness = thickness;
}
}
RepresentationId
#Embeddable
public class RepresentationId implements java.io.Serializable {
private Long idImpXml;
private int codeRepresentation;
public RepresentationId() {
}
public RepresentationId(Long idImpXml, int codeRepresentation) {
this.idImpXml = idImpXml;
this.codeRepresentation = codeRepresentation;
}
#Column(name = "ID_IMP_XML", nullable = false, precision = 38, scale = 0)
public Long getIdImpXml() {
return this.idImpXml;
}
public void setIdImpXml(Long idImpXml) {
this.idImpXml = idImpXml;
}
#Column(name = "CODE_REPRESENTATION", nullable = false)
public int getCodeRepresentation() {
return this.codeRepresentation;
}
public void setCodeRepresentation(int codeRepresentation) {
this.codeRepresentation = codeRepresentation;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof RepresentationId))
return false;
RepresentationId castOther = (RepresentationId) other;
return ((this.getIdImpXml() == castOther.getIdImpXml()) || (this.getIdImpXml() != null
&& castOther.getIdImpXml() != null && this.getIdImpXml().equals(castOther.getIdImpXml())))
&& (this.getCodeRepresentation() == castOther.getCodeRepresentation());
}
public int hashCode() {
int result = 17;
result = 37 * result + (getIdImpXml() == null ? 0 : this.getIdImpXml().hashCode());
result = 37 * result + this.getCodeRepresentation();
return result;
}
}
try to override column definition by adding another field in your object and set the insertable and updatable properties to false in the #JoinColum, like this:
#MapsId("ID_IMP_XML")
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumns(
value={ #JoinColumn(name = "ID_IMP_XML", referencedColumnName = "ID_IMP_XML", insertable=false, updatable=false),
#JoinColumn(name = "CODE_REPRESENTATION", referencedColumnName = "CODE_REPRESENTATION", insertable=false, updatable=false)
})
public Representation getRepresentation() {
return this.representation;
}
private Integer representationCode;
#Column(name = "CODE_REPRESENTATION")
public Integer getRepresentationCode() {
return this.representationCode;
}

hibernate onetomany annotation fetch = FetchType.LAZY didn't work

I have three tables A,B and C. Table B has a foreign key a_id reference to table A, Table B has a foreign key a_id reference to table A. And my hibernate entity files are as following:
A.java
#Entity
#Table(name = "A")
public class A {
private long id;
private String contentA;
private List<B> bList;
private List<C> cList;
#OneToMany(fetch = FetchType.EAGER , mappedBy = "b")
public List<B> getbList() {
return bList;
}
public void setbList(List<B> bList) {
this.bList = bList;
}
#OneToMany(fetch = FetchType.EAGER , mappedBy = "b")
public List<C> getcList() {
return cList;
}
public void setcList(List<C> cList) {
this.cList = cList;
}
#Id
#Column(name = "id", nullable = false)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
#Basic
#Column(name = "content_a", nullable = false, length = 1000)
public String getContentA() {
return contentA;
}
public void setContentA(String contentA) {
this.contentA = contentA;
}
}
B.java
#Entity
#Table(name = "B")
public class B {
private long id;
private String contentB;
private A a;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "a_id", nullable = false)
public A getA() {
return a;
}
public void setA(A a) {
this.a = a;
}
#Id
#Column(name = "id", nullable = false)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
#Basic
#Column(name = "content_b", nullable = false, length = 1000)
public String getContentB() {
return contentB;
}
public void setContentB(String contentB) {
this.contentB = contentB;
}
}
C.java
#Entity
#Table(name = "C")
public class C {
private long id;
private String contentC;
private A a;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "a_id", nullable = false)
public A getA() {
return a;
}
public void setA(A a) {
this.a = a;
}
#Id
#Column(name = "id", nullable = false)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
#Basic
#Column(name = "content_c", nullable = false, length = 1000)
public String getContentC() {
return contentC;
}
public void setContentC(String contentC) {
this.contentC = contentC;
}
}
the problem is sometimes I just want to get A with List<B>, in another time I want to get A with List<C>. Is there any way I can do this by hibernate?
------------------------divide line----------------------
In my real project, I have three entity class: ChapterEntity ChapterTitle1Entity ChapterTitle2Entity ChapterTitle3Entity. There is a private List<ChapterTitle1Entity> chapterTitle1EntityList; in ChapterEntity, also private List<ChapterTitle2Entity> chapterTitle2EntityList; in ChapterTitle2Entity, private List<ChapterTitle3Entity> chapterTitle3EntityList; in ChapterTitle2Entity.
I just want to get a list of ChapterEntity with sublist List<ChapterTitle1Entity> chapterTitle1EntityList, the lazy load annotation didn't work. the following are my class files
ChapterEntity.java
package com.hnu.tutorial.model.entity;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import javax.persistence.*;
import java.util.List;
/**
* Created by shiqin_zhang#qq.com on 2016-09-9/6/16
* Time 11:16 PM
*/
#Entity
#Table(name = "chapter")
public class ChapterEntity {
private List<ChapterTitle1Entity> chapterTitle1EntityList;
private long id;
private int sequence;
private String content;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "chapterEntity")
#Fetch(FetchMode.SUBSELECT)
public List<ChapterTitle1Entity> getChapterTitle1EntityList() {
return chapterTitle1EntityList;
}
public void setChapterTitle1EntityList(List<ChapterTitle1Entity> chapterTitle1EntityList) {
this.chapterTitle1EntityList = chapterTitle1EntityList;
}
#Id
#Column(name = "id", nullable = false)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
#Basic
#Column(name = "sequence", nullable = false)
public int getSequence() {
return sequence;
}
public void setSequence(int sequence) {
this.sequence = sequence;
}
#Basic
#Column(name = "content", nullable = false, length = 1000)
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ChapterEntity that = (ChapterEntity) o;
if (id != that.id) return false;
if (sequence != that.sequence) return false;
if (content != null ? !content.equals(that.content) : that.content != null) return false;
return true;
}
#Override
public int hashCode() {
int result = (int) (id ^ (id >>> 32));
result = 31 * result + sequence;
result = 31 * result + (content != null ? content.hashCode() : 0);
return result;
}
}
ChapterTitle1Entity.java
package com.hnu.tutorial.model.entity;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import javax.persistence.*;
import java.util.List;
/**
* Created by shiqin_zhang#qq.com on 2016-09-11
* Time 6:09 PM
*/
#Entity
#Table(name = "chapter_title_1", schema = "tutorial2")
public class ChapterTitle1Entity {
private long id;
private int sequence;
private String content;
// private long chapterId;
/**
* 1:章前测试,2:实际的测试
*/
private int type;
private ChapterEntity chapterEntity;
private List<ChapterTitle2Entity> chapterTitle2EntityList;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "chapterTitle1Entity")
#Fetch(FetchMode.SUBSELECT)
public List<ChapterTitle2Entity> getChapterTitle2EntityList() {
return chapterTitle2EntityList;
}
public void setChapterTitle2EntityList(List<ChapterTitle2Entity> chapterTitle2EntityList) {
this.chapterTitle2EntityList = chapterTitle2EntityList;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "chapter_id", nullable = false)
public ChapterEntity getChapterEntity() {
return chapterEntity;
}
public void setChapterEntity(ChapterEntity chapterEntity) {
this.chapterEntity = chapterEntity;
}
#Id
#Column(name = "id", nullable = false)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
#Basic
#Column(name = "sequence", nullable = false)
public int getSequence() {
return sequence;
}
public void setSequence(int sequence) {
this.sequence = sequence;
}
#Basic
#Column(name = "content", nullable = false, length = 1000)
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
/*
#Basic
#Column(name = "chapter_id", nullable = false)
public long getChapterId() {
return chapterId;
}
public void setChapterId(long chapterId) {
this.chapterId = chapterId;
}
*/
#Basic
#Column(name = "type", nullable = false)
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ChapterTitle1Entity that = (ChapterTitle1Entity) o;
if (id != that.id) return false;
if (sequence != that.sequence) return false;
// if (chapterId != that.chapterId) return false;
if (type != that.type) return false;
if (content != null ? !content.equals(that.content) : that.content != null) return false;
return true;
}
#Override
public int hashCode() {
int result = (int) (id ^ (id >>> 32));
result = 31 * result + sequence;
result = 31 * result + (content != null ? content.hashCode() : 0);
// result = 31 * result + (int) (chapterId ^ (chapterId >>> 32));
result = 31 * result + type;
return result;
}
}
ChapterTitle2Entity.java
package com.hnu.tutorial.model.entity;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import javax.persistence.*;
import java.util.List;
/**
* Created by shiqin_zhang#qq.com on 2016-09-9/6/16
* Time 11:16 PM
*/
#Entity
#Table(name = "chapter_title_2")
public class ChapterTitle2Entity {
private long id;
private int sequence;
private String content;
// private long title1Id;
private List<ChapterTitle3Entity> chapterTitle3EntityList;
private ChapterTitle1Entity chapterTitle1Entity;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "title_1_id", nullable = false)
public ChapterTitle1Entity getChapterTitle1Entity() {
return chapterTitle1Entity;
}
public void setChapterTitle1Entity(ChapterTitle1Entity chapterTitle1Entity) {
this.chapterTitle1Entity = chapterTitle1Entity;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "chapterTitle2Entity")
#Fetch(FetchMode.SUBSELECT)
public List<ChapterTitle3Entity> getChapterTitle3EntityList() {
return chapterTitle3EntityList;
}
public void setChapterTitle3EntityList(List<ChapterTitle3Entity> chapterTitle3EntityList) {
this.chapterTitle3EntityList = chapterTitle3EntityList;
}
#Id
#Column(name = "id", nullable = false)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
#Basic
#Column(name = "sequence", nullable = false)
public int getSequence() {
return sequence;
}
public void setSequence(int sequence) {
this.sequence = sequence;
}
#Basic
#Column(name = "content", nullable = false, length = 1000)
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
/*
#Basic
#Column(name = "title_1_id", nullable = false)
public long getTitle1Id() {
return title1Id;
}
public void setTitle1Id(long title1Id) {
this.title1Id = title1Id;
}
*/
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ChapterTitle2Entity that = (ChapterTitle2Entity) o;
if (id != that.id) return false;
if (sequence != that.sequence) return false;
// if (title1Id != that.title1Id) return false;
if (content != null ? !content.equals(that.content) : that.content != null) return false;
return true;
}
#Override
public int hashCode() {
int result = (int) (id ^ (id >>> 32));
result = 31 * result + sequence;
result = 31 * result + (content != null ? content.hashCode() : 0);
// result = 31 * result + (int) (title1Id ^ (title1Id >>> 32));
return result;
}
}
ChapterTitle3Entity.java
package com.hnu.tutorial.model.entity;
import javax.persistence.*;
/**
* Created by shiqin_zhang#qq.com on 2016-09-9/6/16
* Time 11:16 PM
*/
#Entity
#Table(name = "chapter_title_3")
public class ChapterTitle3Entity {
private long id;
private int sequence;
private String content;
// private long title2Id;
private ChapterTitle2Entity chapterTitle2Entity;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "title_2_id", nullable = false)
public ChapterTitle2Entity getChapterTitle2Entity() {
return chapterTitle2Entity;
}
public void setChapterTitle2Entity(ChapterTitle2Entity chapterTitle2Entity) {
this.chapterTitle2Entity = chapterTitle2Entity;
}
#Id
#Column(name = "id", nullable = false)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
#Basic
#Column(name = "sequence", nullable = false)
public int getSequence() {
return sequence;
}
public void setSequence(int sequence) {
this.sequence = sequence;
}
#Basic
#Column(name = "content", nullable = false, length = 1000)
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
/*
#Basic
#Column(name = "title_2_id", nullable = false)
public long getTitle2Id() {
return title2Id;
}
public void setTitle2Id(long title2Id) {
this.title2Id = title2Id;
}
*/
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ChapterTitle3Entity that = (ChapterTitle3Entity) o;
if (id != that.id) return false;
if (sequence != that.sequence) return false;
if (content != null ? !content.equals(that.content) : that.content != null) return false;
return true;
}
#Override
public int hashCode() {
int result = (int) (id ^ (id >>> 32));
result = 31 * result + sequence;
result = 31 * result + (content != null ? content.hashCode() : 0);
return result;
}
}
my DAO layer ChapterDAO.java
package com.hnu.tutorial.model.dao;
import com.hnu.tutorial.model.entity.ChapterEntity;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Created by shiqin_zhang#qq.com on 2016-09-9
* Time 11:13 PM
*/
#Repository
public class ChapterDAO extends BaseDAO<ChapterEntity> {
public List<ChapterEntity> chapterEntityList(){
Criteria criteria = session().createCriteria(ChapterEntity.class, "chapter");
criteria.createAlias("chapter.chapterTitle1EntityList", "title1List");
criteria.addOrder(Order.desc("title1List.sequence"));
List<ChapterEntity> chapterEntityList = criteria.list();
return chapterEntityList;
/*String hql = "from ChapterEntity";
List<ChapterEntity> chapterEntityList = session().createQuery(hql).list();
return chapterEntityList;*/
}
}
my service layer ChapterSvc
package com.hnu.tutorial.service.impl;
import com.hnu.tutorial.model.dao.ChapterDAO;
import com.hnu.tutorial.model.entity.ChapterEntity;
import com.hnu.tutorial.model.entity.ChapterTitle1Entity;
import com.hnu.tutorial.service.dto.ChapterDTO;
import com.hnu.tutorial.service.dto.ChapterTitle1DTO;
import com.hnu.tutorial.service.interfaces.IChapterSvc;
import com.hnu.tutorial.utils.BeanMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* Created by shiqin_zhang#qq.com on 2016-09-10
* Time 10:59 AM
*/
#Service
#Transactional
public class ChapterSvc implements IChapterSvc {
#Autowired
private ChapterDAO chapterDAO;
#Override
public List<ChapterDTO> chapterDTOList() {
List<ChapterEntity> chapterEntityList = chapterDAO.chapterEntityList();
List<ChapterDTO> chapterDTOList = BeanMap.mapList(chapterEntityList, ChapterDTO.class);
for(ChapterDTO chapterDTO:chapterDTOList){
List<ChapterTitle1Entity> chapterTitle1EntityList = chapterDTO.getChapterTitle1EntityList();
for (ChapterTitle1Entity chapterTitle1Entity:chapterTitle1EntityList){
chapterTitle1Entity.setChapterEntity(null);
}
}
return chapterDTOList;
}
}
Each time when I query the chapter list, I get all the sub list. Even when I set a breakpoint in the end of method chapterEntityList() of my service layer, I also get all the sub list. I also tried query a list use hql, but it still didn't work.
Change FetchType.EAGER to FetchType.LAZY in your #OneToMany annotations. This will casue Hibernate to load a collection only when you directly refer to it.

persisting a many to many relationship using hibernate and seam

i have a program that communicates with an existing database. There is a composite table that has an employee and a vehicle as its composite key. On the edit or add employee page, their is a dropdown box to select which vehicles the employee prefers and then stores the vehicle list in a hashtable in the employee class. However, the list will not persist, or store, in the composite table. I am new to seam and have spent all day trying to figure this out. Any help would be appreciated.
Here are some of my classes:
Employee:
#Entity
#Table(name = "flower_store_employee", schema = "dbo", catalog = "tyler")
public class FlowerStoreEmployee implements java.io.Serializable, Comparable<FlowerStoreEmployee> {
/**
*
*/
private static final long serialVersionUID = -1727355085366851150L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "employee_id", unique = true, nullable = false)
private Integer employeeId;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "address_id")
private FlowerStoreAddress flowerStoreAddress;
#Column(name = "name_first", length = 25)
#Length(max = 25)
private String nameFirst;
#Column(name = "name_last", length = 25)
#Length(max = 25)
private String nameLast;
#Column(name = "ssn")
private String ssn;
#Column(name = "phone")
private String phone;
#Column(name = "pay")
private int pay;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "flowerStoreEmployee")
private Set<FlowerStoreDelivery> flowerStoreDeliveries = new HashSet<FlowerStoreDelivery>(
0);
#Cascade({org.hibernate.annotations.CascadeType.ALL })
#ManyToMany(fetch = FetchType.LAZY, mappedBy = "flowerStoreEmployees")
//#JoinTable(name = "flower_store_emp_vehicle", schema = "dbo", catalog = "tyler", joinColumns = { #JoinColumn(name = "vehicle_id", nullable = false, updatable = true) }, inverseJoinColumns = { #JoinColumn(name = "employee_id", nullable = false, updatable = true) })
private Set<FlowerStoreVehicle> flowerStoreVehicles = new HashSet<FlowerStoreVehicle>(
0);
public FlowerStoreEmployee() {
}
public FlowerStoreEmployee(int employeeId) {
this.employeeId = employeeId;
}
public FlowerStoreEmployee(FlowerStoreAddress flowerStoreAddress, String nameFirst,
String nameLast, String ssn, String phone, int pay,
Set<FlowerStoreDelivery> flowerStoreDeliveries,
Set<FlowerStoreVehicle> flowerStoreVehicles) {
this.employeeId = employeeId;
this.flowerStoreAddress = flowerStoreAddress;
this.nameFirst = nameFirst;
this.nameLast = nameLast;
this.ssn = ssn;
this.phone = phone;
this.pay = pay;
this.flowerStoreDeliveries = flowerStoreDeliveries;
this.flowerStoreVehicles = flowerStoreVehicles;
}
public int getEmployeeId() {
return this.employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public FlowerStoreAddress getFlowerStoreAddress() {
return this.flowerStoreAddress;
}
public void setFlowerStoreAddress(FlowerStoreAddress flowerStoreAddress) {
this.flowerStoreAddress = flowerStoreAddress;
}
public String getNameFirst() {
return this.nameFirst;
}
public void setNameFirst(String nameFirst) {
this.nameFirst = nameFirst;
}
public String getNameLast() {
return this.nameLast;
}
public void setNameLast(String nameLast) {
this.nameLast = nameLast;
}
public String getSsn() {
return this.ssn;
}
public void setSsn(String ssn) {
this.ssn = ssn;
}
public String getPhone() {
return this.phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public int getPay() {
return this.pay;
}
public void setPay(int pay) {
this.pay = pay;
}
public void setPay(String pay){
this.pay = Integer.parseInt(pay);
}
public Set<FlowerStoreDelivery> getFlowerStoreDeliveries() {
return this.flowerStoreDeliveries;
}
public void setFlowerStoreDeliveries(
Set<FlowerStoreDelivery> flowerStoreDeliveries) {
this.flowerStoreDeliveries = flowerStoreDeliveries;
}
public Set<FlowerStoreVehicle> getFlowerStoreVehicles() {
return this.flowerStoreVehicles;
}
public void setFlowerStoreVehicles(
Set<FlowerStoreVehicle> flowerStoreVehicles) {
this.flowerStoreVehicles = flowerStoreVehicles;
}
public int compareTo(FlowerStoreEmployee emp) {
if(this.employeeId > emp.employeeId){
return 1;
}
else
if(this.employeeId < emp.employeeId){
return -1;
}
else{
return 0;
}
}
Vehicle:
#Entity
#Table(name = "flower_store_vehicle", schema = "dbo", catalog = "tyler")
public class FlowerStoreVehicle implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 5349431404739349258L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "vehicle_id", unique = true, nullable = false)
private int vehicleId;
#Column(name = "vin", length = 17)
#Length(max = 17)
private String vin;
#Column(name = "license", length = 10)
#Length(max = 10)
private String license;
#Column(name = "make", length = 15)
#Length(max = 15)
private String make;
#Column(name = "model", length = 20)
#Length(max = 20)
private String model;
#Column(name = "color", length = 20)
#Length(max = 20)
private String color;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "flowerStoreVehicle")
private Set<FlowerStoreDelivery> flowerStoreDeliveries = new HashSet<FlowerStoreDelivery>(
0);
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable(name = "flower_store_emp_vehicle", schema = "dbo", catalog = "tyler", joinColumns = { #JoinColumn(name = "vehicle_id", nullable = false, updatable = false) }, inverseJoinColumns = { #JoinColumn(name = "employee_id", nullable = false, updatable = false) })
private Set<FlowerStoreEmployee> flowerStoreEmployees = new HashSet<FlowerStoreEmployee>(
0);
public FlowerStoreVehicle() {
}
public FlowerStoreVehicle(int vehicleId) {
this.vehicleId = vehicleId;
}
public FlowerStoreVehicle(int vehicleId, String vin, String license,
String make, String model, String color,
Set<FlowerStoreDelivery> flowerStoreDeliveries,
Set<FlowerStoreEmployee> flowerStoreEmployees) {
this.vehicleId = vehicleId;
this.vin = vin;
this.license = license;
this.make = make;
this.model = model;
this.color = color;
this.flowerStoreDeliveries = flowerStoreDeliveries;
this.flowerStoreEmployees = flowerStoreEmployees;
}
public int getVehicleId() {
return this.vehicleId;
}
public void setVehicleId(int vehicleId) {
this.vehicleId = vehicleId;
}
public String getVin() {
return this.vin;
}
public void setVin(String vin) {
this.vin = vin;
}
public String getLicense() {
return this.license;
}
public void setLicense(String license) {
this.license = license;
}
public String getMake() {
return this.make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return this.model;
}
public void setModel(String model) {
this.model = model;
}
public String getColor() {
return this.color;
}
public void setColor(String color) {
this.color = color;
}
public Set<FlowerStoreDelivery> getFlowerStoreDeliveries() {
return this.flowerStoreDeliveries;
}
public void setFlowerStoreDeliveries(
Set<FlowerStoreDelivery> flowerStoreDeliveries) {
this.flowerStoreDeliveries = flowerStoreDeliveries;
}
public Set<FlowerStoreEmployee> getFlowerStoreEmployees() {
return this.flowerStoreEmployees;
}
public void setFlowerStoreEmployees(
Set<FlowerStoreEmployee> flowerStoreEmployees) {
this.flowerStoreEmployees = flowerStoreEmployees;
}
}
CompositeTableID:
/**
* FlowerStoreEmpVehicleId generated by hbm2java
*/
#Embeddable
public class FlowerStoreEmpVehicleId implements java.io.Serializable {
private int vehicleId;
private int employeeId;
public FlowerStoreEmpVehicleId() {
}
public FlowerStoreEmpVehicleId(int vehicleId, int employeeId) {
this.vehicleId = vehicleId;
this.employeeId = employeeId;
}
#Column(name = "vehicle_id", nullable = false)
public int getVehicleId() {
return this.vehicleId;
}
public void setVehicleId(int vehicleId) {
this.vehicleId = vehicleId;
}
#Column(name = "employee_id", nullable = false)
public int getEmployeeId() {
return this.employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof FlowerStoreEmpVehicleId))
return false;
FlowerStoreEmpVehicleId castOther = (FlowerStoreEmpVehicleId) other;
return (this.getVehicleId() == castOther.getVehicleId())
&& (this.getEmployeeId() == castOther.getEmployeeId());
}
public int hashCode() {
int result = 17;
result = 37 * result + this.getVehicleId();
result = 37 * result + this.getEmployeeId();
return result;
}
}
CompositeTable:
#Entity
#Table(name = "flower_store_emp_vehicle", schema = "dbo", catalog = "tyler")
public class FlowerStoreEmpVehicle implements java.io.Serializable {
private FlowerStoreEmpVehicleId id;
public FlowerStoreEmpVehicle() {
}
public FlowerStoreEmpVehicle(FlowerStoreEmpVehicleId id) {
this.id = id;
}
#EmbeddedId
#AttributeOverrides({
#AttributeOverride(name = "vehicleId", column = #Column(name = "vehicle_id", nullable = false)),
#AttributeOverride(name = "employeeId", column = #Column(name = "employee_id", nullable = false)) })
#NotNull
public FlowerStoreEmpVehicleId getId() {
return this.id;
}
public void setId(FlowerStoreEmpVehicleId id) {
this.id = id;
}
}
and here is the code to save the employee:
public String addEmployee(){
Set<FlowerStoreVehicle> vehicleSet = new HashSet<FlowerStoreVehicle>();
FlowerStoreEmployee n = new FlowerStoreEmployee();
if(first!=null && first!=""){
n.setNameFirst(first);
}
if(last!=null && last!=""){
n.setNameLast(last);
}
if(pay!=null && pay!=""){
int intPay = (int)(Double.parseDouble(pay)*100);
n.setPay(intPay);
}
if(phone!=null && phone!=""){
n.setPhone(phone);
}
if(ssn!=null && ssn!=""){
n.setSsn(ssn);
}
if(vehicle!=null && vehicle!=""){
String[] vehStr = vehicle.split(" ");
for(int i = 0; i < vehStr.length; i++){
int vehId = Integer.parseInt(vehStr[i]);
vehicleSet.add(entityManager.find(FlowerStoreVehicle.class, vehId));
}
}
if(!vehicleSet.isEmpty()){
n.setFlowerStoreVehicles(vehicleSet);
}
entityManager.persist(n);
if(zip!=null && zip!=""){
FlowerStoreZip zipCode = entityManager.find(FlowerStoreZip.class, Integer.parseInt(zip));
if(zipCode==null){
zipCode = new FlowerStoreZip();
if(zip!=null && zip!=""){
zipCode.setZipCode(Integer.parseInt(zip));
}
if(city!=null && city!=""){
zipCode.setCity(city);
}
if(state!=null && city!=""){
zipCode.setState(state);
}
entityManager.persist(zipCode);
}
}
FlowerStoreAddress add = new FlowerStoreAddress();
if(house!=null && house!=""){
add.setHouseNumber(Integer.parseInt(house));
}
if(street!=null && street!=""){
add.setStreet(street);
}
if(zip!=null && zip!=""){
add.setFlowerStoreZip(entityManager.find(FlowerStoreZip.class, Integer.parseInt(zip)));
}
return "/employee.xhtml";
}
If any more info is needed please let me know. Any help will be greatly appreciated. thank you
First of all, check your code, you have a lot of buggy instructions: in Java you compare Strings with the equals() method, not like this: ssn != "".
The root of your problem is not Seam itself but Hibernate. First of all, add elements to the vehicle set via n.getFlowerStoreVehicles().add(...), don't reassign the entire set with n.setFlowerStoreVehicles(...) (this is probably not a problem during entity creation but becomes a problem when modifying the set after the entities are persisted.
The reason for the relationship not being correctly persisted is that FlowerStoreEmployee is the "weak" side of the relationship (the one with the "mappedBy" attribute in the annotation). Move the #JoinTable annotation to the FlowerStoreEmployee class and remove it from FlowerStoreVehicle, remove the mappedBy from FlowerStoreEmployee and put it in the FlowerStoreVehicle (mappedBy="flowerStoreVehicles"). Since the relationship is bi-directional, assign to both sides of the relationship:
FlowerStoreVehicle veh = entityManager.find(FlowerStoreVehicle.class, vehId);
veh.getFlowerStoreEmployees().add(n); // one direction: vehicle -> employee
n.getFlowerStoreVehicles().add(veh); // the other direction: employee -> vehicle
There is no entityManager.persist at the end of your code, apart from persisting the ZipCode no Object is persisted.

Categories

Resources