Koray Tugay
Koray Tugay

Reputation: 23800

How can I make this query work only using JPA (or Hibernate) API?

I have the following method somewhere in my code:

public boolean isFooHere(final Foo foo) {
    final Query query = getCurrentSession().createQuery("SELECT COUNT(*) FROM FooBar WHERE foo_id = " + foo.getId());
    final long count = (Long) query.uniqueResult();
    if (count == 0) {
        return false;
    } else {
        return true;
    }
}

But I think having hardcoded SQL query is not good practice.

How can have the same functionality using only JPA API?

Upvotes: 1

Views: 76

Answers (3)

Gökhan Polat
Gökhan Polat

Reputation: 442

You could use Hibernate Criteria Library.

For Instance;

public Boolean isFooHere(final Foo foo) {

   Criteria criteria = createCriteria();

   criteria.add(Restrictions.eq("foo.id", foo.getId()));

   if(criteria.uniqueResult() != null)
      return true;

   return false;
}

Note that in "foo.id", foo is your db table name.

Upvotes: 1

Koray Tugay
Koray Tugay

Reputation: 23800

This is how I did it:

public boolean isFooHere(final Foo foo) {
    final Criteria criteria = getCurrentSession().createCriteria(FooBar.class);
    criteria.add(Restrictions.eq("foo", foo));
    criteria.setProjection(Projections.rowCount());
    final Long result = (Long) criteria.uniqueResult();
    return result > 0;
}

Upvotes: 0

StanislavL
StanislavL

Reputation: 57381

Something like this. Use class instead of table name in the query and entity field instead of column

Query query = getCurrentSession().createQuery(
        "select count(*) from Foo f where f.id=:id");
query.setLong("id", foo.getId());
Long count = (Long)query.uniqueResult();

Upvotes: 2

Related Questions