2

Is it possible to make an attribute (not primary key) as a @GeneratedValue(strategy = GenerationType.AUTO) ?

I've tried that by putting this in my code, but it doesn't work.

@Column(name = "form_rg")
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer rg;

If not how can I deal that ?

Any help please ?

meee meeee
  • 191
  • 1
  • 3
  • 15

1 Answers1

0

It's not possible using Hibernate.

Proof from doc for GeneratedValue class:

@GeneratedValue annotation may be applied to a primary key property or field of an entity or mapped superclass in conjunction with the {@link Id} annotation.

Solutions:

  1. hibernate-jpa-sequence-non-id

  2. Create separate singleton class which will be used to assign non-id property for each entity

Community
  • 1
  • 1
Sergii Shevchyk
  • 38,716
  • 12
  • 50
  • 61
  • When I create an instance of that GeneralSequenceNumber class, will that returns an incremented number or that needs to be saved as a persist row in table to get that number ? – meee meeee Sep 06 '13 at 20:31
  • actually you need at least invoke a method on `GeneralSequenceNumber` entity which sets `id`. For example, `persist` or `save` in Hibernate session – Sergii Shevchyk Sep 06 '13 at 20:36
  • could you explain why do you need this functionality? Is it worth it? – Sergii Shevchyk Sep 06 '13 at 20:38
  • I've created a class which takes an incremented rank to keep a certain order in my web page, so I need to give them an incremented number automatically and that I can edit at any time. This class is related to another classes, so I need it to be an attribute not a primary key. – meee meeee Sep 07 '13 at 07:09
  • IMO, for this purpose it's better to create separate class which will take care of setting incremented value, change it if necessary. You would have more control over rank value and you could create additional functionality with less efforts . – Sergii Shevchyk Sep 07 '13 at 07:14