在开发MongoDB的REST API过程中,遇到了不少坑。话不多说,直接上。
坑1、为了获取每条数据的"_id"字段时,使用了@Field("_id")注解作为别名。
read时没问题,但会导致MongoRepository的insert方法序列化失败,产生异常“Required identifier property not found for class”。
解决方法:用注解@Id替换@Field
2、create时,不在本地生成ObjectId,而是利用MongoDB自动生成。
cteate方法会序列化对象,如果对象中包含_id字段(见坑1),就会将该字段一起序列化到MongoD中,且其值为空。为了不序列化这个字段,我给它打上注解@Transient。此时序列化倒是没有问题了,但会导致无法获取该字段,例如findById方法返回的对象中_id字段为空。
解决方法:取消@Transient注解,并且在使用insert方法插入数据之前,在本地生成ObjectId即可。代码如下:
/** * Description:CRUD之Create * * @param entity * @return entity * @author example@gmail.com * @Date 2019/1/30 15:40 */ @Override public Entity createEntity(Entity entity) { try { ObjectId objectId = new ObjectId(); intent.setIntentId(objectId.toString()); return intentRepository.insert(intent); } catch (Exception e) { e.printStackTrace(); } return null; }
new ObjectId()会保证生成全局唯一的_id。参考https://www.jianshu.com/p/dd63b93a5955