首页 > 解决方案 > 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没有添加到bookbook.author将是null)。但是,我可以访问author日志语句所示的值。添加userbook也可以正常工作。

我想问题是authorRepository.getOne(createBookVM.authorId)返回一个代理对象,而不是 的实例Author,但我不知道如何应对这种情况。

标签: springspring-bootjpaspring-data-jpajhipster

解决方案


而不是使用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);

推荐阅读