在休眠中检查特定序列是否存在

时间:2017-03-31 10:15:11

标签: java postgresql hibernate

我想运行这样的查询 -

"SELECT nextval('sequenceName')"

但在此之前我想检查Hibernate中是否存在 sequenceName

1 个答案:

答案 0 :(得分:1)

这里的答案给了我一个想法Check if sequence exists in Postgres (plpgsql), 我不知道这是否是一个完美的解决方案,但您可以使用:

SELECT COUNT(*) 
FROM information_schema.sequences 
WHERE sequence_schema='sch_name' AND sequence_name='sequence_name'

这将给你0(如果不存在)或1(如果存在)。

因此,为了解决您的问题,您必须分两次执行查询,一个用于检查序列是否存在,第二个是选择序列,因此您的代码应如下所示:

String sch_name = "sch_test";
String sequence_name = "sequence_name";

//Check if your sequence exist or not
Query q = createNativeQuery("SELECT COUNT(*) FROM        
                             information_schema.sequences 
                             WHERE sequence_schema='" + sch_name + "' 
                             AND sequence_name='" + sequence_name + "'");

int i = (Integer) q.getSingleResult();
int sequence = 0;

//if the sequence exit it will return 1
if(i == 1){
  //increment your sequence and return the result
  q = createNativeQuery("SELECT nextval('" + sequence_name + "')");
  sequence = (Integer) q.getSingleResult();
}else{
   //sequence not exist
}