persisting a many to many relationship using hibernate and seam - java

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.

Related

TableView not showing values when using two Objects JAVAFX with Hibernate

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

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.

Persisting a table with foreign keys using EJB and JPA

I am new to JavaEE and I am having a problem with persisting a table that has foreign keys pointing to the primary key of another table using entity classes and ejb's entity manager. I am using Netbeans.
I have an entity called 'property' and have another entity called 'offer' which holds the foreign key pointing to the primary key of the property. So basically, the logic is that one property can have many offers. Therefore, I am trying to add new offers in the 'offer' table using the entity manager but I am not being able to do it. You can look at the code and see what I maybe missing.
Property entity:
#Entity
#Table(name = "PROPERTY")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Property.findAll", query = "SELECT p FROM Property p")})
public class Property implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "PROPERTYID")
private Integer propertyid;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 500)
#Column(name = "DESCRIPTION")
private String description;
#Size(max = 50)
#Column(name = "TYPE")
private String type;
#Column(name = "NUMBEROFBEDROOM")
private Integer numberofbedroom;
#Column(name = "NUMBEROFBATHROOM")
private Integer numberofbathroom;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 10)
#Column(name = "ISFURNISHED")
private String isfurnished;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 10)
#Column(name = "HASGARDEN")
private String hasgarden;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 20)
#Column(name = "SIZE")
private String size;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 100)
#Column(name = "PRICE")
private String price;
#Basic(optional = false)
#NotNull
#Column(name = "ENTEREDDATE")
#Temporal(TemporalType.DATE)
private Date entereddate;
#Basic(optional = false)
#NotNull
#Column(name = "ENTEREDTIME")
#Temporal(TemporalType.TIME)
private Date enteredtime;
#OneToOne(cascade = CascadeType.ALL, mappedBy = "property")
private Paddress paddress;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "propertyid")
private Collection<Offer> offerCollection;
#JoinColumn(name = "PROPERTYOWNERID", referencedColumnName = "PROPERTYOWNERID")
#ManyToOne(optional = false)
private Propertyowner propertyownerid;
#JoinColumn(name = "REALESTATEAGENTID", referencedColumnName = "REALESTATEAGENTID")
#ManyToOne(optional = false)
private Realestateagent realestateagentid;
public Property() {
}
public Property(Integer propertyid) {
this.propertyid = propertyid;
}
public Property(Integer propertyid, String description, String isfurnished, String hasgarden, String size, String price, Date entereddate, Date enteredtime) {
this.propertyid = propertyid;
this.description = description;
this.isfurnished = isfurnished;
this.hasgarden = hasgarden;
this.size = size;
this.price = price;
this.entereddate = entereddate;
this.enteredtime = enteredtime;
}
public Integer getPropertyid() {
return propertyid;
}
public void setPropertyid(Integer propertyid) {
this.propertyid = propertyid;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Integer getNumberofbedroom() {
return numberofbedroom;
}
public void setNumberofbedroom(Integer numberofbedroom) {
this.numberofbedroom = numberofbedroom;
}
public Integer getNumberofbathroom() {
return numberofbathroom;
}
public void setNumberofbathroom(Integer numberofbathroom) {
this.numberofbathroom = numberofbathroom;
}
public String getIsfurnished() {
return isfurnished;
}
public void setIsfurnished(String isfurnished) {
this.isfurnished = isfurnished;
}
public String getHasgarden() {
return hasgarden;
}
public void setHasgarden(String hasgarden) {
this.hasgarden = hasgarden;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public Date getEntereddate() {
return entereddate;
}
public void setEntereddate(Date entereddate) {
this.entereddate = entereddate;
}
public Date getEnteredtime() {
return enteredtime;
}
public void setEnteredtime(Date enteredtime) {
this.enteredtime = enteredtime;
}
public Paddress getPaddress() {
return paddress;
}
public void setPaddress(Paddress paddress) {
this.paddress = paddress;
}
#XmlTransient
public Collection<Offer> getOfferCollection() {
return offerCollection;
}
public void setOfferCollection(Collection<Offer> offerCollection) {
this.offerCollection = offerCollection;
}
public Propertyowner getPropertyownerid() {
return propertyownerid;
}
public void setPropertyownerid(Propertyowner propertyownerid) {
this.propertyownerid = propertyownerid;
}
public Realestateagent getRealestateagentid() {
return realestateagentid;
}
public void setRealestateagentid(Realestateagent realestateagentid) {
this.realestateagentid = realestateagentid;
}
public String dateToString()
{
DateFormat df = new SimpleDateFormat("dd/MM/yy");
return df.format(entereddate);
}
public String timeToString()
{
DateFormat df = new SimpleDateFormat("HH:mm:ss");
return df.format(enteredtime);
}
#Override
public int hashCode() {
int hash = 0;
hash += (propertyid != null ? propertyid.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Property)) {
return false;
}
Property other = (Property) object;
if ((this.propertyid == null && other.propertyid != null) || (this.propertyid != null && !this.propertyid.equals(other.propertyid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.sushan.model.Property[ propertyid=" + propertyid + " ]";
}
}
EJB PropertyDAO:
#Stateless
public class PropertyDAO implements PropertyDAOLocal {
#PersistenceContext(unitName="RealEstateWebsite-ejbPU")
private EntityManager em;
#Override
public void AddProperty(Property property) {
em.persist(property);
}
#Override
public void EditProperty(Property property) {
em.merge(property);
}
#Override
public void DeleteProperty(int propertyId) {
em.remove(GetProperty(propertyId));
}
#Override
public List<Property> GetAllProperty() {
return em.createNamedQuery("Property.findAll").getResultList();
}
#Override
public Property GetProperty(int propertyId) {
return em.find(Property.class, propertyId);
}
#Override
public void EditPropertyAddress(Paddress propertyAddress) {
em.merge(propertyAddress);
}
}
Offer entity:
#Entity
#Table(name = "OFFER")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Offer.findAll", query = "SELECT o FROM Offer o")})
public class Offer implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "OFFERID")
private Integer offerid;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 100)
#Column(name = "OFFERSTATUS")
private String offerstatus;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 100)
#Column(name = "ORIGINALOFFER")
private String originaloffer;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 100)
#Column(name = "OFFERINGBP")
private String offeringbp;
#Basic(optional = false)
#NotNull
#Column(name = "OFFEREDDATE")
#Temporal(TemporalType.DATE)
private Date offereddate;
#Basic(optional = false)
#NotNull
#Column(name = "OFFEREDTIME")
#Temporal(TemporalType.TIME)
private Date offeredtime;
#JoinColumn(name = "BUYERID", referencedColumnName = "BUYERID")
#ManyToOne(optional = false)
private Buyer buyerid;
#JoinColumn(name = "PROPERTYID", referencedColumnName = "PROPERTYID")
#ManyToOne(optional = false)
private Property propertyid;
public Offer() {
}
public Offer(Integer offerid) {
this.offerid = offerid;
}
public Offer(String offerstatus, String originaloffer, String offeringbp, Date offereddate, Date offeredtime, Buyer buyerid, Property propertyid) {
this.offerstatus = offerstatus;
this.originaloffer = originaloffer;
this.offeringbp = offeringbp;
this.offereddate = offereddate;
this.offeredtime = offeredtime;
this.buyerid = buyerid;
this.propertyid = propertyid;
}
public Integer getOfferid() {
return offerid;
}
public void setOfferid(Integer offerid) {
this.offerid = offerid;
}
public String getOfferstatus() {
return offerstatus;
}
public void setOfferstatus(String offerstatus) {
this.offerstatus = offerstatus;
}
public String getOriginaloffer() {
return originaloffer;
}
public void setOriginaloffer(String originaloffer) {
this.originaloffer = originaloffer;
}
public String getOfferingbp() {
return offeringbp;
}
public void setOfferingbp(String offeringbp) {
this.offeringbp = offeringbp;
}
public Date getOffereddate() {
return offereddate;
}
public void setOffereddate(Date offereddate) {
this.offereddate = offereddate;
}
public Date getOfferedtime() {
return offeredtime;
}
public void setOfferedtime(Date offeredtime) {
this.offeredtime = offeredtime;
}
public Buyer getBuyerid() {
return buyerid;
}
public void setBuyerid(Buyer buyerid) {
this.buyerid = buyerid;
}
public Property getPropertyid() {
return propertyid;
}
public void setPropertyid(Property propertyid) {
this.propertyid = propertyid;
}
#Override
public int hashCode() {
int hash = 0;
hash += (offerid != null ? offerid.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Offer)) {
return false;
}
Offer other = (Offer) object;
if ((this.offerid == null && other.offerid != null) || (this.offerid != null && !this.offerid.equals(other.offerid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.sushan.model.Offer[ offerid=" + offerid + " ]";
}
EJB OfferDAO:
#Stateless
public class OfferDAO implements OfferDAOLocal {
#PersistenceContext(unitName="RealEstateWebsite-ejbPU")
EntityManager em;
#Override
public void EditOffer(Offer offer) {
em.merge(offer);
}
#Override
public List<Offer> GetAllOffer(int propertyId) {
return em.createNamedQuery("Offer.findByPropertyID").setParameter("propertyID", propertyId).getResultList();
}
#Override
public List<Offer> GetAllOffer() {
return em.createNamedQuery("Offer.findAll").getResultList();
}
#Override
public void Add(Offer offer) {
em.persist(offer);
}
}
Servlet that connects the JSP with the EJB:
String action = request.getParameter("action");
String currencyType = request.getParameter("ddlCurrencyType");
String amount = request.getParameter("offerAmount");
String propertyIdStr = request.getParameter("hdnbt");
if ("Offer".equalsIgnoreCase(action))
{
if ("".equals(action) & !"".equals(currencyType) & !"".equals(amount) & !"".equals(propertyIdStr))
{
DateFormat df = new SimpleDateFormat("dd/MM/yy");
DateFormat df1 = new SimpleDateFormat("HH:mm:ss");
Date currentDate = new Date();
Date currentTime = new Date();
int propertyId = Integer.parseInt(propertyIdStr);
try {
currentDate = df.parse(df.format(currentDate));
currentTime = df1.parse(df1.format(currentTime));
} catch (ParseException e) {
}
Buyer buyer = buyerDAO.GetBuyer(1);
Property property = propertyDAO.GetProperty(propertyId);
Offer offer = new Offer("Pending", amount, amount, currentDate, currentTime, buyer, property);
offerDAO.Add(offer);
}
else
{
}
}
request.setAttribute("allProperty", propertyDAO.GetAllProperty());
request.getRequestDispatcher("AdministerProperty.jsp").forward(request, response);
Am I missing something here? I have followed a tutorial which didn't have a foreign key guidance but tried to use my own logic to go around it but it didn't work. I cannot find a reliable source that uses the method similar to me. Most of the resources I find are for Hibernate but I am using EJB.
It seems that the method which retrieves the Property and the method that persists the Offer are run in a separate transactions (DAOs being the Stateless session beans).
That would mean that the Offer is populated and persisted with a detached Property, so the persistence provider is not aware of it.
Not sure why an exception is not raised but you would have to merge the Property first or do the query in the same transaction as you persist the Offer:
#Override
public void Add(Offer offer, int peropertyId) {
Property property = em.find(Property.class, propertyId);
offer.setPeropertyId(property);
em.persist(offer);
}
or
#Override
public void Add(Offer offer, Property peroperty) {
Property managedProperty = em.merge(property);
offer.setPeropertyId(managedProperty);
em.persist(offer);
}
I fixed it. If you look at the code for servlet, it was the problem with my if condition that checks the action parameter. It was meant to be if action is not empty but it checks if action is empty. I found this issue by creating an integer that increments itself when it reaches certain stages within the code.
I think you were right on the fact that I had to do the getting property id and buyer id on the same transaction. Otherwise that would have been the next issue for me. Thank you.

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

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

Spring data Join multiple tables

This is it my database project:
I have a problem with the correct combination of tables, as it is in the picture.
This is my files:
Category.java
#Entity
public class Category {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private long id;
private String categoryName;
protected Category() {}
public Category(String categoryName) {
this.categoryName = categoryName;
}
public String getCategoryName() {
return categoryName;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
#Override
public String toString() {
return String.format(
"Customer[id=%d, firstName='%s']",
id, categoryName);
}
}
Items.java
#Entity
#Table(name = "Items")
public class Items {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int ItemId;
private String ItemName;
private String price;
private Set<Locals> locals = new HashSet<Locals>(0);
public Items(){
}
public Items(String price, String itemName) {
this.price = price;
this.ItemName = itemName;
}
public void setItemId(int itemId) {
ItemId = itemId;
}
public void setLocals(Set<Locals> locals) {
this.locals = locals;
}
public void setPrice(String price) {
this.price = price;
}
public void setItemName(String itemName) {
ItemName = itemName;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "ItemId", unique = true, nullable = false)
public int getItemId() {
return ItemId;
}
#ManyToMany(fetch = FetchType.LAZY, mappedBy = "itemsTo")
public Set<Locals> getLocals() {
return locals;
}
#Column(name = "price", nullable = false, length = 10)
public String getPrice() {
return price;
}
#Column(name = "ItemName", nullable = false, length = 10)
public String getItemName() {
return ItemName;
}
}
Locals.java
#Entity
#Table(name = "Locals")
public class Locals {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int LocalId;
private String localName;
private String address;
private String phoneNumber;
private String coorX;
private String coorY;
private Set<Items> itemsTo = new HashSet<Items>(0);
public Locals(){
}
public Locals(String localName,String address,String phoneNumber, String coorY, String coorX) {
this.coorY = coorY;
this.coorX = coorX;
this.phoneNumber = phoneNumber;
this.address = address;
this.localName = localName;
}
public Locals(String localName,String address,String phoneNumber, String coorY, String coorX, Set<Items> itemsTo) {
this.coorY = coorY;
this.coorX = coorX;
this.phoneNumber = phoneNumber;
this.address = address;
this.localName = localName;
this.itemsTo = itemsTo;
}
public void setLocalId(int localId) {
LocalId = localId;
}
public void setLocalName(String localName) {
this.localName = localName;
}
public void setAddress(String address) {
this.address = address;
}
public void setCoorX(String coorX) {
this.coorX = coorX;
}
public void setCoorY(String coorY) {
this.coorY = coorY;
}
public void setItemsTo(Set<Items> itemsTo) {
this.itemsTo = itemsTo;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "LocalId", unique = true, nullable = false)
public int getLocalId() {
return LocalId;
}
#Column(name = "localName", unique = false, nullable = false, length = 10)
public String getLocalName() {
return localName;
}
#Column(name = "address", unique = false, nullable = false, length = 10)
public String getAddress() {
return address;
}
#Column(name = "phoneNumber", unique = false, nullable = false, length = 10)
public String getPhoneNumber() {
return phoneNumber;
}
#Column(name = "coorX", unique = false, nullable = false, length = 10)
public String getCoorX() {
return coorX;
}
#Column(name = "coorY", unique = false, nullable = false, length = 10)
public String getCoorY() {
return coorY;
}
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinTable(name = "ItemsFinall", joinColumns = {
#JoinColumn(name = "LocalId", nullable = false, updatable = false) },
inverseJoinColumns = { #JoinColumn(name = "ItemId",
nullable = false, updatable = false) })
public Set<Items> getItemsTo() {
return itemsTo;
}
}
and ItemsFinall.java
#Entity
#Table(name = "ItemsFinall")
public class ItemsFinall {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private int ItemId;
private int CategoryId;
private int LocalId;
public ItemsFinall(int id, int localId, int categoryId, int itemId) {
this.LocalId = localId;
this.CategoryId = categoryId;
this.ItemId = itemId;
this.id=id;
}
public void setId(int id) {
this.id = id;
}
public void setLocalId(int localId) {
LocalId = localId;
}
public void setCategoryId(int categoryId) {
CategoryId = categoryId;
}
public void setItemId(int itemId) {
ItemId = itemId;
}
public int getLocalId() {
return LocalId;
}
public int getCategoryId() {
return CategoryId;
}
public int getItemId() {
return ItemId;
}
public int getId() {
return id;
}
}
I get the following error: Caused by: org.springframework.data.mapping.PropertyReferenceException: No property categoryName found for type ItemsFinall!
I do not know what to do to properly connect the table.
ItemsServiceImpl.java
package dnfserver.model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by Ɓukasz on 2015-03-14.
*/
#Component
public class CategoryServiceImpl implements CategoryService {
#Autowired
private CategoryRepository categoryRepository;
private Map<Integer,String> categoryMap = new HashMap<Integer, String>();
#Override
public Category create(Category category) {
Category createdCategory = category;
return categoryRepository.save(createdCategory);
}
#Override
public Category delete(int id) {
return null;
}
#Autowired
public Map<Integer,String> findAll(){
int i=0;
for (Category cat : categoryRepository.findAll()) {
categoryMap.put(i,cat.toString());
i++;
}
return categoryMap;
}
#Override
public Category update(Category shop) {
return null;
}
#Override
public Category findById(int id) {
return categoryRepository.findOne(id);
}
}
In hibernate/JPA you model the relationship between Entities, but not use plain Ids!
For example
#Entity
#Table(name = "ItemsFinall")
public class ItemsFinall {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
//instead of: private int ItemId;
#OneToMany
private Item item;
//instead of: private int CategoryId;
#OneToMany
private Category category;
//instead of: private int LocalId;
#OneToMany
private Local local;
...
(You also need to fix the Set<Locals> locals in item)

Categories

Resources