最近项目初期使用的是关系数据库Server SQL,后来改为MongoDB。在开发实现CURD操作的REST API的过程中遇到了一些坑,现在记录下来,希望以后留作参考。
首先说一下MongoRepository的继承关系,如下:
MongoRepository继承了PagingAndSortingRepository,
PagingAndSortingRepository继承CrudRepository,
CrudRepository继承Repository,
Repository提供最基本的数据访问功能。
现在说一下遇到的坑。
1、根据记录的_id查询时,与根据其他属性的查询方式不一样
举例如下,现有一个文档Entity,其对应的类为:
@Field("_id")
private String entityId;
@Field("entity")
private String entityName;
当根据类属性entityName查询某条记录时,代码如下:
public interface EntityRepository extends MongoRepository<Entity, String> {
/**
* 查询满足实体名称和条件appId的记录,注意方法名中条件名称要与Entity类中的属性名对应,且用And连接。Like表示模糊查询
*/
List<Entity> findByEntityNameLikeAndAppId(String entityName, String appId);
但是,当根据属性entityId应用上述方法时,却得不到数据,只能使用MongoRepository自己的findById方法,代码如下:
private final EntityRepository entityRepository;
@Autowired
public EntityServiceImpl(EntityRepository entityRepository) {
this.entityRepository = entityRepository;
}
@Override
public Entity readEntityById(String entityId, String appId) {
Optional optional = entityRepository.findById(entityId);
if(optional.isPresent()){
Object object = optional.get();
if(object instanceof Entity){
return (Entity)object;
}
}
return null;
}
未完待续。。。