I have an entity with two columns refering same column in other table. Basically, a Transaction depends on Account: when creating a new transaction a send money from one account to another.
Account:
@Entity
@Table(name = "accounts")
public class Account implements java.io.Serializable {
private static final long serialVersionUID = 2612578813518671670L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "idaccount", unique = true, nullable = false)
private Long idaccount;
@Column(name = "name", length = 50)
private String name;
@NotNull
@ManyToOne
@JoinColumn(name = "iduser")
private User user;
...
Transaction:
@Entity
@Table(name = "transactions")
public class Transaction {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "idtransaction", unique = true, nullable = false)
private Long idtransaction;
private BigDecimal amount;
@NotNull
@ManyToOne
@JoinColumn(name = "SOURCE_ACCOUNT")
private Account sourceAccount;
@NotNull
@ManyToOne
@JoinColumn(name = "TARGET_ACCOUNT")
private Account targetAccount;
...
TransactionController
@CrossOrigin
@RestController
@RequestMapping("/transaction")
public class TransactionController {
@Autowired
TransactionService transactionService;
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<Transaction> addTransaction(@RequestBody Transaction Transaction) {
transactionService.save(Transaction);
return new ResponseEntity<Transaction>(Transaction, HttpStatus.CREATED);
}
...
If I try post to create a transaction (naturally I have the accounts already created):
{
"amount": 111,
"sourceAccount": 1,
"targetAccount": 2
}
I get:
Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Can not construct instance of com.mycompany.basicbank.model.Account: no int/Int-argument constructor/factory method to deserialize from Number value (1)
at [Source: java.io.PushbackInputStream@63447acf; line: 3, column: 18] (through reference chain: com.mycompany.basicbank.model.Transaction["sourceAccount"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of com.mycompany.basicbank.model.Account: no int/Int-argument constructor/factory method to deserialize from Number value (1)
at [Source: java.io.PushbackInputStream@63447acf; line: 3, column: 18] (through reference chain: com.mycompany.basicbank.model.Transaction["sourceAccount"])
So my question is: what should I check in order to fix "Can not construct instance of com.livingit.basicbank.model.Account: no int/Int-argument constructor/factory method to deserialize from Number"?