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; } }
source share