How to check if a table is empty using Hibernate

Using Hibernate, the most efficient way to determine if a table is empty or not empty? In other words, does the table have 0 or more than 0 rows?

I could do the HQL query select count(*) from tablename and then check if the result is 0 or not 0, but this is not optimal, since I would query the database in more detail than I really need.

+4
source share
2 answers

The following SQL is a very efficient way to see if a table contains a row:

 SELECT EXISTS (SELECT NULL FROM tablename) 

I'm not sure how to convert it to HQL - maybe it just works?

+3
source

Many databases are effective at returning the number of records in a table, but if you want to be creative, what about session.createQuery("select 1 from table").setMaxSize(1).list().isEmpty() ?

Or: session.createQuery("select 1 from table").setFetchSize(1).scroll(ScrollMode.FORWARD_ONLY).next() == null

I think this will depend on the database as to which method is the fastest.

+2
source

Source: https://habr.com/ru/post/1311253/


All Articles