下面的代码是我接触过的后端 REST 服务的一个片段。我想知道如何判断我得到的时间戳是否为空。我通过反复试验了解到,如果 Postgres 数据库中的时间戳为 null,当我将它引入 Java 时,如果它为 null,它将在当前操作时实例化为新的 DateTime。如何根据模型数据动态检查获取和设置空值?
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;
}
最佳答案
查看结果集#wasNull
https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#wasNull()
Reports whether the last column read had a value of SQL NULL.
因此,您可以在 rs.getTimestamp()
之后使用它来检查读取的值是否为 SQL NULL,但请注意,如果是这种情况,ResultSet#getTimestamp 已经返回空引用。
https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#getTimestamp(int)
the column value; if the value is SQL NULL, the value returned is null
您面临的问题是,当您将空引用传递给 DateTime 的构造函数时,它将被解释为现在。
关于java - 如何判断 Java 中 Postgres 的时间戳是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44315844/