Search code examples
hibernateone-to-manynhibernate-collections

Hibernate remove item from List.


guys ! How can i remove item from Parent - > Child List ? Here is my situation.

Controller

@RequestMapping(value = "/delete/{distributorId}/{exhibitorId}", method = RequestMethod.GET)
    public String deleteExhibitor(Model model, @PathVariable("distributorId") Integer distributorId,
        @PathVariable("exhibitorId") Integer exhibitorId) {

    Distributor distributor = distributorService.getById(distributorId);

    distributor.getExhibitor().remove(exhibitorId);

    distributorService.update(distributor);

    return "redirect:/";
}

And Distributor (Parent)

@Entity
@Table(name = "distributor")
public class Distributor {

@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;

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

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

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

@LazyCollection(LazyCollectionOption.FALSE)
@OrderColumn(name="orders_index")
@OneToMany(cascade = CascadeType.ALL, orphanRemoval=true)
List<Exhibitor> exhibitor = new ArrayList<Exhibitor>();

@LazyCollection(LazyCollectionOption.FALSE)
@OneToMany(cascade = CascadeType.ALL, orphanRemoval=true)
List<Merchandiser> merchandiser = new ArrayList<Merchandiser>();
Getters and setters..

I'm getting the Distributor Id from the url, and next using getByID, getting the proper Distributor object, which contains the Exhibitor that i want to delete..


Solution

  • List's remove method works on equals method implementation of the object .Do some thing like this.

    Iterator x = distributor.getExhibitor().iterator();
    while(x.hasNext()){
        Exhibitor ex = x.next();
        if(ex.getExhibitorId()!=null && ex.getExhibitorId().equals(exhibitorId)){
             x.remove();
             break;
         }
    }