-3

I have java app that uses hibernate orm to work with db? so what is fastest way to check presense of record(mapped to a hibernate object) in db

user590444
  • 4,252
  • 8
  • 36
  • 43

1 Answers1

5

Use entityManager.find.

Example from the docs:

long catId = 1234L;
em.find( Cat.class, new Long(catId) );

Alternatively, count the records:

Integer count = (Integer) session.createQuery("select count(*) from Cats c where c.id = :catId")
                          .setLong("catId", 1234L)
                          .uniqueResult();
boolean exists = count > 0;
dogbane
  • 266,786
  • 75
  • 396
  • 414
  • I do not want select all fields of an object and looking for a simple way of check provided by api – user590444 Apr 26 '12 at 16:21
  • @user590444 "simple way of check provided by api" what?? – maksimov Apr 26 '12 at 16:28
  • if you don't want to select all fields, then select one field - what's the problem? you MUST select at least something from the database to see if a particular record is there - something to return for your WHERE clause. – maksimov Apr 26 '12 at 16:31
  • 2
    Alternatively, count the records. See my update. – dogbane Apr 26 '12 at 16:34
  • DetachedCriteria favorites = DetachedCriteria.forClass(Source.class).setProjection(Projections.rowCount()).add(Restrictions.idEq(request.id().getId())); – user590444 Apr 27 '12 at 10:41
  • In SQL. http://stackoverflow.com/questions/1676551/best-way-to-test-if-a-row-exists-in-a-mysql-table – James P. Aug 12 '13 at 15:49