2016-09-17 7 views
0

私は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; 
... 
} 

私は次のステップを実行しています:

    所有者オブジェクトを作成
  1. :CarsOrm.addOwner()を使用しOwner owner = new Owner(1000000, "Petro", 1976);(owner.cars == NULL)して保存
  2. 車オブジェクトを作成:

    整数[]の所有者= {所有者}。
    車の車=新しい車(9999999、 "黒"、所有者、model.getModelName());

(満たされcar.owners)とCarsOrm.addCarを使用してそれを保存()

報復した後、私はCarsOrm.getOwners(長いregNumber)を使用している、それはnullを返します。 Ormはデータベースにリクエストしません。ステップ1でowner.cars == nullを指定して保存された現金からオブジェクトを取得します。オブジェクトが永続化されているときにプログラムを再起動すると、関数は正しく機能し、正しいオーナーセットを取得します。 なぜオブジェクトオーナーは別のオブジェクトの後にcasheで更新されません - それは車のセットを維持し、変更しますか?

答えて

-2

@ManyToManyアノテーションにcascade = {CascadeType.PERSIST, CascadeType.MERGE}を追加することができます。

しかし、私は休止状態に頼らないことを勧めます。あなたは車のコンストラクターの所有者に車を追加する必要があります。これは、エンティティを永続化する前に追加のチェックを行う場合に便利です。 JUnitテストで。

public Car(long regNumber, String color, Owner owner, Model model){ 
    ... 
    owner.addCar(this); 
} 
関連する問題