Custom auto increment

Asked

Viewed 961 times

5

I have to generate an auto increment of the type "000"+id, but I can not get to something concrete, my base is this below, I wanted only a light even of how to do, 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;
}
  • What is your database?

  • sql server 2008

  • 1

    The idea is to put in the end BD, in the field of ID who’s kind Long one String prefixed 000? Or I misunderstood @haykou

  • That, I made another field with the code name but passing public string Getcodigo() { Return code }

1 answer

5


There are several options. One idea is to create an auxiliary computed column to identity in the database (see that 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 an annotation (specific, non-standard JPA) to recover generated values (@Generated).

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

If you do not want to use anything specific to Hibernate it will be necessary to make a refresh of its entity after persisting it to obtain the computed column.


Some other ideas:

  • 1

    For Sql Server 2012 forward, we can use Sequences

Browser other questions tagged

You are not signed in. Login or sign up in order to post.