简体   繁体   中英

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. 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 .

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

Make a custom repo interface and declare one method to 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);
      }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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