在JPA双向@OneToMany关系,当我更新父实体,子实体在数据库中删除

时间:2019-01-31 10:58:22

标签: java jpa-2.0

当我改变orphanRemoval =真假,实体不被删除而是更新父实体后不会被加载到JSON文件。这是我的下面的代码。 模型类: Market.java:

    package main.java.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.*;
import javax.xml.bind.annotation.XmlRootElement;

import org.codehaus.jackson.annotate.JsonIgnoreProperties;

@XmlRootElement(name="somename")
@Entity
@JsonIgnoreProperties(ignoreUnknown=true)
@Table(name = "market")
@SecondaryTable(name="product",pkJoinColumns=@PrimaryKeyJoinColumn(name="market_id"))
@NamedQuery(name = "findMarket", 
query = "SELECT distinct m FROM Market m, Product p where m.id = p.market_id")
public class Market implements Serializable{

    public List<Product> getProducts() {
        return products;
    }

    public void setProducts(List<Product> products) {
        this.products = products;
    }

    private static final long serialVersionUID = 1L;

    @Column(name = "market_name")
    private String market_name;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private int id;

    @Column(name = "Online_Market_Accessibility")
    private String oma;

    @OneToMany(mappedBy="market", cascade=CascadeType.ALL, orphanRemoval=false)
    @JoinColumn(name="id", nullable=false)
    private List<Product> products = new ArrayList<>();

    public Market() 
    {

    }

    public Market(String market_name,int id, String oma)
    {
        this.market_name = market_name;
        this.id = id;
        this.oma = oma;
    }

    public String getMarket_name() {
        return market_name;
    }

    public void setMarket_name(String market_name) {
        this.market_name = market_name;
    }


    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getOma() {
        return oma;
    }

    public void setOma(String oma) {
        this.oma = oma;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + id;
        result = prime * result + ((market_name == null) ? 0 : market_name.hashCode());
        result = prime * result + ((oma == null) ? 0 : oma.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Market other = (Market) obj;
        if (id != other.id)
            return false;
        if (market_name == null) {
            if (other.market_name != null)
                return false;
        } else if (!market_name.equals(other.market_name))
            return false;
        if (oma == null) {
            if (other.oma != null)
                return false;
        } else if (!oma.equals(other.oma))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "[market_name:"+ market_name + ", id:" + id +", oma:"+oma+"]";
    }
}

Product.java:

    package main.java.model;

import java.io.Serializable;

import javax.persistence.*;

@Entity
@NamedQuery(name = "findProductByMarketId", 
query = "SELECT distinct p " +
        "FROM Market m, Product p where m.id = p.market.id")
public class Product implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private int product_id;

    private String product_name;

    private int market_id;

    @ManyToOne
    @JoinColumn(name="market_id", insertable=false, updatable=false, nullable=false)
    private Market market;

    public Product() {

    }

    public Product(String product_name, int product_id, int market_id)
    {
        this.product_id = product_id;
        this.product_name = product_name;
        this.market_id = market_id;
    }

    public String getProduct_name() {
        return product_name;
    }

    public void setProduct_name(String product_name) {
        this.product_name = product_name;
    }

    public int getProduct_id() {
        return product_id;
    }

    public void setProduct_id(int product_id) {
        this.product_id = product_id;
    }

    public int getMarket_id() {
        return market_id;
    }

    public void setMarket_id(int market_id) {
        this.market_id = market_id;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + market_id;
        result = prime * result + product_id;
        result = prime * result + ((product_name == null) ? 0 : product_name.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Product other = (Product) obj;
        if (market_id != other.market_id)
            return false;
        if (product_id != other.product_id)
            return false;
        if (product_name == null) {
            if (other.product_name != null)
                return false;
        } else if (!product_name.equals(other.product_name))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "Product [name=" + product_name + ", Product Id =" + product_id + "]";
    }
}

这是我的DAO实现

    package main.java.services;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import main.java.dao.MarketDao;
import main.java.model.Market;

public class MarketService implements MarketDao{

    EntityManagerFactory emf = Persistence.createEntityManagerFactory("myPU");
    EntityManager em = emf.createEntityManager();

    public List<Market> getAllMarkets(){
        Query query = em.createNamedQuery("findMarket");
        List<Market> m = query.getResultList();
        return m;
    }

    public void updateMarket(int id, String market_name, Market market) {
        em.getTransaction().begin();
        Query query = em.createQuery("UPDATE Market SET market_name=:market_name WHERE id=:id");
        query.setParameter("id", id);
        query.setParameter("market_name", market_name);
        em.merge(market);
        em.getTransaction().commit();
    }

    public void deleteMarket(int id) {
        Market market = em.find(Market.class, id);
        if(null != market) {
            em.remove(market);
        }
    }

    public void addMarket(Market market) {
        em.getTransaction().begin();
        em.persist(market);
        em.getTransaction().commit();
    }
}

我试图改变我的级联型,但没有奏效。请帮忙。

更新之前我的JSON文件:

[
{
    "id": 2,
    "products": [
        {
            "product_id": 4,
            "market_id": 2,
            "product_name": "Apple"
        },
        {
            "product_id": 5,
            "market_id": 2,
            "product_name": "Samsung"
        }
    ],
    "oma": "Yes",
    "market_name": "SmartPhones"
},
{
    "id": 3,
    "products": [
        {
            "product_id": 6,
            "market_id": 3,
            "product_name": "Ranbaxy"
        }
    ],
    "oma": null,
    "market_name": "Pharmaceuticals"
},
{
    "id": 1,
    "products": [
        {
            "product_id": 3,
            "market_id": 1,
            "product_name": "Emirates"
        },
        {
            "product_id": 2,
            "market_id": 1,
            "product_name": "PANAmerican"
        },
        {
            "product_id": 1,
            "market_id": 1,
            "product_name": "Indigo"
        }
    ],
    "oma": null,
    "market_name": "Airline Travels"
},
{
    "id": 4,
    "products": [
        {
            "product_id": 7,
            "market_id": 4,
            "product_name": "Cake"
        }
    ],
    "oma": null,
    "market_name": "Baked Good"
}

]

更新后还有我的JSON文件:

[
    {
        "id": 2,
        "market_name": "SmartPhones",
        "oma": "Yes",
        "products": [
            {
                "product_id": 4,
                "product_name": "Apple",
                "market_id": 2
            },
            {
                "product_id": 5,
                "product_name": "Samsung",
                "market_id": 2
            }
        ]
    },
    {
        "id": 3,
        "market_name": "Pharmaceuticals",
        "oma": null,
        "products": [
            {
                "product_id": 6,
                "product_name": "Ranbaxy",
                "market_id": 3
            }
        ]
    },
    {
        "id": 1,
        "market_name": "Airline Travels",
        "oma": null,
        "products": []
    },
    {
        "id": 4,
        "market_name": "Baked Good",
        "oma": null,
        "products": [
            {
                "product_id": 7,
                "product_name": "Cake",
                "market_id": 4
            }
        ]
    }
]

但是,数据存在于数据库中。当我重新启动服务器时,它已加载。

这是我的控制器:

@Transactional
@Path("/json/market")
public class MarketContoller {

    MarketService ms = new MarketService();

    @GET
    @Path("/get")
    @Produces(MediaType.APPLICATION_JSON)
    public List<Market> listAllMarket(){
         return ms.getAllMarkets();
    }

    @PUT
    @Path("/put/{id}")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response update(@PathParam("id") int id, @PathParam("market_name") String market_name, Market market) {
        String result = "Market updated " + market;
        ms.updateMarket(id, market_name);
        return Response.status(201).entity(result).build();
    }

     @DELETE
     @Path("{id}")
     public void delete(@PathParam("id") int id) {
            ms.deleteMarket(id);
            }

    @POST
    @Path("/post")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response createMarketInJSON(Market market) {
        String result = "Market created " + market;
        ms.addMarket(market);   
        return Response.status(201).entity(result).build();
    }
}

2 个答案:

答案 0 :(得分:0)

我不知道您的控制器的外观如何,但是那里有些混乱。 由于您在更新过程中覆盖了市场,因此至少ID是正确的。所以试试这个:

public void updateMarket(int id, String market_name) {
    em.getTransaction().begin();
    Market market = em.find(Market.class, id);
    if(null != market) {
        market.setMarket_name(market_name);
        em.merge(market);
    }
    em.getTransaction().commit();
}

答案 1 :(得分:0)

我解决了这个问题。我对更新代码进行了一些更改:

public void updateMarket(int id, String market_name, Market market) {
    em.getTransaction().begin();
    Query query = em.createQuery("UPDATE Market SET market_name=:market_name WHERE id=:id");
    query.setParameter("id", id);
    query.setParameter("market_name", market_name);
    query.executeUpdate();
    em.merge(market);
    em.getTransaction().commit();
}