1
votes

I have 2 entities.

Transaction:

@Data
@Entity
@NoArgsConstructor
@AllArgsConstructor
@DynamicInsert
@DynamicUpdate
@Table(name = "transaction")
public class Transaction {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @OneToOne
    @JoinColumn(name="currency_id", nullable=false)
    private Currency currency;

Currency:

@Data
@Entity
@NoArgsConstructor
@AllArgsConstructor
@DynamicInsert
@DynamicUpdate
@Table(name = "currency")
public class Currency {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

And REST Controller:

@PreAuthorize("hasRole('ROLE_CLIENT')")
@PostMapping("initTransactions")
public ResponseEntity<Transaction> initTransaction(@RequestBody Transaction transactionInput) {
        Transaction transaction = transactionService.initTransaction(transactionInput);
        return new ResponseEntity<>(transaction, HttpStatus.OK);
}

Then I send

  curl -X POST \
  http://localhost:4000/transaction/initTransactions \
  -H 'content-type: application/json' \
  -d '{
  "currency": "EUR",
}'

And got the error:

JSON parse error: Cannot construct instance of com.payment.transactionservice.domain.Currency (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('EU'); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of com.payment.transactionservice.domain.Currency (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('EUR')\n at [Source: (PushbackInputStream); line: 17, column: 15] (through reference chain: com.payment.transactionservice.domain.Transaction[\"currency\"])

How can I correctly send the request and map it in entity? Should I use specific annotations?

1

1 Answers

2
votes

In the @RequestBody you want to receive a Transaction.

The problem is that you are sending a body not complaint to the Transaction class.

In details the value of the field "currency" that you are sending is a String ("EUR"). While the Transaction expects an object.

Supposing that the field you are sending is called currencyName, you have 2 options:

  1. Change the request body - '{"currency": {"currencyName":"EUR"}}'
  2. Change or Add a field String currencyName to the object Transaction(and change the request body accordingly)