由于目的,我需要在插入后立即获取对象的ID。我可以解决以下代码:
session.save(Object o) // insert to database findByPorperty( o.property ) // Return the inserted object along with the id
我认为上面的代码还不够,因为会话需要重新打开才能找到对象。所以:
该session.save(对象)返回对象的ID,或者你可以进行保存或者之后调用ID getter方法。
Save()返回值:
Serializable save(Object object) throws HibernateException
返回值:
the generated identifier
Getter方法示例:
UserDetails实体:
@Entity public class UserDetails { @Id @GeneratedValue private int id; private String name; // Constructor, Setters & Getters }
测试ID的逻辑:
Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.getTransaction().begin(); UserDetails user1 = new UserDetails("user1"); UserDetails user2 = new UserDetails("user2"); //int userId = (Integer) session.save(user1); // if you want to save the id to some variable System.out.println("before save : user id's = "+user1.getId() + " , " + user2.getId()); session.save(user1); session.save(user2); System.out.println("after save : user id's = "+user1.getId() + " , " + user2.getId()); session.getTransaction().commit();
此代码的输出:
保存前:用户ID = 0、0
保存后:用户ID = 1、2
根据此输出,您可以看到在保存UserDetails实体之前未设置ID ,一旦保存了实体,则Hibernate为对象设置了ID- user1并且user2
UserDetails
user1
user2