Home > Enterprise >  Hibernate Second Level Cache - Previously Cached Entities Still being Fetched from DB
Hibernate Second Level Cache - Previously Cached Entities Still being Fetched from DB

Time:08-01

My application is using Hibernate and Hazelcast for the level 2 cache. My setup has two Entities: Country and Address, whereby an Address has a field of type Country.

Country is annotated with @Cache and I can see it is present in the level 2 cache after it has been initially fetched from the DB using findById().

When I fetch the Address entity which has a @ManyToOne link back to a Country (the one in the level 2 cache) - the level 2 cache is not hit to fetch the previously cached Country, why is this?

Country Entity

@Entity(name = "country")
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Country implements Serializable {

    private int countryId;
    private String name;

    @Id
    @Column(name = "country_id")
    public int getCountryId() {
        return countryId;
    }

    public void setCountryId(int countryId) {
        this.countryId = countryId;
    }

    @Basic
    @Column(name = "name")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

Address Entity

@Entity(name = "address")
public class Address {

    private int addressId;
    private Country country;
    
    @Id
    @Column(name = "address_id")
    public int getAddressId() {
        return addressId;
    }

    public void setAddressId(int addressId) {
        this.addressId = addressId;
    }
    
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "country_id")
    public Country getCountry() {
        return country;
    }

    public void setCountry(Country country) {
        this.country = country;
    }
    
}

CodePudding user response:

You have to get one more reference parameter in Country Entity of Address Entity

like this

private Address address;
//getter and setter

CodePudding user response:

When I fetch the Address entity which has a @ManyToOne link back to a Country (the one in the level 2 cache) - the level 2 cache is not hit to fetch the previously cached Country, why is this?

This depends on a few things.

  1. How are you querying/fetching the Address? If you don't use EntityManager#find, you will have to configure the query cache hint: https://docs.jboss.org/hibernate/orm/5.6/userguide/html_single/Hibernate_User_Guide.html#caching-query (for Spring Data, you need to annotate the method with @QueryHint
  2. Did you configure caching properly?
  3. If you use query caching, did you also configure query caching properly?
  • Related