0

I want to have a unique number besides my string id. So I thought I could use Generated from Hibernate but the value is always null.

My entity:

@Entity(name = "user")
public class UserEntity {
    @Id
    @GeneratedValue(generator = "system-uuid")
    @GenericGenerator(name = "system-uuid", strategy = "uuid")
    @Column(updatable = false, nullable = false)
    private String id;

    ....

    @org.hibernate.annotations.Generated(GenerationTime.ALWAYS)
    @Column(name = "identifier_id", insertable = false, updatable = false)
    private Long identifierId;
 }

Could someone please help me?

user1007522
  • 7,858
  • 17
  • 69
  • 113
  • Maybe [this](https://stackoverflow.com/a/60216566/6277104) answer will be helpful. – SternK Dec 14 '20 at 09:37
  • Thank you. But this means that I need to create this table with an sql file? It can't be done via JPA auto generate? – user1007522 Dec 14 '20 at 09:47
  • Looks like yes. To be honest I do not use auto schema generated and as it is suggested in the [documentation](https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#schema-generation) this is no so flexible as incremental migration scripts: *Although the automatic schema generation is very useful for testing and prototyping purposes, in a production environment, it’s much more flexible to manage the schema using incremental migration scripts.* – SternK Dec 14 '20 at 09:55
  • Is there maybe another way to generate something unique for that entity without the need to do it via the database? – user1007522 Dec 14 '20 at 09:57
  • in the official docs you can find how to use java UUID generator https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#identifiers-generators-uuid. You can do it the same way for Long youself. This https://www.baeldung.com/hibernate-identifiers#5-custom-generator can help you (just don't go to the DB and generate Long randomply yourself). It will allow you not to go to the db for generation – Dmitrii Bocharov Dec 14 '20 at 10:08

1 Answers1

2

Thanks to Dmitrii.

I solved this as follows:

@GeneratorType(type = UUIDGenerator.class, when = GenerationTime.INSERT)
@Column(name = "identifier_id")
private String identifierId;


public class UUIDGenerator implements ValueGenerator<String> {
    public String generateValue(Session session, Object owner) {
        return UUID.randomUUID().toString().replace("-", "");
    }
}
user1007522
  • 7,858
  • 17
  • 69
  • 113