我想用Java算法实现,该算法查找所有具有参考ID的记录:
| id | unique_id | reference_id | | |
|----|-----------|--------------|---|---|
| 43 | 55544 | | | |
| 45 | 45454 | 43 | | |
| 66 | 55655 | 45 | | |
| 78 | 88877 | 66 | | |
| 99 | 454 | 33 | | |
具有unique_id 55544的记录的预期结果:
| id | unique_id | reference_id | | |
|----|-----------|--------------|---|---|
| 43 | 55544 | | | |
| 45 | 45454 | 43 | | |
| 66 | 55655 | 45 | | |
| 78 | 88877 | 66 | | |
这是此SQL查询的解决方案:
select @ref:=id as id, unique_id, reference_id
from mytable
join (select @ref:=id from mytable WHERE unique_id = 55544)tmp
where reference_id=@ref
我尝试了以下Java代码:
public ResponseEntity<?> get(@PathVariable String id) {
Optional<PaymentTransactions> obj = transactionService.findById(Integer.parseInt(id));
List<PaymentTransactions> finalList = new ArrayList<PaymentTransactions>();
PaymentTransactions tnx = obj.get();
int ref_id = 0;
while(obj != null) {
List<PaymentTransactions> ref_list = transactionService.findByReference_transaction_id(ref_id);
ref_id = ref_list.get(0).getReference_transaction_id();
finalList.addAll(ref_list);
}
return finalList;
}
我尝试了此代码,但无法正常工作。实现此Java代码的适当方式是什么?