From 6176f9ab71c0423a6959b58a9bf5c76cea0df239 Mon Sep 17 00:00:00 2001 From: ZhouXY108 Date: Tue, 30 May 2023 10:16:47 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20OptionalUtil#orElseNull=20?= =?UTF-8?q?=E6=96=B9=E6=B3=95=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../zhouxy/plusone/commons/util/OptionalUtil.java | 15 +++++++++++++++ .../commons/util/SimpleJdbcTemplateTests.java | 12 ++++++------ 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/src/main/java/xyz/zhouxy/plusone/commons/util/OptionalUtil.java b/src/main/java/xyz/zhouxy/plusone/commons/util/OptionalUtil.java index ce27d79..05808a7 100644 --- a/src/main/java/xyz/zhouxy/plusone/commons/util/OptionalUtil.java +++ b/src/main/java/xyz/zhouxy/plusone/commons/util/OptionalUtil.java @@ -23,6 +23,8 @@ import java.util.OptionalLong; import javax.annotation.Nullable; +import com.google.common.annotations.Beta; + /** * OptionalUtil * @@ -119,6 +121,19 @@ public class OptionalUtil { return optionalOf(objectOptional.orElse(null)); } + /** + * return the value of the optional object if present, + * otherwise {@code null}. + * + * @param the class of the value + * @param optionalObj {@link Optional} object, which must be non-null. + * @return the value of the optional object if present, otherwise {@code null}. + */ + @Beta + public static T orElseNull(Optional optionalObj) { + return optionalObj.orElse(null); + } + private OptionalUtil() { throw new IllegalStateException("Utility class"); } diff --git a/src/test/java/xyz/zhouxy/plusone/commons/util/SimpleJdbcTemplateTests.java b/src/test/java/xyz/zhouxy/plusone/commons/util/SimpleJdbcTemplateTests.java index ea24484..ec55599 100644 --- a/src/test/java/xyz/zhouxy/plusone/commons/util/SimpleJdbcTemplateTests.java +++ b/src/test/java/xyz/zhouxy/plusone/commons/util/SimpleJdbcTemplateTests.java @@ -97,12 +97,12 @@ class SimpleJdbcTemplateTests { final String sql = "INSERT INTO test_table(id, created_by, create_time, updated_by, update_time, status) VALUES(?, ?, ?, ?, ?, ?)"; final List params = recordList.stream() .map(r -> new Object[] { - r.getValueAsString("id").orElse(null), - r.getValueAsString("created_by").orElse(null), - r.getValueAsString("create_time").orElse(null), - r.getValueAsString("updated_by").orElse(null), - r.getValueAsString("update_time").orElse(null), - r.getValueAsString("status").orElse(null) + OptionalUtil.orElseNull(r.getValueAsString("id")), + OptionalUtil.orElseNull(r.getValueAsString("created_by")), + OptionalUtil.orElseNull(r.getValueAsString("create_time")), + OptionalUtil.orElseNull(r.getValueAsString("updated_by")), + OptionalUtil.orElseNull(r.getValueAsString("update_time")), + OptionalUtil.orElseNull(r.getValueAsString("status")) }) .collect(Collectors.toList()); try (Connection conn = this.dataSource.getConnection()) {