繁体   English   中英

通过子文档密钥获取,Spring Hibernate MongoDB应用程序

[英]Get by subdocument key, Spring Hibernate MongoDB application

我得到以下实体:

@Entity
@Document(collection = "devices")
public class Device {

    @Id
    private Long id;

    @ElementCollection
    @Column(name = "basic_info")
    private Map<String, String> basicInfo;

// getters, setters

以及以下存储库代码:

@Repository
public interface DeviceRepository extends MongoRepository<Device, Long> {

    List<Device> findByBasicInfo_Name(String name);

文件看起来像这样:

"id": 1,
"basicInfo": {
    "created": "timestamp",
    "name": "string",
    "type": "string",
    "status": "string"
}

我正在尝试使用findByBasicInfo_Name函数检索基于"basicInfo" "name"键的findByBasicInfo_Name ,甚至尝试使用findByBasicInfoName在另一个线程中建议有人没有运气。 我收到以下错误:

Caused by: org.springframework.data.mapping.PropertyReferenceException: No property name found for type String! Traversed path: Device.basicInfo.

您需要创建一个自定义存储库并使用mongoTemplate实施。

@Repository
public interface DeviceRepository extends MongoRepository<Device, String>, DeviceRepositoryCustom {} 

创建一个自定义的repo接口,并声明一个方法来findByMapKey

public interface DeviceRepositoryCustom {

  List<Device> findByMapKey(String mapKey,String value, Class clazz);
}

实施接口。

  public class DeviceRepositoryImpl implements  DeviceRepositoryCustom {

      @Autowired
      private final MongoTemplate mongoTemplate;

      @Override
      public List<Device> findByMapKey(String mapKey,String value, Class clazz) {

      Query query = Query.query(Criteria.where("basicInfo."+mapId).is(value));

       return mongoTemplate.find(query,clazz);
      }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM