使用hibernate + spring mvc获取自动生成的密钥

时间:2013-08-21 09:48:00

标签: hibernate spring-mvc get return primary-key

我正在使用 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)中生成。我希望得到并返回与上述方法相关的新的自动递增值。

更新我!

3 个答案:

答案 0 :(得分:5)

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

session.persist(object);
object.getId();

答案 1 :(得分:2)

答案 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;
    }