我想运行这样的查询 -
"SELECT nextval('sequenceName')"
但在此之前我想检查 sequenceName 在 Hibernate 中是否存在。
最佳答案
这里的答案给了我一个想法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
}
关于java - 检查 hibernate 中是否存在特定序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43138176/