简体   繁体   English

为什么session.save(object)在休眠状态下不会自动设置ID?

[英]why session.save(object) does not set id automatically in hibernate?

I am using hibernate as a JPA provider for my application and now I have a requirement that I need the id of recently stored request object, but when I do a request.getId it prints null . 我将hibernate用作应用程序的JPA提供程序,现在我需要我需要最近存储的请求对象的ID,但是当我执行request.getId它会输出null

System.out.println("before save : request id's = "+request.getId());   
session.save(request);    
System.out.println("after save : request id's = "+request.getId());

I followed this question . 我遵循了这个问题

Output of this code: 此代码的输出:

before save : request id's = null

after save : reqeust id's = null

public class Request implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

Since the id is generated by the database it will only be there after the entity is actually written. 由于ID是由数据库生成的,因此只有在实际写入实体之后,ID才会存在。 Since hibernate tries to delay the actual write so it might safe some database-hits, session.save() will not necessarily trigger the id-generation. 由于休眠试图延迟实际的写入操作,因此它可能会保护某些数据库命中,因此session.save()不一定会触发ID生成。

Try adding session.flush() after the save and see if the id is populated then. 尝试在保存之后添加session.flush() ,然后查看是否填充了ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM