2016-11-07 9 views
0

JPAエンティティマネージャで非常に奇妙な問題に直面しています。私は団体を牽引している 1)インシデント 2)国JPAは更新されたデータを取得しません

国はマスターであり、インシデントはManyToOneを持つ子です。

Incident.java

@Entity 
@Table(name = "Incident") 
public class Incident { 

    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    @Column(name = "incidentID") 
    private Integer incidentID; 

    @Column(name = "incidentTitle") 
    private String incidentTitle; 

    @ManyToOne 
    @JoinColumn(name = "countryID") 
    private Country country; 

    @Transient 
    @ManyToOne 
    @JoinColumn(name = "countryID") 
    public Country getCountry() { 
     return country; 
    } 

    public void setCountry(Country country) { 
     this.country = country; 
    } 

    // Getter and setters 


} 

Country.Java

@Entity 
@Table(name="Country") 
public class Country { 
    @Id 
    @Column(name="id") 
    @GeneratedValue(strategy=GenerationType.IDENTITY) 
    private Integer id; 

    @Column(name = "name") 
    private String name; 

    @OneToMany(mappedBy = "country", cascade = CascadeType.ALL, orphanRemoval = true) 
    private List<Incident> incident; 


    @OneToMany 
     @JoinColumn(
      name="countryID",nullable=false) 
    public List<Incident> getIncident() { 
     return incident; 
    } 

    public void setIncident(List<Incident> incident) { 
     this.incident = incident; 
    } 
    //getter and setter 

} 

RepositoryImpl.java

@Repository 
@Transactional 
public class IncidentRepositoryImpl implements IncidentRepository{ 

    @PersistenceContext 
    private EntityManager em; 

    @Autowired 
    public void setEntityManager(EntityManagerFactory sf) { 
     this.em = sf.createEntityManager(); 
    } 

    @Override 
    public Incident addIncident(Incident incident) { 
     try {   
      em.getTransaction().begin(); 
      em.persist(incident); 
      em.getTransaction().commit(); 
      return incident; 
     } catch (HibernateException e) {    
      return null; 
     } 
    } 


    public Incident findById(int id) { 
     Incident incident = null; 
     incident = (Incident) em.find(Incident.class, id);  
     return incident; 

    } 

} 

私はインシデントを追加すると、事件が事件テーブルにcountryIDで正常に追加され、しかし、私は同じ事件をフェッチしようとすると、国名はnullになります。しかし、私がサーバーを再起動したり、アプリケーションの国名を再デプロイするときにも来ます。 JAPエンティティマネージャにキャッシュの問題があることを願っています。 findByIdメソッドでem.refresh(incident)を使用しようとすると、国名が正常に取得されます。しかし、このリフレッシュ方法は非常に高価なコールです。

代わりに、自動的にjpaキャッシュを更新する方法を提案してください。あなたのEntityManager em

+0

のライフサイクルを制御します。 – duffymo

+0

それで、私がした間違いは何ですか?私に教えてもらえますか? –

+0

あなたは国のフィールド**と**のゲッターをマッピングしていますか?後者は@Transientです。 getterからすべてのアノテーションを削除します。 –

答えて

0

PersistenceContextType.TRANSACTION

@PersistenceContext(type = PersistenceContextType.TRANSACTION) 
private EntityManager em; 

を追加し、春には、あなたのトランザクションマネージャが挿入をコミットし、セッションをフラッシュするのに失敗しましたような音EntityManager

+0

あなたの提案を試みたが、問題を解決していない。 –

関連する問題