Spring数据deleteBy查询不返回删除的对象 [英] Spring data deleteBy query doesnt return deleted object

查看:19
本文介绍了Spring数据deleteBy查询不返回删除的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Spring-data-mongodb中,我们可以像下面这样从存储库的查询方法中返回单个删除的对象

In Spring-data-mongodb, can we return the single deleted object from query method of repository like below

public interface MyRepository extends MongoRepository<MyObject, String>{
 Optional<MyObject> deleteByXAndY(String x, String y);
}

如果总是有单个文档被上述查询删除.

if there will be always single document that's get deleted by above query.

我试过了,但它抛出异常,如无法将 Long 转换为 MyObject.我认为只支持 void、long 或 List 或 Stream.有什么方法可以实现我想要做的事情吗?

I tried it but it throws exception like cant convert Long to MyObject. I think only void, long or List or Stream are supported. Is there any way to achieve what I am trying to do?

推荐答案

Spring 不知道此方法只能删除一个对象,因此它不允许您使用返回的单个结果来定义它.毕竟,您在此处定义的合同"中并不能保证只有一场比赛.您可能应该定义返回 List 的方法,然后如果您确定只有一个对象,则从列表中获取第一个对象.

Spring doesn't know that only one object can ever be deleted by this method, so it won't allow you to define it with a single result returned. After all, there is no guarantee in the "contract" you have defined here that there will only be one match. You should probably define the method to return a List and then just get the first object from the list if you are sure there will only be one.

这篇关于Spring数据deleteBy查询不返回删除的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆