JOOQ 查询fetch数据有可能为空,所以需要进行判断,但是每次都这么写,感觉太不流畅了。
Last active
January 10, 2020 05:26
-
-
Save upangka/1151b054a083fc14f55a6a40b666bee5 to your computer and use it in GitHub Desktop.
Optional 使用
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.caucoder.optional; | |
import javax.swing.text.html.Option; | |
import java.util.Optional; | |
public class User { | |
public User(Integer id) { | |
this.id = id; | |
} | |
private Integer id; | |
public Integer getId() { | |
return id; | |
} | |
public void setId(Integer id) { | |
this.id = id; | |
} | |
public static void main(String[] args) { | |
User user = new User(3); | |
Optional<User> optionalA = Optional.ofNullable(user); | |
printId(optionalA); | |
user = null; | |
Optional<User> optionalB = Optional.ofNullable(user); | |
printId(optionalB); | |
} | |
/**Output | |
* user存在 | |
* 3 | |
* user不存在 | |
* -1 | |
* | |
*/ | |
public static void printId(Optional<User> optional){ | |
Integer id = optional.map(item->{ | |
System.out.println("user存在"); | |
return item.getId(); | |
}).orElseGet(()->{ | |
System.out.println("user不存在"); | |
return -1; | |
}); | |
System.out.println(id); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment