Использование кэша второго уровня Hibernate с проблемой jpaJAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 Использование кэша второго уровня Hibernate с проблемой jpa

Сообщение Anonymous »

Случай, который я хочу воссоздать:
  • Запуск приложения и помещение одной таблицы из базы данных Postgres в кэш
  • Все запросы к этой таблице должны выполняться и использовать кеш второго уровня вместо подключения к БД.
build.gradle:

Код: Выделить всё

dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.hibernate.orm:hibernate-jcache:6.1.6.Final'
implementation 'org.springframework.boot:spring-boot-starter-web'
runtimeOnly 'org.postgresql:postgresql'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
implementation 'org.ehcache:ehcache:3.10.8'
}
application.properties:

Код: Выделить всё

spring.jpa.show-sql=true
spring.jpa.properties.javax.persistence.sharedCache.mode=ENABLE_SELECTIVE
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.generate_statistics=true
spring.jpa.properties.hibernate.cache.use_second_level_cache=true
spring.jpa.properties.hibernate.cache.use_query_cache=true
spring.jpa.properties.hibernate.cache.region.factory_class=
org.hibernate.cache.jcache.JCacheRegionFactory
spring.jpa.hibernate.ddl-auto=none
Инициализация кэша:

Код: Выделить всё

@Configuration
public class CacheConfig {

private final RegionsRepo repo;

public CacheConfig(RegionsRepo repo) {
this.repo = repo;
}

@PostConstruct
public void initCache() {
repo.findAll().forEach(region -> {});
}
}
Аннотации объектов:

Код: Выделить всё

@Entity
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
@Table(name = "regions")
И JpaRepository:

Код: Выделить всё

public interface RegionsRepo extends JpaRepository {

Optional findRegionsByExternalid(Integer id);

@Override
Optional findById(Long aLong);

@Override
@QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
List findAll();
}
После запуска приложение помещает таблицу в кеш спящего режима второго уровня. Журнал:

Код: Выделить всё

 346333 nanoseconds spent acquiring 1 JDBC connections;
0 nanoseconds spent releasing 0 JDBC connections;
73250 nanoseconds spent preparing 1 JDBC statements;
1098084 nanoseconds spent executing 1 JDBC statements;
0 nanoseconds spent executing 0 JDBC batches;
5962251 nanoseconds spent performing 3 L2C puts;
0 nanoseconds spent performing 0 L2C hits;
368667 nanoseconds spent performing 1 L2C misses;
0 nanoseconds spent executing 0 flushes (flushing a total of 0 entities and 0 collections);
68458 nanoseconds spent executing 1 partial-flushes (flushing a total of 0 entities and 0 collections)
когда я вызываю метод репозитория

findById

который переопределен из JpaRepository, я вижу, что оператор JDBC не выполняется, только чистые обращения L2C, что мне и нужно.
Журнал:

Код: Выделить всё

    1277291 nanoseconds spent acquiring 1 JDBC connections;
0 nanoseconds spent releasing 0 JDBC connections;
0 nanoseconds spent preparing 0 JDBC statements;
0 nanoseconds spent executing 0 JDBC statements;
0 nanoseconds spent executing 0 JDBC batches;
0 nanoseconds spent performing 0 L2C puts;
418709 nanoseconds spent performing 1 L2C hits;
0 nanoseconds spent performing 0 L2C misses;
0 nanoseconds spent executing 0 flushes (flushing a total of 0 entities and 0 collections);
0 nanoseconds spent executing 0 partial-flushes (flushing a total of 0 entities and 0 collections)
НО когда я использую собственный, а не переопределенный метод

findRegionsByExternalid

Обращения L2C игнорируются. Журнал:

Код: Выделить всё

742083 nanoseconds spent acquiring 1 JDBC connections;
0 nanoseconds spent releasing 0 JDBC connections;
849083 nanoseconds spent preparing 1 JDBC statements;
2029042 nanoseconds spent executing 1 JDBC statements;
0 nanoseconds spent executing 0 JDBC batches;
670583 nanoseconds spent performing 1 L2C puts;
0 nanoseconds spent performing 0 L2C hits;
0 nanoseconds spent performing 0 L2C misses;
0 nanoseconds spent executing 0 flushes (flushing a total of 0 entities and 0 collections);
0 nanoseconds spent executing 0 partial-flushes (flushing a total of 0 entities and 0 collections)
Не могли бы вы рассказать, что не так с настройкой кэша гибернации в этом случае?
И что мне следует сделать, чтобы спящий режим использовал кеш L2C в нерабочем режиме? -переопределены методы JpaRepository?

Подробнее здесь: https://stackoverflow.com/questions/784 ... -jpa-issue
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «JAVA»