Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/hibernate/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 休眠手动和自动生成的主键_Sql_Hibernate_Jpa_Orm_Primary Key - Fatal编程技术网

Sql 休眠手动和自动生成的主键

Sql 休眠手动和自动生成的主键,sql,hibernate,jpa,orm,primary-key,Sql,Hibernate,Jpa,Orm,Primary Key,我有一个要求,如果用户为主键输入值,那么我需要在创建实体时使用该值,如果用户不提供值,则需要像R00001一样自动生成主键,R0002等。我想知道我如何实现这一点,以及关于这一点的任何指导尝试利用IdentifierGenerator接口,并定义自己的实现 public class MyEntityIdGenerator implements IdentifierGenerator{ public Serializable generate(SessionImplementor ses

我有一个要求,如果用户为主键输入值,那么我需要在创建实体时使用该值,如果用户不提供值,则需要像R00001一样自动生成主键,R0002等。我想知道我如何实现这一点,以及关于这一点的任何指导

尝试利用
IdentifierGenerator
接口,并定义自己的实现

public class MyEntityIdGenerator implements IdentifierGenerator{

    public Serializable generate(SessionImplementor session, Object object)
            throws HibernateException {
         MyEntity entity = (MyEntity)object;

         if(entity.getId()==null){
            Connection con = session.connection();
            // retrieve next sequence val from database for example

            return nextSeqValue;
         }
    }
}
然后在实体的id字段上添加适当的注释:

@Id
@GenericGenerator(name="myCustomGen", strategy="com.example.MyEntityGenerator")
@GeneratedValue(generator="myCustomGen")