hibernate 5.4.12.Final "The attribute cacheable is undefined for the annotation type NamedQuery",是否不支持cacheable = true?

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

我正在尝试缓存 findByName 源查询,因此我只在会话期间查找一次。但是,在注释中添加 cacheable = true 时,Eclipse 报告它不支持注释中的可缓存设置。我正在使用 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;
    }
}

@NamedQuery 注释确实没有 cacheable 属性。看看javadoc。所以 Eclipse 正确地向您显示了这个错误。

为了缓存查询,您有 2 个选择:

  1. 为从此命名查询创建的所有查询提供提示。
@NamedQuery(
    query = "Select s from Source s where s.name = :name", 
    name = "findSourceByName", 
    hints={@QueryHint(name="org.hibernate.cacheable",value="true")})           
})
  1. 创建特定查询时仅添加提示:
Query query = session.createNamedQuery("findSourceByName");
query.setHint("org.hibernate.cacheable", true);