如何判断Java中Postgres的时间戳是否为空

时间:2017-06-01 19:41:59

标签: java postgresql

以下代码是我所涉及的后端REST服务的片段。我想知道如何判断我得到的时间戳是否为空。我通过试验和错误了解到,如果Postgres数据库中的时间戳为空,那么当我将其带入Java时,如果它为null,它将在当前操作时被实例化为新的DateTime。我该怎么做才能根据模型数据动态检查get和set null?

public List<SubscriptionEntityModel> getAllSubscriptions(PagingInfoDomainModel paging) throws Exception {
    Database db = new Database();

    String stmt = "{call sp_subscriptions_get_all(?, ?)}";

    if(AppConfig.data.isDebug) {
        logger.debug("Running database operation.. " + stmt);
    }

    CallableStatement sproc = db.dbEndpoint.prepareCall(stmt);
    sproc.setInt(1, paging.pageCurrent);
    sproc.setInt(2, paging.pageItemCount);

    ResultSet rs = sproc.executeQuery();

    List<SubscriptionEntityModel> subscriptions = new ArrayList<SubscriptionEntityModel>();
    while(rs.next()) {
        SubscriptionEntityModel subscription = new SubscriptionEntityModel();
        subscription.subscriptionId = rs.getInt("subscription_id");
        subscription.name = rs.getString("name");
        subscription.emailAddress = rs.getString("email_address");
        subscription.phoneNumber = rs.getString("phone_number");
        subscription.organizationId = rs.getInt("organization_id");

        subscription.createdAt = new DateTime(rs.getTimestamp("created_at"));
        subscription.expiredAt = new DateTime(rs.getTimestamp("expired_at"));

        subscriptions.add(subscription);
    }

    sproc.close();
    db.destroy();

    return subscriptions;
}

2 个答案:

答案 0 :(得分:3)

查看ResultSet#wasNull

https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#wasNull()

  

报告最后一列读取的值是否为SQL NULL。

因此,您可以在rs.getTimestamp()之后使用它来检查读取的值是否为SQL NULL,但请注意,如果是这种情况,ResultSet#getTimestamp已经返回空引用。

https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#getTimestamp(int)

  

列值;如果值为SQL NULL,则返回的值为null

您遇到的问题是,当您将null引用传递给DateTime的构造函数时,它将被解释为 now

答案 1 :(得分:1)

java.sql.Timestamp getTimestamp(String columnLabel) throws SQLException;
如果SQL字段为null,则

将返回NULL

问题在于您实例化DateTime对象的方式 使用JodaTime(我给出了这个示例,因为您没有指定使用的库),执行以下代码确实创建了一个具有实际日期时间的DateTime实例:

java.sql.Timestamp timestamp = null;
DateTime dateTime = new DateTime(timestamp);

因此,要解决您的问题,您可以做的是通过结果集检查返回的值 如果不是null,请使用它来创建DateTime对象 否则,请不要使用它并离开null您设置属性DateTime的{​​{1}}字段。

所以不要这样做:

SubscriptionEntityModel

你应该这样做:

subscription.createdAt = new DateTime(rs.getTimestamp("created_at"));