get auto generated key, on save, using hibernate + spring mvc

前端 未结 3 1977
囚心锁ツ
囚心锁ツ 2021-01-14 04:26

I am using Spring MVC + Hibernate

@Resource(name = \"sessionFactory\")
private SessionFactory sessionFactory;

// save
public  int         


        
相关标签:
3条回答
  • 2021-01-14 04:35

    Try this instead. This works with latest Hibernate (version 4.1) also.

    session.persist(object);
    object.getId();
    
    0 讨论(0)
  • 2021-01-14 04:40

    Save method should return generated ID:

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

    0 讨论(0)
  • 2021-01-14 04:55
      //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;
        }
    
    0 讨论(0)
提交回复
热议问题