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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM