Reputation: 891
How to set id in model? I try this code:
public Community(Long id, ...) {
this.id = id;
....
}
But when I do this:
Communtiy c = new (1, ...);
c.save();
Hibernate say:
Execution exception PersistenceException occured : org.hibernate.PersistentObjectException: detached entity passed to persist: models.Community
Upvotes: 0
Views: 453
Reputation: 9764
You can do this by extending from play.db.jpa.GenericModel
instead of play.db.jpa.Model
. This will allow you to set the primary key manually.
In fact, what Model
does is extend from GenericModel
and because it is very common to do so Model
automatically generates primary keys ( by using @Id @GeneratedValue public Long id
). But if for whatever reason you want to set a custom primary key, then extending from GenericModel
is the way to go.
Example
@Entity
public class Community extends GenericModel {
@Id
public Long id;
public Community (Long id) {
this.id = id;
}
}
Upvotes: 2
Reputation: 9811
Try not set id
on your own, id
should be loaded to model after save.
Upvotes: 0