Issue
What I want to achieve to take auto generated ID, hash it and save it into other field in the class, but at the stage of creating object by constructor ID is not yet generated. Any workaround ideas?
@Entity
public class MyClass {
@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.AUTO)
Long id;
String hashID;
MyClass(){
this.hashID = Utils.hashID(id);
}
//setters and getters
}
```
Solution
One way that I can think of is you can use an entity lifecycle callback event like @PostLoad
which is called when the entity is loaded in the persistence context, and initialize your hashed field from the id.
E.g.
@Entity
public class MyClass {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
Long id;
String hashID;
@PostLoad
public void postLoad() {
// Here id is initialized
this.hashID = Utils.hashID(id);
}
}
Answered By - Osama A.R