JPA: how to make auto field increase

I use Eclipselink as my JPA provider, how can I do auto field expansion?

+4
source share
4 answers

I just want an auto-increment field for 1 object.

Yes, I understand, this is what you wrote in your question. But this can be interpreted in several ways and repeating the same thing without specifying does not help much :)

This is how Pascal works, or do I need to do what Bytecode offers, request select (max) counter + 1 from MyEntity to get the next value, then set it to the design field, persist?

If you want to increase the field on an entity record (for example, the โ€œcounterโ€ for Order with id = 1, the other for Order with id = 2), what I suggested would work.

If you want the behavior to look like a primary key (i.e. an auto-incrementing column ), it will not. And in this case, the standard JPA does not offer any particular object (the standard JPA only allows GenereatedValue in the annotated Id field). The only way I can think of is to insert another selected object to get the primary key from it.


Your exact requirement is unclear, but I assume that you are talking about a random field, not a primary key. In this case, you could use lifecycle callback methods:

 @Entity public class MyEntity { ... private int counter; ... @PrePersist @PreUpdate protected void increment() { counter = counter + 1; } } 
+2
source

JPA 2.0 allows you to set auto_increment to a non-id field while you define an auto-increment column in your schema. Hibernate / EclipseLink will not do this for you:

 `non_id` bigint(20) DEFAULT NULL AUTO_INCREMENT, 

and then in your organization:

  @Column(name = "non_id") @GeneratedValue public void setId(Long id) { this.id = id; } 

will do the trick.

+2
source

Some JPA impls allow you to set the GeneratedValue to a field, whether it is PK or not.

-1
source

All Articles