tags:

views:

1290

answers:

2

I'm using MySQL and have the following entity:

class MyEntity {
    @Id
    @GeneratedValue(strategy=IDENTITY)
    @Column(name="id")
    private Integer id;
}

However, I would still like to be able to set the id manually!

The problem is that INSERT will never insert the id column. E.g., when doing this:

MyEntity e = new MyEntity();
e.setId(15);
em.persist(e);
em.flush();
em.refresh(e);

The following queries will be made:

INSERT INTO myEntities (col1, col2, col3) VALUES (?, ?, ?)
SELECT id, col1, col2, col3 FROM myEntities WHERE (id = 15)

And thus the id will still be auto-generated and the refresh() will result in EntityNotFoundException.

If I don't set @GeneratedValue at all, then this case will work OK, but when the value is autogenerated, LAST_INSERT_ID() won't be called.

Is it at all possible to have id columns settable both manually and automatically, like in MySQL?

+2  A: 

JPA doesn't cater for that scenario (nor does JDO either); it assumes you either set the id yourself, or you generate it using the provided generators. DataNucleus has an extension by adding @Extension(key="strategy-when-notnull", value="true") which will generate the value when you didn't set the "id" value, and use your value if you provided it. Maybe other implementations allow something similar ?

--Andy (DataNucleus)

DataNucleus
Thanks, that's good to know. Do you know if there are any plans to change this in JPA 2?
Jaka Jančar
A: 

With EclipseLink, manually assigning ids will work for TABLE based sequencing and SEQUENCE object sequencing but not with IDENTITY.

Jaka Jančar