EN
Hibernate - force entity to fetch id from database
7
points
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();
}
}