I’m seeing some weird behavior with my web service. I am using jersey for JAXRS and eclipselink for JPA. I suspect the issue is somewhere with JPA. To keep it short, I have 2 entities: History and Challenge.
@XmlRootElement
@Entity
public class History {
@Column
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public long id;
@JoinColumn
@ManyToOne
public Challenge challenge;
public History() {
}
}
@XmlRootElement
@Entity
public class Challenge {
@Column
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public long id;
@Column(length = 255)
public String title;
@Column(length = 1000)
public String description;
public Challenge() {
}
}
All entries for History and Challenge are present in the database and don’t change. Usually, when I query all histories, I get back all the entries, and each History has a Challenge attached. However, sometimes, one or 2 of the history entries have null for the Challenge member (although the db is in perfect order). And if I reload the app inside Tomcat, the query works OK again. Later in time, this bug appears again. So I’m guessing it has something to do with how I use the EntityManager. Here is the code for querying all histories:
public List<History> getHistories() {
EntityManager em = emFactory.createEntityManager();
Query query = em.createQuery("SELECT h FROM History h");
List<History> list = (List<History>) query.getResultList();
em.close();
return list;
}
As I said earlier, the histories and challenges don’t change. However, I have some other entities that refer to History and maybe I am doing something somewhere else that triggers this problem here. Should I call em.clear() or em.flush() in my method? Is it necessary in my case where I create an entity manager for each request?
EclipseLink enables a shared cache by default.
See,
http://wiki.eclipse.org/EclipseLink/FAQ/How_to_disable_the_shared_cache%3F
It seems you have corrupted you objects somehow. Perhaps you did not set the ManyToOne when you created the objects. Or somehow set it to null in your app?