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"
}
/**
* 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();
}