简体   繁体   English

使用EJB和JPA持久化具有外键的表

[英]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. 我是JavaEE的新手,我遇到了一个问题,即使用实体类和ejb的实体管理器持久化一个表,该表指向另一个表的主键。 I am using Netbeans. 我正在使用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. 我有一个名为'property'的实体,并有另一个名为'offer'的实体,它保存指向属性主键的外键。 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: 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: 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: 将JSP与EJB连接的Servlet:

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. 我找到的大部分资源都是针对Hibernate的,但我使用的是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). 似乎检索Property的方法和持有Offer的方法在单独的事务中运行(DAO是无状态会话bean)。

That would mean that the Offer is populated and persisted with a detached Property, so the persistence provider is not aware of it. 这意味着将使用分离的属性填充和保留Offer,因此持久性提供程序不会意识到它。

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: 不确定为什么不引发异常,但您必须首先合并属性,或者在保留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. 如果你看一下servlet的代码,那就是我的if条件检查action参数的问题。 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. 我认为你必须在同一笔交易中获取属性ID和买方ID是正确的。 Otherwise that would have been the next issue for me. 否则那对我来说就是下一个问题。 Thank you. 谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM