java - 序列 "testsequence"尚未在此 session 中的 postgresql java 中定义

标签 java postgresql jdbi

我正在使用带有 google juice 作为注入(inject)器的 java 应用程序以及作为数据库层的 jdbi。我需要使用 java 代码从数据库中获取序列。

我在数据库中有应用程序的表,未使用哪个序列。但出于其他目的,我需要序列值作为当前、下一个和最后一个。

尽管以下查询在 pg-admin 中有效

select currval('testsequence'); 

select nextval('testsequence'); 

select last_value FROM testsequence;

代码如下。

public long getCurrentSequenceFromDB()
{
    LOGGER.info("SequenceHelper :getCurrentSequenceFromDBSTART");
    try (Handle handle = jdbi.open())
    {
        SequenceDAO squenceDAO = handle.attach(SequenceDAO.class);
        long sequence = squenceDAO.getCurrentSequence();
        if (sequence != 0)
        {
            LOGGER.info("SequenceHelper :getCurrentSequenceFromDBEND");
            return sequence;
        }
        else
        {
            LOGGER.info("SequenceHelper :getCurrentSequenceFromDBsequence sequence is null");
            return 0;
        }

    }
    catch (Exception e)
    {
        LOGGER.error("Error in getting sequence from database", e);
        throw new SignageServiceException(ErrorCodes.UNEXPECTED_ERROR, "Error in getting sequence from database", e);
    }
}

在查询级别为:

@SqlQuery("select currval('public.testsequence')")
public long getCurrentSequence();

我得到的错误是

Caused by: org.postgresql.util.PSQLException: 
ERROR: currval of sequence "testsequence" is not yet defined in this session

最佳答案

doc

currval

Return the value most recently obtained by nextval for this sequence in the current session. (An error is reported if nextval has never been called for this sequence in this session.) Because this is returning a session-local value, it gives a predictable answer whether or not other sessions have executed nextval since the current session did.

所以您需要先在这个 session 中调用 nextval

否则,如果您想要任何 session 的最后一个值,您可以使用

SELECT last_value FROM sequence_name;

关于java - 序列 "testsequence"尚未在此 session 中的 postgresql java 中定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55513869/

相关文章:

Javafx 应用程序在一段时间后自动崩溃

postgresql - PostgreSQL 上的 EF Core 批量删除

postgresql - 将 PostgreSQL 表流式传输到 Google BigQuery

java - Oracle、JDBI @SqlBatch - 获取 INSERT 触及的所有行

java - 欧拉项目#10,java

java - 什么启动了 Connection evictor 线程以及如何避免这些线程累积?

java - 如何在 POJO 中表示集合以在 Grails View 中呈现为选择

sql - 重命名 PostgreSQL 中具有特定列名的所有表中的所有列?

java - JDBI 查询返回 MSSQL datetimeoffset(4) 列的错误值?

mysql - 使用 JDBI SQL 对象 API 同时检索或创建新行