GhoRdoU MaeMoN
GhoRdoU MaeMoN

Reputation: 63

generate auto-incremented field in java spring data

I need to create a auto-incremented key (not a primary key) to use it as a file-name in spring-data here what i tried:

@NotNull
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "BODY_FILE")
private long bodyFile;

in liquibase:

- column:
     name: BODY_FILE
     type: BIGINT
     autoIncrement: true

but the field bodyfile is always 0.

Upvotes: 1

Views: 3067

Answers (1)

Ayush
Ayush

Reputation: 369

@Generated value will ONLY work with a primary key.

  • It won't work with fields that are not a primary key.
  • It won't even work with the composite primary key.

    But why not generated type can be applied for the non-primary field?

    A possible answer is most of the older version of DB either does not support the AUTO_INCREMENT (Generated value) for the non-primary key field or If they support in a newer version that too has constraints- like for MySQL
    There can be only one AUTO_INCREMENT column per table, it must be indexed, and it cannot have a DEFAULT value.

    So from where this zero comes from in your DB?
    It is because of your datatype 'Long' its default value is getting stored in your DB.

    For more details on @Generated value official documentation

    Upvotes: 2

  • Related Questions