Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hibernate JPA: optional value generation

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?

like image 203
beginner_ Avatar asked Nov 27 '25 16:11

beginner_


1 Answers

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();
    }
}
like image 88
Balázs Németh Avatar answered Nov 30 '25 17:11

Balázs Németh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!