SpringBoot之Jpa的getOne(ID id)方法

  • 使用该方法根据主键ID获取对象时
public News find(Long id){
    return newsRepository.getOne(id);
}
  • 服务器端会报错
{
    "timestamp": "2019-07-30T06:29:40.915+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "Cannot call isReadOnlyBeforeAttachedToSession when isReadOnlySettingAvailable == true [cn.maidaotech.springbootdemo.news.model.News#10001]",
    "path": "/news/news"
}
  • 查看getOne方法的源码
/**
 * Returns a reference to the entity with the given identifier. Depending on how the JPA persistence provider is
 * implemented this is very likely to always return an instance and throw an
 * {@link javax.persistence.EntityNotFoundException} on first access. Some of them will reject invalid identifiers
 * immediately.
 *
 * @param id must not be {@literal null}.
 * @return a reference to the entity with the given identifier.
 * @see EntityManager#getReference(Class, Object) for details on when an exception is thrown.
 */
T getOne(ID id);
  • 发现该方法返回的是实体对象的代理对象(a reference)。
  • 怎么办呢?CrudRepository接口中有一个findById()方法,源码如下:
/**
 * Retrieves an entity by its id.
 *
 * @param id must not be {@literal null}.
 * @return the entity with the given id or {@literal Optional#empty()} if none found
 * @throws IllegalArgumentException if {@code id} is {@literal null}.
 */
Optional<T> findById(ID id);
  • 该方法返回的是Optional ,在Optional类中有个get()方法,返回的是当前对象/值。
  • 我们的代码修改为
public News find(Long id){
    return newsRepository.findById(id).get();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值