3

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?

beginner_
  • 7,230
  • 18
  • 70
  • 127
  • there is an option to give default value. something like default = '' Have used it for giving default date for one timestamp field. – vishnu viswanath Mar 28 '13 at 12:46

2 Answers2

1

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();
    }
}
Community
  • 1
  • 1
Balázs Németh
  • 6,222
  • 9
  • 45
  • 60
  • I don't want to generate always. The value can be supplied from the outside and generation is only required if it is not supplied. – beginner_ Apr 04 '13 at 12:14
0

Assign the value for the barcode from the class itself. Try something like this.

int sequencenumber = generateSequence();
String barcode = prefix + sequencenumber;

I haven't tried this out. So I am not sure if this will work. Do try it out.

Also check this out: Setting default values for columns in JPA

Community
  • 1
  • 1
vishnu viswanath
  • 3,794
  • 2
  • 36
  • 47