使用Criteria API(JPA 2.0)创建查询 [英] Creating queries using Criteria API (JPA 2.0)

查看:107
本文介绍了使用Criteria API(JPA 2.0)创建查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用来自JPA 2.0的Criteria API创建查询,但无法使其正常工作.

I'm trying to create a query with the Criteria API from JPA 2.0, but I can't make it work.

问题在于之间"条件方法.我阅读了一些文档,以了解我该怎么做,但是由于发现了JPA,所以我不明白为什么它不起作用.

The problem is with the "between" conditional method. I read some documentation to know how I have to do it, but since I'm discovering JPA, I don't understand why it does not work.

首先,我看不到当我写"Transaction_"时应该出现的"creationDate".

First, I can't see "creationDate" which should appear when I write "Transaction_."

我认为这可能是正常的,因为我读取了元模型是在运行时生成的,所以我尝试使用"Foo_.getDeclaredSingularAttribute("value")"代替"Foo_.value",但仍然无法正常工作完全没有.

I thought it was maybe normal, since I read the metamodel was generated at runtime, so I tried to use 'Foo_.getDeclaredSingularAttribute("value")' instead of 'Foo_.value', but it still doesn't work at all.

这是我的代码:

public List<Transaction> getTransactions(Date startDate, Date endDate) {
    EntityManager em = getEntityManager();
    try {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Transaction> cq = cb.createQuery(Transaction.class);
        Metamodel m = em.getMetamodel();
        EntityType<Transaction> Transaction_ = m.entity(Transaction.class);
        Root<Transaction> transaction = cq.from(Transaction.class);

        // Error here. cannot find symbol. symbol: variable creationDate
        cq.where(cb.between(transaction.get(Transaction_.creationDate), startDate, endDate));

        // I also tried this:
        // cq.where(cb.between(Transaction_.getDeclaredSingularAttribute("creationDate"), startDate, endDate));

        List<Transaction> result = em.createQuery(cq).getResultList();
        return result;
    } finally {
        em.close();
    }
}

有人可以帮我解决这个问题吗?谢谢.

Can someone help me to figure this out? Thanks.

这是事务处理源(其中几乎没有内容,因为它是由Netbeans从我的数据库中自动生成的)

EDIT : here is the Transaction source (almost nothing in it, since it was automatically generated by Netbeans, from my database)

package projetjava.db;

import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
@Table(name = "transaction")
@NamedQueries({
    @NamedQuery(name = "Transaction.findAll", query = "SELECT t FROM Transaction t"),
    @NamedQuery(name = "Transaction.findById", query = "SELECT t FROM Transaction t WHERE t.id = :id"),
    @NamedQuery(name = "Transaction.findByIDAccount", query = "SELECT t FROM Transaction t WHERE t.iDAccount = :iDAccount"),
    @NamedQuery(name = "Transaction.findByDescription", query = "SELECT t FROM Transaction t WHERE t.description = :description"),
    @NamedQuery(name = "Transaction.findByCreationDate", query = "SELECT t FROM Transaction t WHERE t.creationDate = :creationDate"),
    @NamedQuery(name = "Transaction.findByAmount", query = "SELECT t FROM Transaction t WHERE t.amount = :amount")})
public class Transaction implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "ID")
    private Integer id;
    @Basic(optional = false)
    @Column(name = "IDAccount")
    private int iDAccount;
    @Basic(optional = false)
    @Column(name = "Description")
    private String description;
    @Basic(optional = false)
    @Column(name = "CreationDate")
    @Temporal(TemporalType.DATE)
    private Date creationDate;
    @Basic(optional = false)
    @Column(name = "Amount")
    private double amount;

    public Transaction() {
    }

    public Transaction(Integer id) {
        this.id = id;
    }

    public Transaction(Integer id, int iDAccount, String description, Date creationDate, double amount) {
        this.id = id;
        this.iDAccount = iDAccount;
        this.description = description;
        this.creationDate = creationDate;
        this.amount = amount;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public int getIDAccount() {
        return iDAccount;
    }

    public void setIDAccount(int iDAccount) {
        this.iDAccount = iDAccount;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Date getCreationDate() {
        return creationDate;
    }

    public void setCreationDate(Date creationDate) {
        this.creationDate = creationDate;
    }

    public double getAmount() {
        return amount;
    }

    public void setAmount(double amount) {
        this.amount = amount;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.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 Transaction)) {
            return false;
        }
        Transaction other = (Transaction) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "projetjava.db.Transaction[id=" + id + "]";
    }

}

推荐答案

我认为这可能是正常的,因为我读取了元模型是在运行时生成的(...)

I thought it was maybe normal, since I read the metamodel was generated at runtime (...)

元模型类是在编译时使用注释处理生成的.换句话说,您需要在编译器级别激活注释处理. Hibernate JPA 2元模型生成器文档介绍了如何使用Ant,Maven和Eclipse或Idea等IDE(可以将这种方法转换为其他提供程序)来实现.遗憾的是,NetBeans当前不支持此功能.

Metamodel classes are generated at compile time using annotation processing. In other words, you need to activate annotation processing at the compiler level. The Hibernate JPA 2 Metamodel Generator documentation describes how to do that with Ant, Maven and IDEs like Eclipse or Idea (the approach can be transposed to other providers). Sadly, this feature is currently not supported in NetBeans.

因此,要么使用并配置上述构建工具之一,要么切换到另一个IDE.例如,使用Eclipse,在项目上右键单击,然后转到 Java编译器>注释处理并启用它:

So either use and configure one of the mentioned build tool or switch to another IDE. For example, with Eclipse, right-click on the project and go to Java Compiler > Annotation Processing and Enable it:

然后将提供程序所需的JAR(此步骤请参阅JPA提供程序的文档)添加到工厂路径.

Then add the required JAR(s) of your provider (refer to the documentation of your JPA provider for this step) to the Factory Path.

这篇关于使用Criteria API(JPA 2.0)创建查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆