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
Asked
Active
Viewed 4,454 times
-3
-
Use your dao to select from the database? I don't really understand the question. – Tim Pote Apr 26 '12 at 16:13
-
p.s. Session factory object is hidden by Hibernate Template – user590444 Apr 26 '12 at 16:15
-
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:17
1 Answers
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
-
-
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
-
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