WANG há 6 anos atrás
pai
commit
85126dbc1f

+ 58 - 0
src/main/java/cn/com/qmth/examcloud/web/helpers/GlobalHelper.java

@@ -0,0 +1,58 @@
+package cn.com.qmth.examcloud.web.helpers;
+
+import java.util.Optional;
+
+import org.springframework.data.repository.CrudRepository;
+
+import cn.com.qmth.examcloud.commons.exception.StatusException;
+import cn.com.qmth.examcloud.commons.util.JsonUtil;
+
+/**
+ * 全局 helper
+ *
+ * @author WANGWEI
+ * @date 2019年3月4日
+ * @Copyright (c) 2018-? http://qmth.com.cn All Rights Reserved.
+ */
+public class GlobalHelper {
+
+	/**
+	 * 获取存在的实体
+	 *
+	 * @author WANGWEI
+	 * @param repo
+	 * @param id
+	 * @param se
+	 * @return
+	 */
+	public static <ID, T> T getPresentEntity(CrudRepository<T, ID> repo, ID id, Class<T> c) {
+		Optional<T> optional = repo.findById(id);
+		if (!optional.isPresent()) {
+			String simpleName = c.getSimpleName();
+			String desc = String.format("%s (ID: %s) is not present", simpleName,
+					JsonUtil.toJson(id));
+			throw new StatusException("122", desc);
+		} else {
+			return optional.get();
+		}
+	}
+
+	/**
+	 * 获取实体(不存在返回null)
+	 *
+	 * @author WANGWEI
+	 * @param repo
+	 * @param id
+	 * @param c
+	 * @return
+	 */
+	public static <ID, T> T getEntity(CrudRepository<T, ID> repo, ID id, Class<T> c) {
+		Optional<T> optional = repo.findById(id);
+		if (!optional.isPresent()) {
+			return null;
+		} else {
+			return optional.get();
+		}
+	}
+
+}