【问题标题】:@ManyToOne UniDirectional delete@ManyToOne 单向删除
【发布时间】:2015-08-23 03:41:25
【问题描述】:

我在人和车之间有一个@ManyToOne 单向关系,这意味着一辆车可以由几个人拥有。问题是当我删除汽车时,汽车 ID 不会从 Person 的实体连接列中删除。有没有办法配置 JPA 在删除汽车后从车主加入列中删除汽车 ID?

注意: 使用 orpahRemoval=true 将无济于事,因为我需要将父级的汽车引用更新为 null,并且每个实体(汽车/人)不依赖于另一个实体的存在......

 @Entity
    public class Car{
        @Id
        @GeneratedValue
        private long id;
    }

    @Entity
    public class Person {
        @Id
        @GeneratedValue
        private long id;

        @ManyToOne
        @JoinColumn(name="CAR_ID")
        private Car car;  
    }

【问题讨论】:

    标签: jpa eclipselink many-to-one


    【解决方案1】:

    没有。您需要执行查询以查找所有拥有给定汽车的人,将他们的汽车设置为 null,然后删除汽车:

    List<Person> persons = em.createQuery("select p from Person p where p.car = :car", Person.class)
                             .setParameter("car", car)
                             .getResultList();
    for (Person person : persons) {
        person.setCar(null);
    }
    em.remove(car);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-01
      • 2017-09-27
      • 2020-11-08
      • 2017-10-23
      • 2013-08-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多