Languages
[Edit]
EN

Hibernate - force entity to fetch id from database

7 points
Created by:
Frank-van-Puffelen
289

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();

    }
}

 

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