0

I have use case in JPA where I need to increase the quantity or update the existing row with quantity on duplicate insertion of a primary key.

@Table(name = "order_line_exception")
@IdClass(OrderLineExceptionKey.class)
public class OrderLineException

    @Id
    @Column(name = "order_id")
    private long orderId;

    @Id
    @Column(name = "gtin_nbr")
    private String gtinNbr;

    @Id
    @Column(name = "order_line_nbr")
    private short orderLineNbr;

    @Id
    @Column(name = "exception_code")
    private short exceptionCode;

    @Column(name = "exception_qty")
    private int exceptionQty;
}````

increase exceptionQty if same primary key repeated


Ric
  • 37
  • 1
  • 5
  • So you're assuming your primary key will be duplicated - that's impossible. – Andronicus Jan 06 '20 at 06:03
  • @Andronicus That impossible in the database, but it doesn't mean that someone cannot still try to _attempt_ that insert. – Tim Biegeleisen Jan 06 '20 at 06:04
  • 1
    Does this answer your question? [Can Hibernate work with MySQL's "ON DUPLICATE KEY UPDATE" syntax?](https://stackoverflow.com/questions/913341/can-hibernate-work-with-mysqls-on-duplicate-key-update-syntax) – Tim Biegeleisen Jan 06 '20 at 06:05
  • Ach ok, maybe I misunderstood. That entity doesn't have to be written to the database, only one field incremented, right? – Andronicus Jan 06 '20 at 06:06
  • Tim Biegeleisen I am looking for similar type of requirement but can be controlled on repository.save(entity) and not always +1 it should exceptionQty = existingexceptionQty + newexceptionQty – Ric Jan 06 '20 at 06:22
  • This is business logic and should be implemented and testes by your application business code – Simon Martinelli Jan 06 '20 at 08:51

1 Answers1

0

You can use FluentJPA, combined with ON DUPLICATE KEY UPDATE clause.

Konstantin Triger
  • 1,576
  • 14
  • 11