spring - Spring Data JPA:使用通过`JpaRepository.getOne(id)`检索到的对象
问题描述
在使用 JHipster (v6.0.1) Kotlin blueprint (v0.8.0) 生成的 Spring Boot 应用程序中,我有以下 POST 请求处理程序
@PostMapping("/book")
fun createBook(@RequestBody createBookVM: CreateBookVM): ResponseEntity<Book> {
val author = authorRepository.getOne(createBookVM.authorId)
val userLogin = SecurityUtils.getCurrentUserLogin().orElseThrow { RuntimeException("User not logged in") }
val user = userRepository.findOneByLogin(userLogin).orElseThrow { RuntimeException("IMPOSSIBLE: user does not exist in DB") }
val book= Book()
book.author = author // FIXME
book.user = user
log.debug("Author object with id : {}", author.id) // THIS WORKS
val result = bookRepository.save(book)
return ResponseEntity.created(URI("/api/books/" + result.id))
.headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.id.toString()))
.body(result)
}
问题是author
没有添加到book
(book.author
将是null
)。但是,我可以访问author
日志语句所示的值。添加user
到book
也可以正常工作。
我想问题是authorRepository.getOne(createBookVM.authorId)
返回一个代理对象,而不是 的实例Author
,但我不知道如何应对这种情况。
解决方案
而不是使用authorRepository.getOne(createBookVM.binId)
use authorRepository.findById(createBookVM.binId)
。
T getOne(ID id)
返回引用,而不是实体。
/**
* Returns a reference to the entity with the given identifier.
*
* @param id must not be {@literal null}.
* @return a reference to the entity with the given identifier.
* @see EntityManager#getReference(Class, Object)
* @throws javax.persistence.EntityNotFoundException if no entity exists for given {@code id}.
*/
T getOne(ID id);
Optional<T> findById(ID id)
返回一个实体。
/**
* 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);
您也可以authorRepository.findOne(createBookVM.binId)
用于比 jpa 2.xx 更早的版本:
/**
* Retrieves an entity by its id.
*
* @param id must not be {@literal null}.
* @return the entity with the given id or {@literal null} if none found
* @throws IllegalArgumentException if {@code id} is {@literal null}
*/
T findOne(ID id);
推荐阅读
- python - 根据分隔符获取列表中的值
- node.js - package.json 执行与量角器中的其他构建工具执行有什么不同?
- jhipster - 如何使用 jhipster 运行聊天应用程序
- postgresql - 即使已授予权限,也会出现“表 foo 的权限被拒绝”错误
- go - go-routines 的协调和优雅的关闭
- r - 错误:glm.fit:出现数字 0 或 1 的拟合概率
- r - 如何在不接收无效字符错误的情况下聚合字符和数值
- c - 如何将 GtkEntry 小部件设置为仅使用 C 接受数字?
- python - TypeError:尝试求解二次多项式时,无法将序列乘以“numpy.float64”类型的非整数
- javascript - 如何将 WMTS 图层添加到 Openlayers 地图