Reputation: 38705
I use Eclipselink as my JPA provider, how can I make a field auto increment?
Upvotes: 5
Views: 16136
Reputation: 981
If you are using mysql (not sure if it works for other DBs) and make the column auto increment from DB side, following code should work
@Column(name = "counter", unique = true, insertable = false, updatable = false)
@Generated(value = GenerationTime.INSERT)
private Long counter;
Upvotes: 0
Reputation: 4941
JPA 2.0 allows you to set auto_increment in a non-id field as long as you define the auto increment column in your schema - Hibernate / EclipseLink will not do it for you:
`non_id` bigint(20) DEFAULT NULL AUTO_INCREMENT,
and then in your entity:
@Column(name = "non_id")
@GeneratedValue
public void setId(Long id) {
this.id = id;
}
will do the trick.
Upvotes: 2
Reputation: 47933
@Harry: unfortunately it looks like that EclipseLink cannot make non-ID fields auto-incremented. But looks like OpenJPA does have this feature:
Upvotes: 1
Reputation: 570385
I just want an auto-increment field for 1 entity.
Yes, I get that, this is what you wrote in your question. But it can be interpreted in several ways and repeating the same thing without clarifying doesn't help much :)
So does Pascal's way work or I have to do what Bytecode suggest, query select (max) counter + 1 from MyEntity, to get the next value, then set it to the design field, the persist?
If you want to increment a field per entity record (e.g. a "counter" for Order
with id=1, another one for Order
with id=2), what I suggested would work.
If you want a behavior similar to a primary key (i.e. an auto-incremented column), it won't. And in that case, standard JPA doesn't offer any particular facility (standard JPA only allows GenereatedValue
on Id
annotated field). The only way I can think of would be to insert another dedicated entity just to get the primary key from it.
Your exact requirement is unclear but I'm assuming you're talking about a random field, not the primary key. In that case, you could maybe use life cycle callbacks methods:
@Entity
public class MyEntity {
...
private int counter;
...
@PrePersist
@PreUpdate
protected void increment() {
counter = counter + 1;
}
}
Upvotes: 2
Reputation: 39
Some JPA impls allow you to set GeneratedValue on the field whether it is PK or not
Upvotes: -1