Hibernate — why does not the first-level cache?

0 like 0 dislike
12 views
From the documentation:
The first-level cache is always bound to the session object. Hibernate always uses the default this cache and cannot be disabled.

My code.

@Entity @Table(name = "okof") public class Okof { @Id protected Integer id; @Column(name = "name") private String name; public Okof() { } ... } @Repository public class JpaOkofRepositoryImpl implements OkofRepository { @PersistenceContext private EntityManager em; @Override public List getOkofList() { return em.createQuery("SELECT o FROM Okof o ORDER BY o.code").getResultList(); } ... }


Test:
public static void main(String[] args) { try (GenericXmlApplicationContext appCtx = new GenericXmlApplicationContext()) { appCtx.load("spring/spring-app.xml", "spring/spring-db.xml"); appCtx.refresh(); OkofRepository repository = appCtx.getBean(OkofRepository.class); repository.getOkofList(); repository.getOkofList(); } }


In console we see:
Hibernate: /* SELECT o FROM Okof o ORDER BY o.code */ select okof0_.code as code1_1_, okof0_.name as name2_1_ from okof okof0_ order by okof0_.code Hibernate: /* SELECT o FROM Okof o ORDER BY o.code */ select okof0_.code as code1_1_, okof0_.name as name2_1_ from okof okof0_ order by okof0_.code


I.e. twice called a method with a request - and twice the query went to the database, but had one.
What I don't understand?
Thank you.
by | 12 views

1 Answer

0 like 0 dislike
From the documentation:
The first-level cache is always bound to the session object. Hibernate always uses the default this cache and cannot be disabled.


Each call to the repository.getOkofList() in main() creates a new session object. By the time the second call to the repository.getOkofList (), the first session and its cache has already been destroyed.
by

Related questions

0 like 0 dislike
1 answer
0 like 0 dislike
1 answer
0 like 0 dislike
1 answer
asked Mar 25, 2019 by palebluedot
0 like 0 dislike
1 answer
0 like 0 dislike
1 answer
110,608 questions
257,186 answers
0 comments
33,605 users