我有一个持久性类Customer
和CustomerDao
接口。
现在,我想返回客户ID(字符串)的集合。
我正在使用查询注释,并使用fields
指定_id:1
仅返回ID。
这是我所得到的样本,类似/收藏的列表:
{ "_id" : "505a2ebf-3b72-4a52-8b9b-67b86e873719" }
直接代替ID值的列表/集合:
505a2ebf-3b72-4a52-8b9b-67b86e873719
为更好地理解我的意思,请参见以下代码:
持续课程
@Document(collection = "customer")
public class Customer implements Serializable {
@Id
private String id;
// getter and setter
}
Dao界面:
public interface CustomerDao extends MongoRepository<Customer, String> {
...
@Query(value="{}", fields="{_id : 1}")
Collection<String> getCustomerIds();
...
}
服务
public class CustomerService {
@Autowired
private CustomerDao m_customerDao;
...
public Collection<String> getCustomerIds() {
return m_customerDao.getCustomerIds();
}
...
}
有没有更简单的方法来返回ID值的集合/列表?
我在想创建一个类似ProjectedId
的类,它仅包含id
属性...然后不返回Collection<String>
...我将返回一个Collection<ProjectedId>
。但是我认为有很多简单的方法可以做到这一点。
ProjectedId类
public class ProjectedId {
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
将CustomerDao
更改为:
public interface CustomerDao extends MongoRepository<Customer, String> {
...
@Query(value="{}", fields="{_id : 1}")
Collection<ProjectedId> getCustomerIds();
...
}
谢谢!