Hibernate springboot&x2B;hazelcast+;冬眠';s findAll()从数据库而不是缓存中检索数据
我目前正在springboot应用程序(版本1.5.2.RELEASE)中使用hibernate二级缓存和hazelcast 3.7.5。 每当我使用SpringDataJPA实现的findAll()方法时,hibernate都会从数据库中检索数据,但当我使用findOne(id)方法时,hibernate会从chache获取数据。有人能解释这种奇怪的行为吗? 这是我的hibernate配置Hibernate springboot&x2B;hazelcast+;冬眠';s findAll()从数据库而不是缓存中检索数据,hibernate,jpa,caching,spring-boot,hazelcast,Hibernate,Jpa,Caching,Spring Boot,Hazelcast,我目前正在springboot应用程序(版本1.5.2.RELEASE)中使用hibernate二级缓存和hazelcast 3.7.5。 每当我使用SpringDataJPA实现的findAll()方法时,hibernate都会从数据库中检索数据,但当我使用findOne(id)方法时,hibernate会从chache获取数据。有人能解释这种奇怪的行为吗? 这是我的hibernate配置 spring: datasource: url: jdbc:h2:file:./target/h
spring:
datasource:
url: jdbc:h2:file:./target/h2db/db/parametrage;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS PARAM
username: sa
password:
jpa:
open-in-view: false
show-sql: true
hibernate:
ddl-auto: none
naming:
implicit-strategy: org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
properties:
hibernate.default_schema: PARAM
hibernate.id.new_generator_mappings: true
hibernate.cache.use_second_level_cache: true
hibernate.cache.use_query_cache: false
hibernate.generate_statistics: true
hibernate.cache.region.factory_class: com.hazelcast.hibernate.HazelcastCacheRegionFactory
hibernate.cache.hazelcast.instance_name: hazelcast
hibernate.cache.use_minimal_puts: true
hibernate.cache.hazelcast.use_lite_member: true
@Configuration
@EnableCaching
public class CacheConfiguration {
private final Logger log = LoggerFactory.getLogger(CacheConfiguration.class);
private final Environment env;
public CacheConfiguration(Environment env) {
this.env = env;
}
@Bean
public CacheManager cacheManager(HazelcastInstance hazelcastInstance) {
log.debug("Starting HazelcastCacheManager");
CacheManager cacheManager = new HazelcastCacheManager(hazelcastInstance);
return cacheManager;
}
@PreDestroy
public void destroy() {
log.info("Closing Cache Manager");
Hazelcast.shutdownAll();
}
@Bean
public HazelcastInstance hazelcastInstance() {
log.debug("Configuring Hazelcast");
Config config = new Config();
config.setInstanceName("hazelcast");
config.getNetworkConfig().setPort(5701);
config.getNetworkConfig().setPortAutoIncrement(true);
config.getNetworkConfig().getJoin().getAwsConfig().setEnabled(false);
config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false);
config.getNetworkConfig().getJoin().getTcpIpConfig().addMember("localhost").setEnabled(true);
config.getMapConfigs().put("default", initializeDefaultMapConfig());
config.getManagementCenterConfig().
setUrl("http://localhost:8080/mancenter")
.setEnabled(true);
return Hazelcast.newHazelcastInstance(config);
}
private MapConfig initializeDefaultMapConfig() {
MapConfig mapConfig = new MapConfig();
mapConfig.setBackupCount(0);
mapConfig.setEvictionPolicy(EvictionPolicy.LRU);
mapConfig.setMaxSizeConfig(new MaxSizeConfig(0, MaxSizeConfig.MaxSizePolicy.USED_HEAP_SIZE));
return mapConfig;
}
}
这是我的hazelcast配置
spring:
datasource:
url: jdbc:h2:file:./target/h2db/db/parametrage;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS PARAM
username: sa
password:
jpa:
open-in-view: false
show-sql: true
hibernate:
ddl-auto: none
naming:
implicit-strategy: org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
properties:
hibernate.default_schema: PARAM
hibernate.id.new_generator_mappings: true
hibernate.cache.use_second_level_cache: true
hibernate.cache.use_query_cache: false
hibernate.generate_statistics: true
hibernate.cache.region.factory_class: com.hazelcast.hibernate.HazelcastCacheRegionFactory
hibernate.cache.hazelcast.instance_name: hazelcast
hibernate.cache.use_minimal_puts: true
hibernate.cache.hazelcast.use_lite_member: true
@Configuration
@EnableCaching
public class CacheConfiguration {
private final Logger log = LoggerFactory.getLogger(CacheConfiguration.class);
private final Environment env;
public CacheConfiguration(Environment env) {
this.env = env;
}
@Bean
public CacheManager cacheManager(HazelcastInstance hazelcastInstance) {
log.debug("Starting HazelcastCacheManager");
CacheManager cacheManager = new HazelcastCacheManager(hazelcastInstance);
return cacheManager;
}
@PreDestroy
public void destroy() {
log.info("Closing Cache Manager");
Hazelcast.shutdownAll();
}
@Bean
public HazelcastInstance hazelcastInstance() {
log.debug("Configuring Hazelcast");
Config config = new Config();
config.setInstanceName("hazelcast");
config.getNetworkConfig().setPort(5701);
config.getNetworkConfig().setPortAutoIncrement(true);
config.getNetworkConfig().getJoin().getAwsConfig().setEnabled(false);
config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false);
config.getNetworkConfig().getJoin().getTcpIpConfig().addMember("localhost").setEnabled(true);
config.getMapConfigs().put("default", initializeDefaultMapConfig());
config.getManagementCenterConfig().
setUrl("http://localhost:8080/mancenter")
.setEnabled(true);
return Hazelcast.newHazelcastInstance(config);
}
private MapConfig initializeDefaultMapConfig() {
MapConfig mapConfig = new MapConfig();
mapConfig.setBackupCount(0);
mapConfig.setEvictionPolicy(EvictionPolicy.LRU);
mapConfig.setMaxSizeConfig(new MaxSizeConfig(0, MaxSizeConfig.MaxSizePolicy.USED_HEAP_SIZE));
return mapConfig;
}
}
最后这里是一个实体的例子
@Entity
@Table(name = "Banque")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Banque implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "Code")
private Integer code;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 150)
@Column(name = "Designation")
private String designation;
@OneToMany(mappedBy = "codeBanque")
@JsonBackReference
private Collection<Societe> societeCollection;
public Banque() {
}
public Banque(Integer code) {
this.code = code;
}
public Banque(Integer code, String designation) {
this.code = code;
this.designation = designation;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public Collection<Societe> getSocieteCollection() {
return societeCollection;
}
public void setSocieteCollection(Collection<Societe> societeCollection) {
this.societeCollection = societeCollection;
}
@Override
public int hashCode() {
int hash = 0;
hash += (code != null ? code.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Banque)) {
return false;
}
Banque other = (Banque) object;
if ((this.code == null && other.code != null) || (this.code != null && !this.code.equals(other.code))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.csys.parametrage.domain.Banque[ code=" + code + " ]";
}
@实体
@表(name=“Banque”)
@缓存(用法=缓存并发策略。非严格读写)
公共类Banque实现了可序列化{
私有静态最终长serialVersionUID=1L;
@身份证
@GeneratedValue(策略=GenerationType.IDENTITY)
@基本(可选=假)
@列(name=“Code”)
专用整数码;
@基本(可选=假)
@NotNull
@尺寸(最小值=1,最大值=150)
@列(名称=“名称”)
专用字符串指定;
@OneToMany(mappedBy=“codeBanque”)
@JsonBackReference
私人收藏协会收藏;
公共银行(){
}
公共银行(整数代码){
this.code=代码;
}
公共银行(整数代码、字符串名称){
this.code=代码;
这个名称=名称;
}
公共整数getCode(){
返回码;
}
公共无效设置码(整数码){
this.code=代码;
}
公共字符串getDesignation(){
返回指定;
}
公共无效设置名称(字符串名称){
这个名称=名称;
}
公共集合getSocieteCollection(){
归还社会募捐;
}
公共void setSocieteCollection(集合societeCollection){
this.societeCollection=societeCollection;
}
@凌驾
公共int hashCode(){
int hash=0;
hash+=(code!=null?code.hashCode():0);
返回散列;
}
@凌驾
公共布尔等于(对象){
//TODO:警告-如果未设置id字段,此方法将不起作用
if(!(Banque的对象实例)){
返回false;
}
Banque other=(Banque)对象;
if((this.code==null&&other.code!=null)| |(this.code!=null&&!this.code.equals(other.code))){
返回false;
}
返回true;
}
@凌驾
公共字符串toString(){
返回“com.csys.parametrace.domain.Banque[code=“+code+”]”;
}
}我让它起作用了。您需要缓存集合。 我变了
@OneToMany(mappedBy = "codeBanque")
private Collection<Societe> societeCollection;
@OneToMany(mappedBy=“codeBanque”)
私人收藏协会收藏;
到
@Cache(用法=cacheconcurrencysttrategy.NONSTRICT\u READ\u WRITE)
@OneToMany(fetch=FetchType.EAGER,mappedBy=“codeBanque”)
私人收藏协会收藏;
正如尼尔·史蒂文森(Neil Stevenson)在评论中所说,解决方案是使用查询缓存。
为此,i'v将hibernate.cache切换为true,但也将i'v指定为hibernate必须使用@QueryHints
缓存的查询。
这是我的存储库的代码
Repository("BanqueRepository")
public interface BanqueRepository extends JpaRepository<Banque, Integer> {
public Banque findByCode(Integer code);
@Override
@QueryHints({
@QueryHint(name = "org.hibernate.cacheable", value = "true")})
public List<Banque> findAll();
}
存储库(“BanqueRepository”)
公共接口BanqueRepository扩展了JpaRepository{
公共Banque findByCode(整数代码);
@凌驾
@牢骚({
@QueryHint(name=“org.hibernate.cacheable”,value=“true”)}
公共列表findAll();
}
你已经使用了\u query\u cache
falsei'v切换了它,但仍然存在相同的问题。你能发布更多详细信息吗pom.xml
加上任何其他配置文件,如hibernate.cfg.xml
,persistence.xml
。这或一个完整的复制样本将有助于我的目的是得到“Banque”的列表,我找到了一个解决方案,感谢你的第一个评论:)谢谢你男人:D