0

in my object sometimes I need to create Id by myself. How can i tell to JPA to not create ID if there is already one?

@Data
@Builder
@Entity
@Table(name = "steps")
@NoArgsConstructor
@AllArgsConstructor
@EntityListeners(AuditingEntityListener.class)
@SequenceGenerator(name = "seq_steps", sequenceName = "seq_steps", allocationSize = 1)
public class Step implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private UUID id;
}

This is how I created a step object.

var uuid = UUID.fromString("7f173364-1ad9-4e45-94ab-788fb641edb5")
Step step = new Step();
                step.setAction(excelAction.getActionName());
                step.setAction(StepType.STEP.name());
                step.setId(uuid);
                step.setCreatedBy(userName);
                step.setModifiedBy(userName);
                step.setTeam(team);
          

stepRepository.save()

when I check database I see entity saved with different uuid. How can can I force JPA to use my uuid and do you think is it a good approach?

erondem
  • 482
  • 1
  • 11
  • 24
  • Does JPA have a general config for this or should I add this to every class that I need such feature? – erondem Jan 16 '23 at 12:47
  • This is a duplicate, but the linked question doesn't have good answers IMO. Use your own PrePersist method and assign the UUIDs if they aren't there already within it, yourself. JPA will call your pre persist method if the entity is new - note though that if you have an ID within the ID field, Spring's 'save' logic will first try a find query using that ID - so it will query first then call JPA's persist if it isn't found. If you know your entity is new, you can save the overhead and just call persist directly. – Chris Jan 16 '23 at 16:37

1 Answers1

0

You should remove the annotation @GeneratedValue(strategy = GenerationType.AUTO) for id

shashank
  • 65
  • 6