What is the Hibernate equivalent of “select 1 from DUAL”?

浪子不回头ぞ 提交于 2020-01-03 11:57:10

问题


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).


回答1:


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.




回答2:


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...




回答3:


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();



回答4:


For native queries and for DUAL table mapping problem, One need to create query with hibernate

session.createSQLQuery("SELECT 1 from DUAL") 

and not with

session.createQuery("SELECT 1 from DUAL").



回答5:


Hmm, for portability, the select 1 from dual is not going to port to some DBs since they do not have dual. ANSI standard information_schema views would be an option, but there is again no guarentee that all the possible DBs you may work against will have them - but might be better odds.



来源:https://stackoverflow.com/questions/7844798/what-is-the-hibernate-equivalent-of-select-1-from-dual

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!