HQL Object Named Parameters

2019-07-10 04:42发布

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?

标签: hql
1条回答
姐就是有狂的资本
2楼-- · 2019-07-10 05:24

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);
查看更多
登录 后发表回答