Get generated ID in JPA in pre persist method before commit?

Viewed 1036

The entity has a generic ID generator,

Entity

@Entity
public class Customer {
    @Id
    @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;
    private String name;
    private String email;
    private String token;
    private string filepath;
    private String value;
    
     @PrePersist
    private void prePersistFunction(){

        log.info("PrePersist method called");
        filepath = id+".txt";
        write value to this file (filetpath)
        value = null;
    }

    ...
    //getters
    //equals and hashcode
}

The file path value gets id as null in this case.

How can I get the value of id in preperists since this is a custom genric generator not by database?

Thanks

2 Answers

You can not do that in pre persist. @PrePersist annotated function is executed before persist is called for a new entity. At this point the Id has not been generated yet so you can not compose a field based on it.

You could do that in your custom generator. Your custom generator should have a generate method where you calculate and return the entity Id. You also get access to the entity being persisted so in addition to that you can set the composed field:

@Override
public Serializable generate(SharedSessionContractImplementor session, Object obj) {

    long id = // Calculate new id

    // obj is the entity being persisted whose identifier will be set with calculated id 
    // We can set other fields as well
    Customer customer = (Customer) obj;
    customer.setFilepath(id+".txt");

    return id;
}
Related