senior
senior

Reputation: 2276

java how to set an auto increment attribute

In my entity I have this code:

@Entity
@Table(name = "product")
class Product{   
...
    @GeneratedValue(strategy=GenerationType.AUTO)
    int rank;
}

When I try to save an object of type product, in DB, the rank value remains always 0

Can I set an attribute other than the id auto-increment?

Upvotes: 2

Views: 2688

Answers (4)

Carlitos Way
Carlitos Way

Reputation: 3424

The solution proposed by @Alain Cruz, is the way! But it is the half of the answer... You will need:

1) To Modify your rank attribute like this:

@Generated(GenerationTime.INSERT)
@Column(name = "column_name", insertable = false)
Long rank;

2) Create a before insertion trigger that monitors Products entities, checking that if rank comes null, you will change that value for a new value returned by the desired sequence...

I have done this approach to generate special codes using SQL Functions stored in my database... You can find more info here

Upvotes: 1

Zeusox
Zeusox

Reputation: 8468

The following should work and if it does not, then try what comes after:

@Entity
@Table(name = "product")
class Product{   
...
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int rank;
}

public int getId() {
    return id;
}



public void setId(int id) {
    this.id = id;
}

If that does not work, then go to your database and set rank variable to be auto incremented.

Upvotes: 0

Alain Cruz
Alain Cruz

Reputation: 5097

There are different ways to auto generate a value, but they must always be done on the @Id field. If it is not declared, then you won't be able to auto increment your value.

There are different types of strategies to increment your Id. In this blog, you can learn more about them. For your example, IDENTITY should do the trick.

@Entity
@Table(name = "product")
class Product{   

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    int rank;
}

Update

After doing some research, it seems that Hibernate now allows to auto increment other non-id fields, but it uses another annotation for the purpose. I haven't tried it, but maybe it could work. This in case your rank is not your id.

@Generated(GenerationTime.INSERT)
@Column(name = "column_name", insertable = false)
int rank;

Upvotes: 1

@Entity
@Table(name = "product")
class Product{   
...
    @GeneratedValue(strategy=GenerationType.IDENTITY )
    int rank;
}

Upvotes: 0

Related Questions