0

i have situation on which i try to persist entity with id that depends on the max id value, for example the new entity id will be MAX(id)+1. now i try to use JPA to persist this entity

@Entity
@Table(name = "product")
public class ProductDetails {

    @Id
    @GeneratedValue
    private String id;

i used strategy = GenerationType.AUTO, strategy = GenerationType.IDENTITY,strategy = GenerationType.SEQUENCE,strategy = GenerationType.TABLE none of them work, so i think i can solve it through selecting the max id then +1 and use that value (i did not try it) what i am asking for, is there is any way to handle this situation through JPA or Hibernate.Note:the id columns is not auto-increment and the db doesn't have sequence.

Melad Basilius
  • 3,847
  • 10
  • 44
  • 81

2 Answers2

1

Don't use String as Primary key. if you need id like "ABC123" then take 2 id columns. One as id(int) PK, second as display_id(String). You can auto-generate display_id in database level using trigger.

  • Please understand the issue. How can you get Max(id) if you will take id as String ? – Biraj Sahoo Jun 01 '17 at 13:32
  • i understand the issue, i don't want use Max(id), that is how the SQL is written by another one. i try to figure out solution.i already made the Id as long and strategy = GenerationType.AUTO, did not work – Melad Basilius Jun 01 '17 at 14:26
1

If you use String as a type of your Id you shouldn't use auto-increment cause String is something that can't be incremented since it's not a number type. Just leave @Idand add @GeneratedValue(generator = "uuid") - that should work. Additionally you can add @GenericGenerator(name = "uuid", strategy = "uuid2")

Andrew Petryk
  • 229
  • 2
  • 4