Search code examples
springjhipsterspring-repositories

How to retrieve the repository from JHipster spring controller?


I have a JHipster microservice application, and I've added a spring controller. However, it is generated without a repository and I don't know how to retrieve it to perform data tasks.

This is the code:

@RestController
@RequestMapping("/api/data")
public class DataResource {

    private final Logger log = LoggerFactory.getLogger(DataResource.class);
    private final DeviceRepository deviceRepository;

    public DataResource() {
    }

    /**
    * GET global
    */
    @GetMapping("/global")
    public ResponseEntity<GlobalStatusDTO[]> global() {

        List<Device> list=deviceRepository.findAll();
        GlobalStatusDTO data[]=new GlobalStatusDTO[]{new GlobalStatusDTO(list.size(),1,1,1,1)};
        return ResponseEntity.ok(data);
    }

}

EDIT: I need to inject an already existing repository, here is the CRUD part where the repository is initialized:

@RestController
@RequestMapping("/api")
@Transactional
public class DeviceResource {

    private final Logger log = LoggerFactory.getLogger(DeviceResource.class);

    private static final String ENTITY_NAME = "powerbackDevice";

    @Value("${jhipster.clientApp.name}")
    private String applicationName;

    private final DeviceRepository deviceRepository;

    public DeviceResource(DeviceRepository deviceRepository) {
        this.deviceRepository = deviceRepository;
    }

    /**
     * {@code POST  /devices} : Create a new device.
     *
     * @param device the device to create.
     * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new device, or with status {@code 400 (Bad Request)} if the device has already an ID.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PostMapping("/devices")
    public ResponseEntity<Device> createDevice(@Valid @RequestBody Device device) throws URISyntaxException {
...


Solution

  • I might misunderstand you, but your first code part doesn't work, because, you didn't inject DeviceRepository by the constructor. Of course, there are other methods of injections.

    @RestController
    @RequestMapping("/api/data")
    public class DataResource {
    
        private final Logger log = LoggerFactory.getLogger(DataResource.class);
        private final DeviceRepository deviceRepository;
    
        //changes are here only, constructor method of injection
        public DataResource(DeviceRepository deviceRepository) {
          this.deviceRepository = deviceRepository; 
        }
    
        /**
        * GET global
        */
        @GetMapping("/global")
        public ResponseEntity<GlobalStatusDTO[]> global() {
    
            List<Device> list=deviceRepository.findAll();
            GlobalStatusDTO data[]=new GlobalStatusDTO[]{new GlobalStatusDTO(list.size(),1,1,1,1)};
            return ResponseEntity.ok(data);
        }
    
    }