私はORMのHibernateのJPAを使用して、次のDAOクラスを持っている:のEntityManagerは@ManyToMany関係フィールドのデータを更新しない
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;
...
}
私は次のステップを実行しています:
-
所有者オブジェクトを作成
- :CarsOrm.addOwner()を使用し
Owner owner = new Owner(1000000, "Petro", 1976);
(owner.cars == NULL)して保存 車オブジェクトを作成:
整数[]の所有者= {所有者}。
車の車=新しい車(9999999、 "黒"、所有者、model.getModelName());
(満たされcar.owners)とCarsOrm.addCarを使用してそれを保存()
報復した後、私はCarsOrm.getOwners(長いregNumber)を使用している、それはnullを返します。 Ormはデータベースにリクエストしません。ステップ1でowner.cars == nullを指定して保存された現金からオブジェクトを取得します。オブジェクトが永続化されているときにプログラムを再起動すると、関数は正しく機能し、正しいオーナーセットを取得します。 なぜオブジェクトオーナーは別のオブジェクトの後にcasheで更新されません - 車それは車のセットを維持し、変更しますか?