我在JPA实体经理面临一个非常奇怪的问题。我有两个实体 1)事件 2)国家
国家是主人,事件是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,但是当我尝试获取同一事件时,国家/地区名称为空。但是,当我重新启动服务器或重新部署应用程序国家/地区名称时也会出现。希望JAP实体管理器存在缓存问题。我尝试在findById方法中使用em.refresh(incident),然后国家名称成功。但是这种刷新方法是非常昂贵的。
请提供一些替代解决方案,如何自动更新jpa缓存。
答案 0 :(得分:0)
在EntityManager em
上,添加
@PersistenceContext(type = PersistenceContextType.TRANSACTION)
private EntityManager em;
使用PersistenceContextType.TRANSACTION
,Spring可以控制EntityManager