简体   繁体   中英

how does “.merge(entity)” work?

i'm creating a java EE (web) application using JPA and EJB for model-tier. i think i have to use Session Beans for CRUD.

this is my BrandFacade.java (session bean)

package model.business;

import model.localinterface.BrandFacadeLocal;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import model.entities.Brand;

@Stateless
public class BrandFacade extends AbstractFacade<Brand> implements BrandFacadeLocal, BrandFacadeRemote {

    @PersistenceContext(unitName = "MyWheelEE-ejbPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public BrandFacade() {
        super(Brand.class);
    }


    @Override
    public boolean CreateBrand(String name) {
        Brand brand=new Brand(0, name);
        boolean result=true;
        try {
            em.persist(brand);
        } catch (Exception e) {
            result=false;
        }  
        em.close();
        return result;
    }

    @Override
    public void deleteBrand(int brandOid) {
        em.remove(getBrandByOid(brandOid));
        em.flush();
    }

    @Override
    public Brand getBrandByOid(int brandOid) {
        em.flush();
        return em.find(Brand.class, brandOid);
    }

    @Override
    public void editBrand(Brand brand) {
        em.merge(brand);
        em.flush();
    }


}

and this is my Brand.java class (entity)

package model.entities;

import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

@Entity
@Table(name = "brand")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Brand.findAll", query = "SELECT b FROM Brand b"),
    @NamedQuery(name = "Brand.findByOid", query = "SELECT b FROM Brand b WHERE b.oid = :oid"),
    @NamedQuery(name = "Brand.findByName", query = "SELECT b FROM Brand b WHERE b.name = :name")})
public class Brand implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "oid")
    private Integer oid;
    @Basic(optional = false)
    @Column(name = "name")
    private String name;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "brandOid")
    private List<Wheelchair> wheelchairList;

    public Brand() {
    }

    public Brand(Integer oid) {
        this.oid = oid;
    }

    public Brand(Integer oid, String name) {
        this.oid = oid;
        this.name = name;
    }

    public Integer getOid() {
        return oid;
    }

    public void setOid(Integer oid) {
        this.oid = oid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @XmlTransient
    public List<Wheelchair> getWheelchairList() {
        return wheelchairList;
    }

    public void setWheelchairList(List<Wheelchair> wheelchairList) {
        this.wheelchairList = wheelchairList;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (oid != null ? oid.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 Brand)) {
            return false;
        }
        Brand other = (Brand) object;
        if ((this.oid == null && other.oid != null) || (this.oid != null && !this.oid.equals(other.oid))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "model.entities.Brand[ oid=" + oid + " ]";
    }

}

i wish to know how does .merge method work... i think it search in the DB the entity which has the primary key of the entity passed and then it works on edited fields right?

but how i can edit a brand knowing only the name?

It's quite simple really, here your answers:

I wish to know how does .merge method work... When you call merge method, JPA will verify if the field marked as primary key (@Id) is not null: - IF YES: JPA will create a new record in your database - IT NOT: JPA will update your record using the id field value, something like (UPDATE table_name ..... WHERE id=?) So, you are right :)

but how i can edit a brand knowing only the name? If you wanna edit a record knowing another field rather than Id field, you will have 2 options: 1. Write JPQL, something like:

UPDATE Person p SET p.lastName = 'New Last Name' WHERE p.name = 'his name'
  1. Write a Native Query, in this case, you will write PLAIN SQL and the run it

In both cases, you will need to do something like:

Query query = em.createQuery or em.createNativeQuery

and then just execute it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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