I am using JPA 2.1(with EclipseLink implementation), to get a record from Database. By default it first level cache is enabled, it caches the record in PersistenceContext. If I try to get same record I will get it from first level cache, so no query will be fired on database second time.
Once transaction is over the first level cache will be cleared, and If I try to get same entry one more time, query has to be fired as the cache is cleared and it should come from database but it is not.
At least the query should be fired on database if I close the current entity manager,re-open it, and try to get the record.
Even now second query is not going to database. Once I get the record from the database first time(at this time I can see the select query in console logs), after wards if I try to get one more time, its coming from cache memory(as I can not see the query one more time in console logs, I am pretending that it is coming from cache), no matter what I do(use new transaction or close and re-open entity manager) the first level cache ain't cleared.
The code which I am using is below:
EntityManagerFactory entityManagerFactory=
Persistence.createEntityManagerFactory("01EmployeeBasics");
EntityManager entityManager=entityManagerFactory.createEntityManager();
System.out.println("EM1 : "+entityManager);
entityManager.getTransaction().begin();
System.out.println("Tx1 : "+entityManager.getTransaction());
Employee employee=entityManager.find(Employee.class, 123);
entityManager.getTransaction().commit();
entityManager.close();
entityManager=entityManagerFactory.createEntityManager();
System.out.println("EM2 : "+entityManager);
entityManager.getTransaction().begin();
System.out.println("Tx2 : "+entityManager.getTransaction());
Employee employee2=entityManager.find(Employee.class, 123);
entityManager.getTransaction().commit();
entityManager.close();
entityManagerFactory.close();
Employee class is as below:
package in.co.way2learn;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Employee {
@Id
private int id;
private String name;
private int salary;
public Employee() {
// TODO Auto-generated constructor stub
}
public Employee(int id, String name, int salary) {
super();
this.id = id;
this.name = name;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
System.out.println("Employee.getName()");
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
In database there is a record with id 123.
Now my question is why the first level cache is not cleared??