HIbernate - JPA: foreign key not set in ManyToOne relationship - java

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

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

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.

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.

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

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

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