我有一个实体,有两列引用其他表中的同一列。基本上,交易取决于账户:在创建新交易时,将资金从一个账户汇到另一个账户。
帐户:
@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;
...
交易:
@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);
}
...
如果我尝试发布以创建交易(当然我已经创建了帐户):
{
"amount": 111,
"sourceAccount": 1,
"targetAccount": 2
}
我明白了:
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"])
所以我的问题是:我应该检查什么才能修复“无法构造com.livingit.basicbank.model.Account的实例:没有int / Int-argument构造函数/工厂方法从数字反序列化”?
答案 0 :(得分:1)
问题是您发送的json与class TransactionClient {
BigDecimal amount,
Long sourceAccount,
Long targetAccount
}
类不完全匹配。因此你会看到错误
但是你想要实现的是一个有效的场景,可以做到。
一些选择。
创建一个与json匹配的新类(不是Transaction)。喜欢
{
"amount": 111,
"sourceAccount": {
"idaccount" :123123,
..... // All the Non Null fields
},
"targetAccount": {
"idaccount" :45554,
..... // All the Non Null fields
},
}
在后端(控制器或某些服务中),您可以使用此sourceAccount和targetAccount从数据库获取Acccounts,并使用此对象创建一个事务对象并保存。
从前端调用后端获取这些源和目标帐户的帐户(json),然后使用json调用您的事务端点
{{1}}