Hibernate jpa获取自增主键Id

项目中使用Spring +Hibernate+jpa。有场景需要保存实体后获取实体的主键进行下一步的操作。
经过查询资料以及参考通过修改主键注解的方式。即

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

实际就是strategy 的修改,查询源码:

public enum GenerationType{
    /**
     * Indicates that the persistence provider must assign
     * primary keys for the entity using an underlying
     * database table to ensure uniqueness.
     */
    TABLE,
    /**
     * Indicates that the persistence provider must assign
     * primary keys for the entity using a database sequence.
     */
    SEQUENCE,
    /**
     * Indicates that the persistence provider must assign
     * primary keys for the entity using a database identity column.
     */
    IDENTITY,
    /**
     * Indicates that the persistence provider should pick an
     * appropriate strategy for the particular database. The
     * AUTO generation strategy may expect a database
     * resource to exist, or it may attempt to create one. A vendor
     * may provide documentation on how to create such resources
     * in the event that it does not support schema generation
     * or cannot create the schema resource at runtime.
     */
    AUTO
}

一共存在4种类型
–AUTO: 主键由程序控制,是默认选项,不设置即此项
–IDENTITY:主键由数据库自动生成,即采用数据库ID自增长的方式,Oracle不支持这种方式
–SEQUENCE:通过数据库的序列产生主键,通过@SequenceGenerator 注解指定序列名,mysql不支持这种方式
–TABLE:通过特定的数据库表产生主键,使用该策略可以使应用更易于数据库移植

在IDENTITY时,实际调用的保存完成后直接取实体即可,例如

User usr=new User ();
usr.setName("tony");
userDao.persist(usr);
sysout(usr.getId());

你可能感兴趣的:(java)