Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Hibernate equivalent of "select 1 from DUAL"?

What is the minimal Hibernate query? Is there an equivalent of "select 1 from DUAL" for Hibernate?

I am writing a healthcheck function and would like to execute a minimal query, but use HQL to keep the code portable (as opposed to using a native query).

like image 579
Ken Liu Avatar asked Oct 21 '11 03:10

Ken Liu


People also ask

What is SELECT 1 in SQL?

The statement 'select 1' from any table name means that it returns only 1. For example, If any table has 4 records then it will return 1 four times.

Can we use select * in HQL?

Keywords like SELECT, FROM, and WHERE, etc., are not case sensitive, but properties like table and column names are case sensitive in HQL.

What does dual mean in mysql?

The DUAL is special one row, one column table present by default in all Oracle databases. The owner of DUAL is SYS (SYS owns the data dictionary, therefore DUAL is part of the data dictionary.) but DUAL can be accessed by every user.


3 Answers

Hibernate's dialects are what translate to the various databases, and there's no "health check" or "validation" query support in the dialects. This kind of thing is normally done by the connection pool, not by Hibernate. See, e.g., DBCP's validation query property.

like image 140
Ryan Stewart Avatar answered Nov 15 '22 09:11

Ryan Stewart


The SQL select 1 from DUAL; is not a very good health check, the only thing you see is a server response that doesn't tell if the data itself is healthy. But if you want to make such a question, just make your own data entity that simulates DUAL and you're in control of the object and you'll stay generic for any RDBMS.

Something like

@Entity
@Table(name="myDual")
public class MyDual implements Serializable {

  @Id
  @Column(name = "id")
  Integer id;

  public Integer getId() {
    return id;
  }

  public void setId(Integer id) {
    this.id = id;
  }

}

Don't forget to use CacheMode.IGNORE or CacheMode.REFRESH to force the query. Otherwise you might check the cache and not the database...

like image 39
Sven Avatar answered Nov 15 '22 08:11

Sven


Dynamic native sql query will work for it. for example - session.createSQLQuery("Select 1 from dual").uniqueResult();

Also you can query with an existing table like

session.createQuery("select 1 from existingTable").setMaxResults(1).uniqueResult();
like image 33
Raj Avatar answered Nov 15 '22 07:11

Raj