Is it possible to set a filed in hibernate to have a value generated whenever it is null?
This is not the primary key but business key. Basically I have a container with a barcode field. If no barcode is assigned, generate it automatically (eg, prefix + sequence number).
Is that possible or do I need to create a custom method for accessing the next sequence value?
Have a look at this: Hibernate JPA Sequence (non-Id)
The idea is to create an entity for the generated value BarCode and then use it as a property of your main entity:
@Entity
public class BarCode{
private static final String PREFIX = "PREFIX";
@Id
@GeneratedValue(...)
private Long number;
public String getBarCodeValue(){
return PREFIX + getNumber();
}
}
@Entity
public class MyEntity {
@Id ..
private Long id;
@OneToOne(...)
private BarCode barCode;
public String getBarCodeValue(){
return barCode.getBarCodeValue();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With