微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何将 Hibernate 缓存与外部更改同步

如何解决如何将 Hibernate 缓存与外部更改同步

@Entity
@Table(name = "abc")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Abc{

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "sequenceGenerator")
    @SequenceGenerator(name = "sequenceGenerator")
    private Long id;

    @OnetoMany(mappedBy = "Abc")
    @Column(name = "name",nullable = false)
    private String name;

    @Cache
    private List<AbcAccess> accesses = new ArrayList<>();
}
@Entity
@Table(name = "abc_access")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class AbcAccess {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "sequenceGenerator")
    @SequenceGenerator(name = "sequenceGenerator")

    private Long id;

    @Column(name = "name",nullable = false)
    private String name;

    @ManyToOne(optional = false)
    private Abc abc;
}

背景:Spring Boot + Spring JPA (hibernate) + Ehcache,启用二级缓存。

Cacheorg.hibernate.annotations.Cache

配置(用 kotlin 编写):

@Configuration
@EnableCaching
class AbcConifg{


    private val jcacheConfiguration: javax.cache.configuration.Configuration<Any,Any>

    init {
        val ehcache = jHipsterProperties.cache.ehcache

        jcacheConfiguration = Eh107Configuration.fromEhcacheCacheConfiguration(
            CacheConfigurationBuilder.newCacheConfigurationBuilder(
                Any::class.java,Any::class.java,ResourcePoolsBuilder.heap(ehcache.maxEntries)
            )
                .withExpiry(ExpiryPolicyBuilder.timetoLiveExpiration(Duration.ofSeconds(ehcache.timetoLiveSeconds.toLong())))
                .build()
        )
    }

    @Bean
    fun hibernatePropertiesCustomizer(cacheManager: javax.cache.CacheManager) = HibernatePropertiesCustomizer {
        hibernateProperties -> hibernateProperties[ConfigSettings.CACHE_MANAGER] = cacheManager
    }
}

当我从数据库查询 Abc 时,它会将结果缓存到二级缓存中。

现在我在数据库中再插入一个AbcAccess,然后我再次从数据库查询Abc,它只会从缓存中获取结果。而 access 中的 Abc 不是实时的,它错过了一个 access

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。