0

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
Anthony Tsivarev
  • 881
  • 3
  • 13
  • 25
  • Please provide information about `Model`. What generation type of your id you are using? This question seems similar to yours http://stackoverflow.com/questions/2108178/id-generatedvalue-but-set-own-id-value. – Thor Mar 03 '12 at 07:40

2 Answers2

2

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.

Official documentation here.

Example

@Entity
public class Community extends GenericModel {
    @Id
    public Long id;

    public Community (Long id) {
        this.id = id;
    }
}
mcls
  • 9,071
  • 2
  • 29
  • 28
0

Try not set id on your own, id should be loaded to model after save.

IProblemFactory
  • 9,551
  • 8
  • 50
  • 66