Spring Jpa repository find all returns empty list

Total
32
Shares

I have connected spring boot to an MySQL database running on a VPS. I’ve mapped the entity class, repository, service and controller. But when calling the get method for "findAll" I get an empty list in postman. When I query the table in MySQL workbench I do get data, so its not empty.

Did I miss something?

My entity class:

@Entity
public class Requests {

    @Id
    @Column
    private Long id;

    @Column
    private Long url_id;

    @Column
    private Date timestamp;

    @Column
    private String method;

    @Column
    private String document;

    @Column
    private String mime_type;

    @Column
    private char is_html;

    @Column
    private int status_code;

    @Column
    private String reason;

    @Column
    private String cookies;

    @Column
    private String request;

    @Column
    private String response;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getUrl_id() {
        return url_id;
    }

    public void setUrl_id(Long url_id) {
        this.url_id = url_id;
    }

    public Date getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(Date timestamp) {
        this.timestamp = timestamp;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getDocument() {
        return document;
    }

    public void setDocument(String document) {
        this.document = document;
    }

    public String getMime_type() {
        return mime_type;
    }

    public void setMime_type(String mime_type) {
        this.mime_type = mime_type;
    }

    public char getIs_html() {
        return is_html;
    }

    public void setIs_html(char is_html) {
        this.is_html = is_html;
    }

    public int getStatus_code() {
        return status_code;
    }

    public void setStatus_code(int status_code) {
        this.status_code = status_code;
    }

    public String getReason() {
        return reason;
    }

    public void setReason(String reason) {
        this.reason = reason;
    }

    public String getCookies() {
        return cookies;
    }

    public void setCookies(String cookies) {
        this.cookies = cookies;
    }

    public String getRequest() {
        return request;
    }

    public void setRequest(String request) {
        this.request = request;
    }

    public String getResponse() {
        return response;
    }

    public void setResponse(String response) {
        this.response = response;
    }
}

My reposiroty:

public interface RequestsRepository extends JpaRepository<Requests, Long> {
}

My service:

@Service
public class RequestsService {

    private final RequestsRepository requestsRepository;


    public RequestsService(RequestsRepository requestsRepository) {
        this.requestsRepository = requestsRepository;
    }

    public List<RequestsDTO> findAll() {
        return requestsRepository.findAll()
                .stream()
                .map(requests -> mapToDTO(requests, new RequestsDTO()))
                .collect(Collectors.toList());
    }



    private RequestsDTO mapToDTO(final Requests requests, final RequestsDTO requestsDTO) {
        requestsDTO.setId(requests.getId());
        requestsDTO.setUrl_id(requests.getUrl_id());
        requestsDTO.setTimestamp(requests.getTimestamp());
        requestsDTO.setMethod(requests.getMethod());
        requestsDTO.setDocument(requests.getDocument());
        requestsDTO.setMime_type(requests.getMime_type());
        requestsDTO.setIs_html(requests.getIs_html());
        requestsDTO.setStatus_code(requests.getStatus_code());
        requestsDTO.setReason(requests.getReason());
        requestsDTO.setCookies(requests.getCookies());
        requestsDTO.setRequest(requests.getRequest());
        requestsDTO.setResponse(requests.getResponse());
        return requestsDTO;
    }

    private Requests mapToEntity(final RequestsDTO requestsDTO, final Requests requests) {
        requests.setId(requestsDTO.getId());
        requests.setUrl_id(requestsDTO.getUrl_id());
        requests.setTimestamp(requestsDTO.getTimestamp());
        requests.setMethod(requestsDTO.getMethod());
        requests.setDocument(requestsDTO.getDocument());
        requests.setMime_type(requestsDTO.getMime_type());
        requests.setIs_html(requestsDTO.getIs_html());
        requests.setStatus_code(requestsDTO.getStatus_code());
        requests.setReason(requestsDTO.getReason());
        requests.setCookies(requestsDTO.getCookies());
        requests.setRequest(requestsDTO.getRequest());
        requests.setResponse(requestsDTO.getResponse());
        return requests;
    }
}

And my controller:

@RestController
@RequestMapping(value = "/api/crawler", produces = MediaType.APPLICATION_JSON_VALUE)
public class RequestsController {

    private final RequestsService requestsService;


    public RequestsController(RequestsService requestsService) {
        this.requestsService = requestsService;
    }

    @GetMapping
    public ResponseEntity<List<RequestsDTO>> getAllRequests() {return ResponseEntity.ok(requestsService.findAll()); }
}

EDIT

My crawler domain config

/**
 * Data source for the MySQL crawler database
 */
@Configuration
@EntityScan(basePackages = "cs.crawler.server.projectcs.domain.crawlerdb")
@EnableJpaRepositories(basePackages = "cs.crawler.server.projectcs.repos.crawlerdb")
@EnableTransactionManagement
public class CrawlerDomainConfig {

    @Bean
    @ConfigurationProperties("spring.datasource.crawler")
    public DataSourceProperties crawlerDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.crawler.configuration")
    public HikariDataSource secondDataSource(DataSourceProperties secondDataSourceProperties) {
        return secondDataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
    }

}

My config YAML:

spring:
  datasource:
    users:
      url: ${JDBC_DATABASE_URL:jdbc:h2:mem:projectcs}
      username: ${JDBC_DATABASE_USERNAME:sa}
      password: ${JDBC_DATABASE_PASSWORD:}
    crawler:
      url: ${JDBC_DATABASE_URL:jdbc:mysql://VPSIPHERE:3306/darcweb?createDatabaseIfNotExist=false}
      username: ${JDBC_DATABASE_USERNAME:root}
      password: ${JDBC_DATABASE_PASSWORD:mypassword}
  dbcp2:
    max-wait-millis: 30000
    validation-query: "SELECT 1"
    validation-query-timeout: 30
  jpa:
    hibernate:
      ddl-auto: update
    open-in-view: false
    properties:
      hibernate:
        jdbc:
          lob:
            non_contextual_creation: true
        id:
          new_generator_mappings: true
springdoc:
  pathsToMatch: /api/**

Solution

You have 2 datasoruce dependencies (mysql and h2). You need to specify which datasource for spring to use – it picks h2 by default which is the reason you don’t find anything.

Add following lines to your application.properties file to specify the database:

spring.datasource.url=jdbc:mysql://localhost:3306/DATABASE_NAME
spring.datasource.username=USERNAME
spring.datasource.password=PASSWORD

To use h2 for tests for example you can overwrite application.properties for h2 under your test folder in resources

In case you want to use both databases simultaneously in your application you would need to define both and set them in runtime into your enviroment like shown here:

https://www.baeldung.com/spring-data-jpa-multiple-databases

Leave a Reply

Your email address will not be published. Required fields are marked *