EntityManager不会更新@ManyToMany关系字段中的数据

时间:2016-09-17 09:30:48

标签: java hibernate jpa many-to-many

我正在使用ORM Hibernate的JPA并拥有下一个DAO类:

public class CarsOrm  {
    @PersistenceContext(unitName = "springHibernate", type = PersistenceContextType.EXTENDED)
    EntityManager em;

    @Transactional
    public boolean addCar(Car car) {
        if (em.find(Car.class, car.regNumber) != null)
            return false;
        Model model = em.find(Model.class, car.modelName);
        if (model == null)
            return false;
        em.persist(car);
        return true;

    }

    @Transactional
    public boolean addOwner(Owner owner) {
        if (em.find(Owner.class, owner.id) != null)
            return false;
        em.persist(owner);
        return true;

    }


    public Iterable<Owner> getOwners(long regNumber) {
        Car car = em.find(Car.class, regNumber);
        return car==null?null:car.getOwners();
    }

   ...
}

实体是下一个:

@Entity
@Table(name = "cars")
public class Car {
    @Id
    long regNumber;
    String color;
    @ManyToOne
    Model model;
    @ManyToMany(fetch = FetchType.EAGER)
    Set<Owner> owners;
...
}

@Entity
@Table(name = "owners")
public class Owner {
    @Id
    int id;
    String ownerName;
    int yearBirth;
    @ManyToMany(mappedBy = "owners", fetch = FetchType.EAGER)
    Set<Car> cars;
...
}

我正在做下一步:

  1. 创建所有者对象:Owner owner = new Owner(1000000, "Petro", 1976);(owner.cars == null)并使用CarsOrm.addOwner()保存它
  2. 创建汽车对象:

    整数[]所有者= {所有者};
    Car car = new Car(9999999,“Black”,所有者,model.getModelName());

  3. (car.owners填充)并使用CarsOrm.addCar()

    保存它

    当我使用CarsOrm.getOwners(long regNumber)后,它返回null。 Orm不向数据库发出请求 - 它使用owner.cars == null从步骤1中保存的现金获取对象。如果我在持久化对象时重新启动程序,则该功能正常工作 - 检索正确的所有者集。 为什么对象所有者不会在另一个对象后更新 - 汽车持续并更改它的汽车组?

1 个答案:

答案 0 :(得分:-2)

您可以尝试将cascade = {CascadeType.PERSIST, CascadeType.MERGE}添加到@ManyToMany注释中。

但我建议不要依赖hibernate。您应该在Car的consturctor中将汽车添加到车主。如果您在持久化实体之前进行一些额外检查,这将非常有用。在JUnit测试中。

public Car(long regNumber, String color, Owner owner, Model model){
  ...
  owner.addCar(this);
}