HQL对象命名参数

时间:2011-08-10 13:57:26

标签: hql

我想知道是否可以从HQL中的名为parameter的对象中检索特定列。

实施例

public class Product
{
    private int id;
    private Supplier supplier;

    private String name;
    private String description;
    private double price;

    public Product()
    {
        super();
    }

    public Product(String name, String description, double price)
    {
        super();
        this.name = name;
        this.description = description;
        this.price = price;
    }

    public String getDescription()
    {
        return description;
    }
    public void setDescription(String description)
    {
        this.description = description;
    }
    public int getId()
    {
        return id;
    }
    public void setId(int id)
    {
        this.id = id;
    }
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }

    public Supplier getSupplier()
    {
        return supplier;
    }
    public void setSupplier(Supplier supplier)
    {
        this.supplier = supplier;
    }

    public double getPrice()
    {
        return price;
    }
    public void setPrice(double price)
    {
        this.price = price;
    }
}

正如您所看到的,我创建了产品,并且其中包含供应商对象。 所以当我做HQL并调用

String hql = "from Product as product where product.supplier=:supplier";
        Query query = session.createQuery(hql);
        query.setEntity("supplier",supplier);
        List results = query.list();
        displayProductsList(results);

但是可以获得产品供应商的名称吗? 而不只是整个供应商?

1 个答案:

答案 0 :(得分:4)

只是不要将供应商实例传递给您的查询,而是直接传递供应商的名称:

String hql = "from Product as product where product.supplier.name = :supplierName";
Query query = session.createQuery(hql);
query.setString("supplierName", supplier.getName());
List results = query.list();
displayProductsList(results);