spring-data-jpa中的getOne方法与findById方法

在springboot 2.0以上版本中,CrudRepository接口的findOne(T id)方法已经被官方移除。

以前findOne方法如果查询到没有结果就会返回null,2.0版本后出现getOne方法,但是查询到没有结果的时候就会报错,而不是返回null。

慎用getOne方法,选择findById方法代替。
findById方法返回的类型是Optional,进入Optional类中,有两个方法可以解决我们的问题。

	/**
     * If a value is present in this {@code Optional}, returns the value,
     * otherwise throws {@code NoSuchElementException}.
     *
     * @return the non-null value held by this {@code Optional}
     * @throws NoSuchElementException if there is no value present
     *
     * @see Optional#isPresent()
     */
	public T get() {
        if (value == null) {
            throw new NoSuchElementException("No value present");
        }
        return value;
    }

调用这种方法前要进行isPresent()判断,这种方法在value值为null时会抛出异常。

 	@Override
    public String getUserName(Long id) {
        Optional<User> user = userDao.findById(id);
        if (user.isPresent()) {
            return user.get().getUserName();
        } else {
            return "查询无果";
        }
	/**
     * Return the value if present, otherwise return {@code other}.
     *
     * @param other the value to be returned if there is no value present, may
     * be null
     * @return the value, if present, otherwise {@code other}
     */
    public T orElse(T other) {
        return value != null ? value : other;
    }

这种方法在value值为null时可以自定义other值作为返回值。

	@Override
    public User getUser(Long id) {
        return userDao.findById(id).orElse(null);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值