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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With