簡體   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