2

I have this situation where I need to increment a non primary key column upon insert of every new record. This column is not a primary key. However it has unique constraint. How can I use Hibernate Annotations to accomplish auto increment of this particular column? I know it can be done quite easily for primary keys, but I want exactly same thing to be done for a non primary key column (meaning without using @Id annotation?)

--Thanks

Ace
  • 1,501
  • 4
  • 30
  • 49

3 Answers3

1

As far as I can see, you can use the Hibernate specific annotation @Generated. Your field would look something like this:

@Generated(value="GenerationTime.INSERT")
@GenericGenerator(name="fieldGenerator", strategy="sequence")
private X field;

You can read the different types of strategies here.

I'm 90% sure that should work. If it doesn't then let me know.

Community
  • 1
  • 1
JamesENL
  • 6,400
  • 6
  • 39
  • 64
  • Would you be so kind and take a look at this: http://stackoverflow.com/questions/29976363/hibernate-generatedvalue-in-embedded-always-null maybe you can help me here. – Stefan Falk May 01 '15 at 11:27
1

I checked this and Hibernate allow only one auto column (per table) and it must be defined as a key.

In addition to primary key column If you try to use more than one auto column you will get the error :

[error] o.h.t.h.SchemaUpdate - Incorrect table definition; there can be only one auto column and it must be defined as a key.

You can use sequence or table-use as sequence and save the return value as seq.

simple example of table use as sequence:

@Entity(name = "T1")

@Table(name = "t1")

public  class T1 {

    @Id
    @GeneratedValue
    @Column(name = "c_id")
    private Long seqId;

    public Long getseqId() {
        return seqId;
    }

    public void setseqId(Long sId) {
        this.seqId= sId;
    }
}
saintedlama
  • 6,838
  • 1
  • 28
  • 46
Alon Asulin
  • 109
  • 1
  • 3
-1

@Id @GeneratedValue(strategy=GenerationType.AUTO) private int id;

it works fine for me

RidLam
  • 1
  • 3