0

I would like to create a mapping service using JPA. The mapping is simple, I have one key (String) for one value (Long). The keys are computed values (so it cannot be autogenerated) and are unique. The only operations that will be executed is findById(String key) and save(MyMapping mapping). What I want is, when I save a new mapping, I just need to give the key, and the value would be autogenerated using autoincrement.

What is the best way to implement this ? Is there a @GeneratedValue for value columns?

JPA version : jakarta.persistence:jakarta.persistence-api:2.2.3

My mapping entity :

@Entity
public class MyMapping {
    @Id
    String key;

    Long value; // must be unique and autoincremented value
}
DwightMint
  • 48
  • 5
  • Why not let database deal with that? Something like Sequence. Also you can check this: https://stackoverflow.com/questions/2595124/how-does-the-jpa-sequencegenerator-annotation-work – pringi Feb 11 '22 at 10:59
  • 1
    A simple Question: If both, key and value are unique, isn't it then just a matter of opinion wich one of them should function as "key"? Why don't you just take the Long "value" as an ```@Id``` and use ```@GeneratedValue``` for it. You can still add an ```@Index``` for the String field. – frank Feb 11 '22 at 12:25
  • @pringi yes I thought about it, but the "value" field is not annoted with `@Id` so I cannot use it here – DwightMint Feb 11 '22 at 13:37
  • @frank Yes they are both unique but I only know the `key` value. In terme of performance is it the same if I annotate the `value` with `@Id` and the `key` with `@Index` to retrieve the element ? – DwightMint Feb 11 '22 at 13:42
  • 1
    Only reason you might be choosy on which you mark as the ID for JPA is that it affects what JPA will need to use for object identity, which affects relationships and caching. JPA requires using the ID as the target of FKs to make cache look-ups easier for providers - but many providers allow FKs to reference non-id columns. The DB though should handle IDs as they do any other field - with an unique index on it. What you specify in JPA as *the* id doesn't even have to match *the* id in the database. Ideally it just needs to be unique. – Chris Feb 11 '22 at 15:19

0 Answers0