我正在使用 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);
}
作为新记录保存,生成的新主键在自动增量(db.MySQL)中生成。我希望得到并返回与上述方法相关的新的自动递增值。
更新我!
答案 0 :(得分:5)
试试这个。这也适用于最新的Hibernate(版本4.1)。
session.persist(object);
object.getId();
答案 1 :(得分:2)
保存方法应该返回生成的ID:
http://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/Session.html#save(java.lang.Object)
答案 2 :(得分:0)
//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;
}