-1

When i changed my orphanRemoval=true to false, the entities are not deleted but are not loaded into json file after updating the parent entity. This is my code below. Models classes: 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 + "]";
    }
}

And this is my dao implementation

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

I have tried changing my cascade type but it didn't work. Please help.

My JSON file before update :

[
{
    "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"
}

]

And my JSON file after update :

[
    {
        "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
            }
        ]
    }
]

But, the data exists in the database. When I restart the server, its loaded.

This is my controller :

@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();
    }
}
  • The query in the updateMarket method is not used at all. All you do is to merge the incoming market object. Where from that object come? I assume you create it from an incoming json. And if that incoming json doesn't contain all of the related products, then of course when you merge it the persisted market will no more contain those relations. – Selindek Jan 31 '19 at 11:30
  • But, the incoming json contains all of the related products. But when I merge it, the persisted market no more contains those relations – Kumari Ankita Jan 31 '19 at 13:08
  • This might be a duplicate of https://stackoverflow.com/questions/5460573/hibernate-bidirectional-manytoone-updating-the-not-owning-side-not-working – Jens Schauder May 25 '20 at 09:21

2 Answers2

0

I don't know how does you controller look like, but something is messed up there. Because you override the market during update, at least the id is correct. So try this:

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();
}
Selindek
  • 3,269
  • 1
  • 18
  • 25
0

I have solved this. I have made a little change in code of update :

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