Search code examples
javahibernatejpaannotationsnamed-query

hibernate 5.4.12.Final "The attribute cacheable is undefined for the annotation type NamedQuery", is cacheable = true not supported?


I am trying to cache the findByName source query so i only look it up once during the session. However when adding cacheable = true to the annotation, Eclipse reports that it does not support the cacheable setting in the annotation. I am using Hibernate 5.4.12.Final

package aware.process.models;

import java.util.List;

import javax.persistence.Cacheable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.Query;
import javax.persistence.Table;

import org.hibernate.Session;

import aware.process.HibernateUtil;
import lombok.Getter;
import lombok.Setter;

@Entity  
@Table(name= "source")  
@Cacheable  
@NamedQuery(query = "Select s from Source s where s.name = :name", name = "findSourceByName", cacheable = true)
@Getter @Setter
public class Source {

    @Id
    private String id;
    private String name;

    public static Source getByName(String parseType) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();

        Query query = session.createNamedQuery("findSourceByName");

        query.setParameter("name", parseType);
        List<Source> sourceList = query.getResultList();

        Source source = (Source) sourceList.get(0);
        session.getTransaction().commit();
        return source;
    }
}

Solution

  • @NamedQuery annotation doesn't have cacheable attribute indeed. Look at the javadoc. So Eclipse shows you this error correctly.

    In order to cache the query, you have 2 options:

    1. Make hint for all queries created from this named query.
    @NamedQuery(
        query = "Select s from Source s where s.name = :name", 
        name = "findSourceByName", 
        hints={@QueryHint(name="org.hibernate.cacheable",value="true")})           
    })
    
    1. Add hint only to specific queries when you create them:
    Query query = session.createNamedQuery("findSourceByName");
    query.setHint("org.hibernate.cacheable", true);