0

I need to have an event_number column in my events table, which can uniquely identify each row, but this column is not the @Id of the table. Each event_number must follow some format like EVENT100001,EVENT100002,...

I went through @GeneratedValue annotation and found that this only can be used with @Id columns. But then found this answer but not sure whether it causes any race conditions.

Is there any cleaner way of doing this? Here is my entity

@Entity
@Table(name = "events")
public class Event {

    @Id
    @Access(AccessType.PROPERTY)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(name = "event_number", nullable = false, unique = true)
    private String eventNumber;
}
Raviteja Reddy
  • 109
  • 2
  • 14
  • Should the `eventNumber` value be generated based on the `id`, or it's completely independent. – SternK Jun 14 '21 at 09:24
  • It's completely independent, only requirement is that it should follow the sequence `EVENT100001,EVENT100002,...` and `EVENT100001` should be the starting value. – Raviteja Reddy Jun 14 '21 at 09:27
  • Maybe [this answer](https://stackoverflow.com/a/60216566/6277104) will be helpful – SternK Jun 14 '21 at 09:29
  • This doesn't support the alphanumeric requirement in my case – Raviteja Reddy Jun 14 '21 at 09:32
  • You just should use `MyGenerator implements ValueGenerator`. and then slightly modify `generateValue` by adding a prefix that you need – SternK Jun 14 '21 at 09:47

1 Answers1

0

You can use @GeneratorType annotation.

You should have an implementation of hibernate ValueGenerator. The simple example you can see below.

import org.hibernate.Session;
import org.hibernate.tuple.ValueGenerator;

public class EventGenerator implements ValueGenerator<String> 
{
   public String generateValue(Session session, Object owner)
   {
      return  "EVENT" + session
            .createNativeQuery("select nextval('TST_DATA_SEQ')")
            .getSingleResult();
   }
}

And then you can use it like this:

@GeneratorType(type = EventGenerator.class, when = GenerationTime.INSERT)
@Column(name = "event_number")
private String eventNumber;
SternK
  • 11,649
  • 22
  • 32
  • 46
  • My application is based on mySql and doesn't support sequence, so had to change the strategy on getting unique value. To get the sequence values, I created a table with id column set to autoincrement starting `100001` and wrote a stored procedure which inserts a value into this table and returns the the `LAST_INSERT_ID()`. In the `generateValue` method instead of the call to get next value, I am invoking the stored procedure. Now, I'm facing a new error. Updating the question with more details – Raviteja Reddy Jun 14 '21 at 17:34