Reputation: 1178
I have the next test:
public void testAddDonations() throws MalformedURLException, SQLException, DatabaseUnitException {
prepareCategoriesAndProjects();
Project proj = (Project) session.get(Project.class, 1);
Project proj2 = (Project) session.get(Project.class, 2);
DonationLogic donation = new DonationLogic(10000,50);
donation.setProject(proj);
DonationLogic donation2 = new DonationLogic(100000,500);
donation2.setProject(proj2);
session.persist(donation);
session.persist(donation2);
session.flush();
Project proj3 = (Project) session.get(Project.class, 2);
assertEquals(100000, proj3.getDonation());
}
My problem here is when I load at first proj2 from database getDonation is null (no enties are in donations table yet). However when I try to load from database proj3 (the same as proj2), hibernate does not go to database and getDonation is still null. More - tests show that proj2 and proj3 for hibernate is one object. So hibernate does not go to database second time (i think beacuse it thinks it already has object proj2). Can I change this behaviour?
Upvotes: 0
Views: 440
Reputation: 23552
This is the way Hibernate first level cache works. If entities are found in the first level cache, they are not re-read from the database.
To achieve what you want you could:
1) Clear the session after flushing:
session.flush();
session.clear();
This way first level cache will be emptied and entities are re-read from the database when requested.
2) Refresh the entity:
session.refresh(proj2);
This way proj2
is refreshed with the current state from the database (affects proj3
also because it's the same object).
3) And the last, but the best and recommended solution, update both sides of bidirectional associations whenever possible:
donation2.setProject(proj2);
proj2.setDonationLogic(donation2);
Upvotes: 1