EN
Hibernate - force entity to fetch id from database
7 points
Quick solution:
xxxxxxxxxx
1
import org.springframework.beans.factory.annotation.Autowired;
2
import org.springframework.stereotype.Controller;
3
import org.springframework.transaction.annotation.Transactional;
4
import org.springframework.web.bind.annotation.RequestMapping;
5
import org.springframework.web.bind.annotation.RequestMethod;
6
import org.springframework.web.bind.annotation.ResponseBody;
7
8
import javax.persistence.EntityManager;
9
10
11
public class UserController {
12
13
14
private EntityManager entityManager;
15
16
value = "/users/some-action", method = {RequestMethod.GET}, produces = "text/javascript") (
17
18
// <----------- MUST BE @Transactional to use entityManager.refresh(entity)
19
public String someAction() throws Exception {
20
21
UserEntity userEntity = new UserEntity();
22
23
// id is null
24
Long idBefore = userEntity.getId();
25
26
entityManager.refresh(userEntity); // <-----------
27
28
// id is not null
29
Long idAfter = userEntity.getId();
30
31
}
32
}