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 findById(ID id);
  • 该方法返回的是Optional ,在Optional类中有个get()方法,返回的是当前对象/值。
  • 我们的代码修改为
public News find(Long id){
    return newsRepository.findById(id).get();
}

你可能感兴趣的:(java,jquery,leetcode,vue,android)