Hibernate从List中删除项目。

时间:2016-09-05 15:22:03

标签: hibernate one-to-many nhibernate-collections

伙计们! 如何从Parent中删除项目 - >儿童清单? 这是我的情况。

控制器

@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:/";
}

分销商(家长)

@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..

我从网址获取分销商ID,然后使用getByID获取正确的分销商对象,​​其中包含我要删除的参展商..

1 个答案:

答案 0 :(得分:0)

List的remove方法适用于对象的equals方法实现。做这样的事情。

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