简体   繁体   中英

Get the last inserted record's primary key

I have Entity class named Driver, My primary key generation mechanism is

 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 private Long id; 

Now I need to add "driverCode" attribute to the Driver, It should be unique value with prefix (dri1, dri2), "dri" is the prefix value , key should be the primary key value of the Driver, I want to add the driverCode when the driver is created at first time, To do that I need to get the last inserted Driver's primary key, add one ,and concatenate with the prefix, Can any one tell how to get the last inserted record's primary key before insert a new record, Is there any easy way to this?,

Thank you in advance,

If you flush() your EntityManger , the @Id field will be populated with the value about to be saved to the database, so you don't need to find the last one inserted because you already know the current one being inserted:

EntityManger em;
Driver d = new Driver();
em.persist(d);
em.flush();
long id = d.getId(); // this will give you the current record's id


Also, it is quite tricky, and dangerous, to "get the last inserted id"; it is nowhere near as simple as it seems.

the one that works for me

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId() {
    return id;
}

then you can

object.getId();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM