0

I'm using JPA, Hibernate and Postgres. I'd like the code to be as solution neutral as possible, where JPA is a given. My simplified entity looks like this:

@Entity
@Table(name = "example")
public class ExampleEntity  {

    @Id
    @GeneratedValue
    private UUID id;
    
    private String businessId; //format is YYYY000001 where YYYY = current year. Current assumption: number is incrementing and reset every year, number is always filled up with leading 0 to make the key 10 digits
}

I always have a generated UUID as the primary key. The business-id shall only be set if a certain state has been reached and is therefore unrelated to when the entity has been created. I would like the database to take care of the incrementing number.

Preferably I'd like to solve this through JPA, but also see a "dirtier" solution where I fetch the sequence-id and generate the business-key in my logic.

marco
  • 163
  • 1
  • 1
  • 9
  • Maybe [this](https://stackoverflow.com/questions/60198528/is-it-possible-to-have-autoincrement-number-without-it-being-an-id) will be helpful – SternK Feb 18 '21 at 09:15
  • @SternK Thank you for your reply. Both solutions are hibernate specific. The second one seems to fit better. Can this also be done while updating and only once? – marco Feb 18 '21 at 09:25
  • You should just correct [GenerationTime](https://docs.jboss.org/hibernate/orm/5.4/javadocs/org/hibernate/annotations/GenerationTime.html) – SternK Feb 18 '21 at 09:29
  • As for *only once*, it looks like you do not have this option. – SternK Feb 18 '21 at 09:32
  • Once it's set it must be immutable – marco Feb 18 '21 at 09:34
  • `I would like the database to take care of the incrementing number.` - from this point of view I guess that `@Generated` annotation is more suitable for your needs. – SternK Feb 18 '21 at 09:36
  • I don't see how I can make this solution work with only set once and only when I want to set it (neither with insert nor with any update) – marco Feb 18 '21 at 09:45
  • I could use a separate Entity with a OneToOne and then generate the id while inserting. Seems overengineered. There has to be an easier solution. – marco Feb 18 '21 at 10:08

0 Answers0