【发布时间】:2016-09-17 09:30:48
【问题描述】:
我正在使用 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;
...
}
我正在做接下来的步骤:
- 创建所有者对象:
Owner owner = new Owner(1000000, "Petro", 1976);(owner.cars == null) 并使用 CarsOrm.addOwner() 保存它 -
创建汽车对象:
整数[] 所有者 = {所有者};
Car car = new Car(9999999, "Black", Owners, model.getModelName());
(car.owners 填充)并使用 CarsOrm.addCar() 保存它
当我使用 CarsOrm.getOwners(long regNumber) 之后,它返回 null。 Orm 不向数据库发出请求 - 它从步骤 1 中保存的 owner.cars == null 的现金中获取对象。如果我在保留对象时重新启动程序,则该功能可以正常工作-检索正确的所有者集。 为什么对象 owner 不会在另一个对象之后更新 - car 坚持并更改它的汽车集?
【问题讨论】:
标签: java hibernate jpa many-to-many