4

我正在使用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)。我想获取并返回关于上述方法的新的自动递增值。

让我知道 !

4

3 回答 3

5

试试这个。这也适用于最新的 Hibernate(4.1 版)。

session.persist(object);
object.getId();
于 2015-01-21T11:14:16.653 回答
2

保存方法应该返回生成的 ID:

http://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/Session.html#save(java.lang.Object)

于 2013-08-21T09:55:18.883 回答
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;
    }
于 2018-07-24T14:16:39.800 回答