Hello, unfortunately I seem to have some issues. I have changed my classes to have a OneTomany mappedBy relationship as follows. When testing this in JUnit (see test() method below) it all works fine and I get my collection back. When I use it in my web app it fails; the collection is null!
In the application (web app), I create the readings in one call and I try to read them in another call. I checked the database and all the entities are created (document and readings) but when I try to get the collection of readings null is returned.
I have tried to clear the entity manager in the second call to make sure the reading will be done from the DB but no success.
I have tried to add ManyToOne of the owning side (Readings), added EAGER fetch to the collection no change.
I have tried to persist the document first and then each Reading separately but still no result.
I am guessing this must be an issue with the EntityManager's life cycle but cannot figure out what. I am using Guice injection and Guice persist and should get one EntityManager per request.
Also, please note that in the web app I actually get the documents through a query of this type:
getEntityManager().createQuery("select e from Document e", Document.class).getResultList()
and then loop through the result.
Hope you can help.
Thanks
@Entity
public class Document {
// ID is generated by the database
@Id private long id;
@OneToMany(mappedBy="document")
private ArrayList<Reading> readings = new ArrayList<Reading>();
public long getId() {
return id;
}
public ArrayList<Reading> getReadings() {
return readings;
}
public void addReading(Reading reading) {
this.readings.add(reading);
}
}
@Entity
public class Reading {
// ID is generated by the database
@Id private long id;
private Document document = null;
public Reading(Document document) {
this.document = document;
this.document.addReading(this);
}
public long getId() {
return id;
}
public Document getDocument() {
return document;
}
}
public void test() {
// em is the EntityManager
em.getTransaction().begin();
Document doc = new Document();
// Note that these readings will be added to the
// document in the Reading constructor
Reading reading1 = new Reading(doc);
Reading reading2 = new Reading(doc);
em.persist(doc);
em.getTransaction().commit();
Document tmpDoc = em.find(Document.class, doc.getId());
ArrayList<Reading> readings = tmpDoc.getReadings();
// Both these turn out to be false!
assertTrue(readings != null);
assertTrue(readings.size() == 2);
}