Languages
[Edit]
EN

Hibernate - force entity to fetch id from database

7 points
Created by:
Frank-van-Puffelen
439

Quick solution:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.persistence.EntityManager;

@Controller
public class UserController {

    @Autowired
    private EntityManager entityManager;

    @RequestMapping(value = "/users/some-action", method = {RequestMethod.GET}, produces = "text/javascript")
    @ResponseBody
    @Transactional // <----------- MUST BE @Transactional to use entityManager.refresh(entity)
    public String someAction() throws Exception {

        UserEntity userEntity = new UserEntity();

        // id is null
        Long idBefore = userEntity.getId();

        entityManager.refresh(userEntity); // <-----------

        // id is not null
        Long idAfter = userEntity.getId();

    }
}

 

Alternative titles

  1. Hibernate / spring jpa - force entity to fetch id from mysql
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join