Reputation: 2714
I've got a problem to persist an Entity and to get the id after the persist happened. I can see that the data was created in the database, with the right id, but the id is still null at the object.
Heres my entity:
@Entity
public class Bookmark {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private String name;
@Column(nullable = false)
@Temporal(TemporalType.DATE)
private Date createdAt;
@ManyToOne
private Page page;
@ManyToOne
private Color color;
@ManyToOne
private User user;
...
..
And here is my Code where I Create the Entity:
//init bookmark from json basic data
Bookmark bookmark = new Bookmark(currentUser,page);
bookmark.setName(name);
bookmark.setColor(color);
//set User relationship for the bookmark
currentUser.getBookmarks().add(bookmark);
//save the altered entities
tx.begin();
em.merge(currentUser);
em.persist(bookmark);
tx.commit();
//Build the response
System.out.println("uriInfo:"+uriInfo+ "bookmark:"+bookmark);
URI bookmarkUri = uriInfo.getAbsolutePathBuilder().path(bookmark.getId().toString()).build();
I'm getting a nullpointer Exception at the last line because getId() results in null. How can i avoid that?
Upvotes: 3
Views: 2642
Reputation: 2714
I fixed the problem. The root of the problem is the order of the commands to persist the bookmark. This is the right order:
em.persist(bookmark);
em.merge(currentUser);
So first of all you have to persist the entity and after that you can merge the entity of the relationships of that entity.
Upvotes: 2
Reputation: 338
I'm not familiar with the Identity PK generation strategy, perhaps you should add @ReturnInsert
to your @Id
column, to force the PK to be returned on insert statements.
Upvotes: 1