2015-12-06 26 views
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)); 
     } 
    } 
} 

先謝謝了!

+0

你知道如何做到這一點的查詢? –

回答

1

我認爲有一種方法可以做到這一點,雖然我沒有嘗試過這個,但也許我可以在我如何做到這一點。

首先,我寧願用更靈活的方式使用MongoTemplate來查詢mongodb。 MongoTemplate已經包含在Spring Boot Mongodb數據庫中,看起來你已經在使用該庫了,所以它不是你必須使用的附加庫。在Spring中,有一種方法可以@Autowired MongoTemplate,因此可以快速輕鬆地獲取完成此任務的對象。

隨着mongoTemplate,你會做這樣的事情:

Query query = new Query(); 
query.addCriteria(Criteria.where("listVouchers.id").is("1234")); 
List<Host> host = mongoTemplate.find(query, Host.class); 

請參閱文檔在這裏:https://docs.mongodb.org/manual/tutorial/query-documents/

相關問題