Jose Ospina
Jose Ospina

Reputation: 2217

Hibernate Criteria Subquery HibernateException: Unknown entity: null

The scope is to get all the Bid elements which have been created by userId and are part of the Project projectId AND for which there exist a Decision, on that Bid for which the Verb.verb String is "accepted".

However, I am getting a

org.hibernate.HibernateException: Unknown entity: null

exception when trying to implement that as the following pair of query and subquery:

DetachedCriteria accepedBidIds = DetachedCriteria.forClass(DecisionOnBid.class, "dec")
        .createAlias("dec.bid", "dec_bid")
        .add(Restrictions.eq("verb.verb", "accepted"))
        .setProjection(Projections.property("dec_bid.id"));

Criteria query = sessionFactory.getCurrentSession().createCriteria(Bid.class).createAlias("cbtion.project","proj");
query.add(Restrictions.and(
        Restrictions.like("creator.id", userId),
        Restrictions.like("proj.id", projectId),
        Subqueries.eq("id", accepedBidIds)));

List<Bid> bids = (List<Bid>) query.list();

These are my entities. I am purposely avoiding bidirectional dependencies.

@Entity
@Table( name = "bids" )
public class Bid {

    @Id
    @GeneratedValue(generator="increment")
    @GenericGenerator(name="increment", strategy = "increment")
    private int id;
    @ManyToOne
    private Cbtion cbtion = new Cbtion();
    @ManyToOne
    private User creator = new User();

    ...
}


@Entity
@Table( name = "cbtions" )
public class Cbtion {

    @Id
    @GeneratedValue(generator="increment")
    @GenericGenerator(name="increment", strategy = "increment")
    private int id;
    @ManyToOne
    private Project project;
    @ManyToOne

    ...
}

@Entity
@Table( name = "decisions_on_bids" )
public class DecisionOnBid extends Decision {

    @ManyToOne
    private Verb verb;
    @OneToOne
    private Bid bid;

    ...
}

I have tried with some combinations of Aliases, but cant get the right one. Any suggestion?

Upvotes: 2

Views: 5365

Answers (1)

Jose Ospina
Jose Ospina

Reputation: 2217

This is what finally worked for me:

DetachedCriteria accepedBidIds = DetachedCriteria.forClass(DecisionOnBid.class, "d")
        .createAlias("d.verb", "d_v")
        .add(Restrictions.eq("d_v.verb", "accept"))
        .createAlias("d.bid", "d_b")
        .setProjection(Projections.property("d_b.id"));

Criteria query = sessionFactory.getCurrentSession().createCriteria(Bid.class,"b")       
        .add(Restrictions.eq("creator.id", userId))
        .createAlias("b.cbtion","b_c")
        .createAlias("b_c.project","b_c_p")
        .add(Restrictions.eq("b_c_p.id", projectId))
        .add(Subqueries.propertyIn("b.id", accepedBidIds));

@SuppressWarnings("unchecked")
List<Bid> bids = (List<Bid>) query.list();

Not all changes are needed. I think the key ones are to use a lot of alieases, and specially the createCriteria(Bid.class,"b") was not clear to me at the beginning.

Upvotes: 8

Related Questions