jsf - Retrieve the id of an Entity object as soon as the entity was instantiated? -
is there way in jpa retrieve id of entity object entity instantiated? e.g person person = new person();
currently using in entity class following strategy: @generatedvalue(strategy = generationtype.identity)
if not there "dummy id" strategy having dummyid e.g -10 etc before actual primary key set table in database? please note primary key in mysql db set autoincrement.
the reason need able add new entities in lists , sort them using there id in jsf datatables before persisting them in db.
there no way retrieve id before persisting - because has no id until persist entity. has nothing strategy. has concurrence.
but can add own temporary key use case:
@entity public class person { private static final atomiclong counter = new atomiclong(); @id @generatedvalue(strategy = generationtype.identity) private long id; private final transient long tempid = counter.decrementandget(); public long getidforcomparison() { return id == null ? tempid : id; } }
remember counter
decrease every created object - instantiated jpa provider. if count new (unpersisted) objects, or worried time of atomic counter, should use different constructor jpa:
@entity public class person { private static final atomiclong counter = new atomiclong(); @id @generatedvalue(strategy = generationtype.identity) private long id; private transient long tempid; private string name; protected person() { // constructor jpa - nothing do, id attached } public person(string name) { // constructor creation of new objects tempid = counter.decrementandget(); this.name = name; } public long getidforcomparison() { return id == null ? tempid : id; } }
Comments
Post a Comment