开发者

Hibernate criteria question

I have following POJO`s: - Company

  • Node (nodeID, company)

  • User (userID, node)

I want to create where clause(via Cr开发者_JS百科iteria) which will return to me every user for given company. Something like ...

Criteria criteria = session.createCriteria(User.class)
criteria.add(Restrinctions.eq("node.company", someCompanyObject);

But this is not working, so is it possible to do this with criteria class or should use HQL/SQL?

Thanks in advance!


The hibernate documentation says:

By navigating associations using createCriteria() you can specify constraints upon related entities:

List cats = sess.createCriteria(Cat.class)
    .add( Restrictions.like("name", "F%") )
    .createCriteria("kittens")
        .add( Restrictions.like("name", "F%") )
    .list();

Transposed to your problem:

Criteria criteria = session.createCriteria(User.class) 
    .createCriteria( "node" )
    .add( Restrinctions.eq( "company", someCompanyObject) );


You use the id...

Restrinctions.eq("node.company.id", someCompanyObject.id);


What you want is possible with Criteria API. Your code has some errors, but perhaps they are just typos. It is hard to tell what the error is without looking at the table and the hibernate configuration. Try something like this:

Criteria criteria = session.createCriteria(User.class);
List users = criteria.add(Restrictions.eq("node.company", someCompanyObject))
            .list();


And if you want save some code use Seimos at http://github.com/moesio/seimos

As an example, you can use criteria as follows:

Criteria criteria = session.createCriteria(Cat.class);
criteria.add(Restrictions.like(“description”, “Pap”)
  .addOrder(Order.asc(“description”);

Criteria subCriteria = criteria.createCriteria("kind", "kind");
subCriteria.add(Restrictions.eq("description", "persa"));

Criteria anotherSubCriteria = subCriteria.createCriteria("anAssociation","anAssociation");
anotherSubCriteria.add(Restrictions.eq("attribute", "anything"));

criteria.setResultTransformer(new AliasToBeanResultTransformer(Cat.class));

criteria.crateAlias(“kind.anAssociation”, “kind_anAssociation”);

criteria.setProjections(Projections.projectionList()
  .add(Projections.alias(Projections.property(“id”), “id”))
  .add(Projections.alias(Projections.property(“kind.id”, “kind.id”))
  .add(Projections.alias(Projections.property(“kind.anAssocation.attribute”, “kind.anAssociation.attribute”))

List cats = criteria.list();

But if you want save some code, you can use Seimos and code just

Filters filters = new Filters();
filters.add(new Filters(“description”, “Pap”)
  .add(new Filter(“description”))
  .add(new Filter("kind.description", "persa"))
  .add(new Filter("kind.anAssociation.attribute", "anything"));
List<Cat> cats = dao.find(filters);

So, consider use http://github.com/moesio/seimos

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜