【发布时间】:2017-03-21 04:18:35
【问题描述】:
我在 JPA 实体管理器中遇到了一个非常奇怪的问题。我有两个实体 1) 事件 2) 国家
Country 是 master,Incident 是 ManyToOne 的子节点。
事件.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
}
国家.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;
}
}
当我添加事件时,事件在事件表中使用国家 ID 成功添加,但是当我尝试获取相同的事件时,国家名称为空。但是当我重新启动服务器或重新部署应用程序国家名称时也会出现。希望 JAP 实体管理器存在缓存问题。我尝试在 findById 方法中使用 em.refresh(incident) ,然后国家名称就成功了。但是这种刷新方法调用非常昂贵。
请提出一些替代解决方案,如何自动更新 jpa 缓存。
【问题讨论】:
-
听起来您的事务管理器未能提交插入和刷新会话。
-
那么,我犯了什么错误。可以告诉我吗?
-
你在映射国家字段和的getter是什么?后者与@Transient。从 getter 中删除所有注释。