Spring Data JPA:使用通过JpaRepository.getOne(id)检索的对象

时间:2019-05-18 21:38:52

标签: spring spring-boot jpa spring-data-jpa jhipster

在用JHipster(v6.0.1)Kotlin蓝图(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的实例,但是我不知道如何应对这种情况。

1 个答案:

答案 0 :(得分:2)

使用authorRepository.getOne(createBookVM.binId)代替使用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);

对于比jpa 2.x.x更旧的版本,您也可以使用authorRepository.findOne(createBookVM.binId)

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