2
我有以下數據模型,並且我想要獲取子列表對象中的特定對象,我知道有可能獲得整個對象列出並通過每個對象,並與搜索ID進行比較,但我想知道是否有可能使用MongoRepository
來做到這一點。Spring-Boot數據MongoDB - 如何獲取特定的超級特定對象的嵌套對象
@Document
public class Host {
@Id
private String id;
@NotNull
private String name;
@DBRef
private List<Vouchers> listVoucher;
public Host() {
}
//Getters and Setters
}
和..
@Document
public class Vouchers {
@Id
private String id;
@NotNull
private int codeId;
public Vouchers() {
}
//Getters and Setters
}
repository類:
public interface HostRepository extends MongoRepository<Host, String> {
List<Host> findAll();
Host findById(String id);
Host findByName(String name);
//How to build the correct query ??????????
List<Vouchers> findVouchersAll();
Vouchers findByVouchersById(String hostId, String voucherId);
}
控制器類:
@RestController
@RequestMapping(value = "api/v1/host")
public class VoucherController {
@Inject
HostRepository hostRepository;
@RequestMapping(value = "/{hostId}/voucher",method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public List<Vouchers> list() {
return hostRepository.findVouchersAll();
}
@RequestMapping(value = "/{hostId}/voucher/{voucherId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Vouchers getOneVoucher(@PathVariable String hostId, @PathVariable String voucherId) {
Vouchers voucher = hostRepository.findByVouchersById(hostId, voucherId);
if (voucher != null) {
return voucher;
} else {
throw new VoucherNotFoundException(String.format("There is no voucher with id=%s", voucherId));
}
}
}
先謝謝了!
你知道如何做到這一點的查詢? –