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?

1
  • there is an option to give default value. something like default = '' Have used it for giving default date for one timestamp field. Commented Mar 28, 2013 at 12:46

2 Answers 2

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();
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.