简体   繁体   English

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

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

I got the following entity: 我得到以下实体:

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

    @Id
    private Long id;

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

// getters, setters

and the following repository code: 以及以下存储库代码:

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

    List<Device> findByBasicInfo_Name(String name);

and the document looks like this: 文件看起来像这样:

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

I am trying to retrieve a document based on the "name" key in "basicInfo" with the findByBasicInfo_Name function, I even tried with findByBasicInfoName as someone suggested in another thread without any luck. 我正在尝试使用findByBasicInfo_Name函数检索基于"basicInfo" "name"键的findByBasicInfo_Name ,甚至尝试使用findByBasicInfoName在另一个线程中建议有人没有运气。 I get the following error: 我收到以下错误:

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

You need to create a custom repository and implement using mongoTemplate . 您需要创建一个自定义存储库并使用mongoTemplate实施。

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

Make a custom repo interface and declare one method to findByMapKey 创建一个自定义的repo接口,并声明一个方法来findByMapKey

public interface DeviceRepositoryCustom {

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

Implement the interface. 实施接口。

  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