javaoracle-databasejpajpa-2.0

How do I know the id before saving an object in jpa


I have a new object. I want to know id before saving it. Is it possible? Or there is another way for this? I am using jpa as orm and oracle as database.

@Id
@Basic(optional = false)
@Column(name = "ID", nullable = false)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "woTypeSeq")
private Long id;

I have a code field in my entity. If the user doesn't enter a value for the code field, I want to set code as entity's id. If I persist entity, of course i can get id and set code value as id, but this is extra query database.

I want to do something like that

if(entity.getCode()==null) {
   entity.setCode(entity.getId);
   jpaDao.saveOrUpdate(entity);
}

Solution

  • After long researching about this, finally I found a solution.

    In fact, if you use sequence generator in jpa, certainly you cannot obtain entity's id before saving it in database, because next id will be assigned by database sequence.

    There is one way to obtain the id if you use a custom generator, you can get the id before saving. Here is simple implementation:

    public class CustomGenerator extends IdentityGenerator implements Configurable {
    
        private IdentifierGenerator defaultGenerator;
    
        public Serializable generate(SessionImplementor session, Object object) throws HibernateException {
            Long idValue = (Long)defaultGenerator.generate(session, object);
            //idValue will be assigned your entity id
            return idValue;
        }
    
        @Override
        public void configure(Type type, Properties params, Dialect d) throws MappingException {
            DefaultIdentifierGeneratorFactory dd = new DefaultIdentifierGeneratorFactory();
            dd.setDialect(d);
            defaultGenerator = dd.createIdentifierGenerator("sequence", type, params);
        }
    }
    

    Using CustomGenerator for id field:

    @Id
    @Basic(optional = false)
    @Column(name = "ID", nullable = false)
    @GenericGenerator(name = "seq_id", strategy = "com.yoncabt.abys.core.listener.CustomGenerator", parameters = { @Parameter(name = "sequence", value = "II_FIRM_DOC_PRM_SEQ") })
    @GeneratedValue(generator = "seq_id")
    private Long id;