Custom auto increment

5

I have to generate an auto increment of type "000"+id , but I can not get to something concrete, my base is this below, I just wanted a light how to do it, I do not need the answer itself. >

@Id
@GeneratedValue                                 
@Column(name = "id", nullable = false)
public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}
    
asked by anonymous 15.10.2014 / 19:09

1 answer

5

There are several options. One idea is to create an auxiliary computed column at identity in the database (see this article ):

CREATE TABLE MinhaTabela
( 
 DbID INT IDENTITY NOT NULL PRIMARY KEY,
);

CREATE FUNCTION GeraID (@id int) 
RETURNS CHAR(5) 
AS 
BEGIN
RETURN RIGHT('00000' + CONVERT(VARCHAR(10), @id), 5) 
END;

ALTER TABLE MinhaTabela ADD MeuID as DBO.GeraID(DbID);

Hibernate has a (non-standard JPA) annotation to retrieve generated values ( @Generated ).

@Generated(GenerationTime.INSERT) 
@Column(name = "MeuID", insertable = false)
String meuID;

If you do not want to use anything specific to Hibernate you will need to make a refresh of your entity after persisting to get the computed column.

Some other ideas:

15.10.2014 / 20:03