Reputation: 3103
I am using Spring MVC + Hibernate
@Resource(name = "sessionFactory")
private SessionFactory sessionFactory;
// save
public <T> int save(T entity) throws DataAccessException {
Session session = sessionFactory.getCurrentSession();
session.save(entity);
}
As New Record Save , New Primary Key generated which in auto increment (db.MySQL). I want to get and return the new auto incremented value with respect to the above method.
Update me !
Upvotes: 4
Views: 5595
Reputation: 1
//assumption: this method is adding a player into database and returns generated player id
//Here player is object of class Player
public int addPlayer(Player player){
int player_id; //variable to store generated ID
Session session = sessionFactory.openSession();
session.beginTransaction();
session.persist(player); //adding player
player_id=player.getplayer_id(); //getplayer_id is the getter method for the variable player_id
session. getTransaction().commit();
session.close();
return player_id;
}
Upvotes: 0
Reputation: 324
Try this instead. This works with latest Hibernate (version 4.1) also.
session.persist(object);
object.getId();
Upvotes: 5
Reputation: 4683
Save method should return generated ID:
http://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/Session.html#save(java.lang.Object)
Upvotes: 2