Koz
Koz

Reputation: 151

How to give an alias to the resulting rows of a subquery in Hibernate?

Example classes:

public Class Order{
    private Integer id;
    private Customer customer;
}

public Class Customer{
    private Integer id;
    private String name;
}

Example query that I want to execute in PostgreSQL syntax:

SELECT order_alias.id 
FROM (select * from order where customer is not null) order_alias 
WHERE order_alias.customer < 10;

How can I do this in Hibernate?

The reason I'm asking this is because Hibernate seems to be throwing an "Unknown entity: null" error when the customer property is null.

This is what I was trying to do with Criteria:

DetachedCriteria dc = DetachedCriteria.forClass(Order.class, "o");
dc.add(Restrictions.lt("o.customer.id", 10);
dc.setProjection(Projections.property("o.id");

Criteria query = Session.createCriteria(OtherClass.class, "oc");
query.add(Subqueries.propertyIn("oc.id", dc);
List<OtherClass> listOC = query.list();

And I was getting an error which seemed to be coming from line 2.

Upvotes: 2

Views: 2695

Answers (1)

StanislavL
StanislavL

Reputation: 57421

You can define alias and use it. Like this

DetachedCriteria dc = DetachedCriteria.forClass(Order.class, "o");
dc.createAlias("customer", "customer");
dc.add(Restrictions.lt("customer.id", 10);
dc.setProjection(Projections.property("o.id");

Upvotes: 1

Related Questions