HQL Object Named Parameters

百般思念 提交于 2019-12-24 02:33:40

问题


I was wondering if it is possible to retrieve a specific column from an object named parameter in HQL.

Example

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;
    }
}

as you can see I created the product and it has a supplier object within it. So when I do HQL and call

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);

but is it possible to just get product's supplier's name? and not just the whole supplier?


回答1:


Just don't pass a Supplier instance to your query, but pass the supplier's name directly:

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);


来源:https://stackoverflow.com/questions/7011980/hql-object-named-parameters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!