How to get the auto-increment primary key value in MySQL using Hibernate

若如初见. 提交于 2019-12-04 03:12:00

When you save the hibernate entity, the id property will be populated for you. So if you have

MyThing thing = new MyThing();
...

// save the transient instance.
dao.save(thing);

// after the session flushes, thing.getId() should return the id.

I actually almost always do an assertNotNull on the id of a persisted entity in my tests to make sure the save worked.

Once you're persisted the object, you should be able to call getId() or whatever your @ID column is, so you could return that from your method. You could also invalidate the Hibernate first level cache and fetch it again.

However, for portability, you might want to look at using Hibernate with sequence style ID generation. This will ease the transition away from MySQL if you ever need to. Certainly, if you use this style of generator, you'll be able to get the ID immediately, because Hibernate needs to resolve the column value before it persists the object:

@Id
@GeneratedValue (generator="MY_SEQ")
@GenericGenerator( name = "MY_SEQ",
    strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
    parameters = { 
        @Parameter(name = "sequence_name", value = "MY_SEQ"), 
        @Parameter(name = "initial_value", value = "1"), 
        @Parameter(name = "increment_size", value = "10") }
        )
@Column ( name = "id", nullable = false )
public Long getId () {

        return this.id;
    }

It's a bit more complex, but it's the kind of thing you can cut and paste, apart from changing the SEQUENCE name.

When you are calling a save() method in Hibernate, the object doesn't get written to the database immediately. It occurs either when you try to read from the database (from the same table?) or explicitly call flush(). Until the corresponding record is not inserted into the database table, MySQL would not allocate an id for it.

So, the id is available, but not before Hibernate actually inserts the record into the MySQL table.

If you want, you can get the next primary key independently of an object using:

Session session = SessionFactoryUtil.getSessionFactory().getCurrentSession();
Query query = session.createSQLQuery( "select nextval('schemaName.keySequence')" );

Long key = (Long) query.list().get( 0 );
return key;
kRIdAi uzumaki

Well in case of auto increment generator class, when we use the save() method it returns the primary key (assuming its id). So it returns that particular id, so you can do this

int id = session.save(modelClass);

And return id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!