P
P
p-oleg2018-09-10 17:42:57
Java
p-oleg, 2018-09-10 17:42:57

Hibernate - why is the first level cache not working?

From the documentation: The
first level cache is always bound to the session object. Hibernate always uses this cache by default 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<Okof> getOkofList() {
        return em.createQuery("SELECT o FROM Okof o ORDER BY o.code").getResultList();
    }
  ...
}

Testing:
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 the 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

Those. twice called the method with a request - and twice the request went to the database, although it should have been one.
What am I not getting?
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sviato_slav, 2018-09-10
@sviato_slav

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

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

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question