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?
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
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;
@Entity
@Table(name = "product")
class Product{
...
@GeneratedValue(strategy=GenerationType.IDENTITY )
int rank;
}
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.