Spring操作MongoDB之Spring黑科技-采用继承MongoRepository接口实现

1.首先看一下MongoRespository接口的API

2.自定义一个实体类

public class LbsLocation implements Serializable {
    private String cityId;
    /**
     * ACC状态 0:关闭 1:开启
     */
    private Integer acc;

    @Id
    private String id;
    /**
     * 角度
     *
     */
    private Integer angle;

    /**
     * 高度
     *
     */
    private Integer height;
    /**
     * 剩余电量
     *
     */
    private Integer electricity;
    /**
     * 终端号
     */
    private String terminalId;

    /**
     * 车辆ID
     */
    @Indexed
    private String vehicleId;

    /**
     * 速度
     *
     */
    private Integer speed;
    /**
     * 状态 0 正常 1:离线 2:异常
     */
    private Integer status;
    /**
     *油门状态 0:正常 1:断油
     */
    private Integer oilState;

    /**
     * 电状态 0:正常 1:断电
     *
     */
    private Integer powerState;

    /**
     * 锁状态 0:正常 1:锁车
     *
     */
    private Integer lockState;
    /**
     * 上报模式
     */
    private Integer reportMod;
    /**
     * 上报间隔
     */
    private Long reportInterval;
    /**
     * 位置 [lng(经度),lat(纬度)]
     */
    @GeoSpatialIndexed(type = GeoSpatialIndexType.GEO_2DSPHERE)
    private Double[] location;
    /**
     * 更新时间
     *
     */
    @Indexed
    private Date time;
    private String imei;
    private String iccid;

}

3.自定义一个仓库接口

public interface LocationDao extends MongoRepository<LbsLocation,String> {
    List<LbsLocation> findByLocationNear(Point point, Distance min, Distance max);
    List<LbsLocation> findByLocationNear(Point point, Distance max);
    List<LbsLocation> findByLocationWithin(Polygon polygon);
}
  1. 根据实体类中的属性进行查询: 
  2. 当需要根据实体类中的属性查询时,MongoRepository提供的方法已经不能满足,我们需要在PersonRepository仓库中定义方法,定义方法名的规则为:find + By + 属性名(首字母大写),
  3. 根据实体类中的属性进行模糊查询: 
  4. 当需要根据实体类中的属性进行模糊查询时,我们也需要在PersonRepository仓库中定义方法,模糊查询定义方法名的规则为:find + By + 属性名(首字母大写) + Like,如:根据姓名进行模糊查询Person 
  5. 带分页的模糊查询,其实是把模糊查询以及分页进行合并,同时我们也需要在PersonRepository仓库中定义方法,定义方法名的规则和模糊查询的规则一致,只是参数不同而已。 

GreaterThan(大于) 
方法名举例:

findByCityIdGreaterThan(int cityId) 

LessThan(小于) 
方法名举例:

findByCityIdLessThan(int cityId) 

Between(在…之间) 
方法名举例:

findByCityIdBetween(int from, int to) 

Not(不包含) 
方法名举例:

findByVehicleIdNot(String vehicleId) 

Near(查询地理位置相近的) 

方法名举例:

List<LbsLocation> findByLocationNear(Point point, Distance max);

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值