java - Spring Boot GET request returns empty JSON, even though data exists in database - Stack Overflow

I'm working on a Spring Boot application that connects to a PostgreSQL database. I have an entity

I'm working on a Spring Boot application that connects to a PostgreSQL database. I have an entity class Player, and data is inserted into the database manually. However, when I send a GET request to retrieve the data, the response is an empty JSON array ({}). Despite this, I can see the data in the database using SQL queries directly.

Player entity

package com.backend.basketMarkt.Entity;

import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Entity
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Data
@Table(name = "Player_Stats")
public class Player {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true)
    private Integer id;

    @Column(name = "player")
    private String playerName;
    private Integer age;
    private String team;

    @Column(name = "pos")
    private String position;

    @Column(name = "games_played")
    private Integer gamesPlayed;

    @Column(name = "games_started")
    private Integer gamesStarted;

    @Column(name = "minutes_played")
    private float minutesPlayed;

    @Column(name = "field_goals")
    private float fg;

    @Column(name = "field_goals_attempted")
    private float fga;

    @Column(name = "field_goals_percentage")
    private float fgp;

    @Column(name = "three_point_fg")
    private float threePointFg;

    @Column(name = "three_point_attempted")
    private float threePointA;

    @Column(name = "three_point_percentage")
    private float threePointP;

    @Column(name = "two_point_fg")
    private float twoPointFg;

    @Column(name = "two_point_attempted")
    private float twoPointA;

    @Column(name = "two_point_percentage")
    private float twoPointP;

    @Column(name = "effective_fg_percentage")
    private float effectiveFgPercentage;

    @Column(name = "free_throws")
    private float freeThrows;

    @Column(name = "free_throws_attempted")
    private float freeThrowsAttempted;

    @Column(name = "free_throw_percentage")
    private float freeThrowsPercentage;

    @Column(name = "offensive_rebounds")
    private float offensiveRebounds;

    @Column(name = "defensive_rebounds")
    private float defensiveRebounds;

    @Column(name = "total_rebounds")
    private float totalRebounds;

    private float assists;
    private float steals;
    private float blocks;
    private float turnovers;

    @Column(name = "personal_fouls")
    private float personalFouls;

    private float points;

}

Repository

package com.backend.basketMarkt.Repository;

import com.backend.basketMarkt.Entity.Player;
import .springframework.data.jpa.repository.JpaRepository;
import .springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface PlayerRepository extends JpaRepository<Player, Integer> {
    void deleteByPlayerName(String player);

    Optional<Player> findByPlayerName(String player);
    List<Player> findByPosition(String position);
    List<Player> findByPositionAndPlayerName(String position, String player);
    List<Player> findByTeam(String team);
    List<Player> findByTeamAndPlayerName(String team, String player);
    void deleteByPosition(String position);
}

Service

package com.backend.basketMarkt.Service;

import com.backend.basketMarkt.Entity.Player;
import com.backend.basketMarkt.Repository.PlayerRepository;
import jakarta.transaction.Transactional;
import .springframework.beans.factory.annotation.Autowired;
import .springframework.http.ResponseEntity;
import .springframework.stereotype.Component;
import .springframework.stereotype.Service;
import .springframework.web.bind.annotation.GetMapping;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Component
public class PlayerService {

    final private PlayerRepository playerRepository;

    @Autowired
    public PlayerService(PlayerRepository playerRepository) {
        this.playerRepository = playerRepository;
    }

    public List<Player> getPlayers() {
        List<Player> players = playerRepository.findAll();
        System.out.println("Total players in DB: " + players.size()); // Debug için
        return players;
    }

    public Optional<Player> getPlayerByName(String player) { // repositorydeki birinci
        return playerRepository.findByPlayerName(player);
    }

    public List<Player> getPlayersByPosition(String position) { // repositorydeki ikinci
        return playerRepository.findByPosition(position);
    }

    public List<Player> getPlayersByPositionAndPlayer(String position, String player) { // repositorydeki ucuncu
        return playerRepository.findByPositionAndPlayerName(position, player);
    }

    public List<Player> getPlayersByTeam(String team) { // repositorydeki dorduncu
        return playerRepository.findByTeam(team);
    }

    public List<Player> getPlayersByTeamAndPlayer(String team, String player) { // repositorydeki besinci
        return playerRepository.findByTeamAndPlayerName(team, player);
    }

    public Player addPlayer(Player player) {
        return playerRepository.save(player);
    }

    @GetMapping("/test")
    public ResponseEntity<String> testEndpoint() {
        List<Player> players = playerRepository.findAll();
        return ResponseEntity.ok("Total players in DB: " + players.size());
    }

    public Player updatePlayer(Player player) {
        Optional<Player> existingPlayer = playerRepository.findByPlayerName(player.getPlayerName());

        if (existingPlayer.isPresent()) {
            Player playerToUpdate = existingPlayer.get();
            playerToUpdate.setPosition(player.getPosition());
            playerToUpdate.setTeam(player.getTeam());
            playerToUpdate.setAge(player.getAge());
            playerRepository.save(playerToUpdate);
            return playerToUpdate;
        }
        return null;
    }

    @Transactional
    public void deleteByPlayerName(String playerName) {
        playerRepository.deleteByPlayerName(playerName);
    }

    @Transactional
    public void deleteByPosition(String position) {
        if (position == null || position.isEmpty()) {
            throw new IllegalArgumentException("Position cannot be null or empty");
        }
        playerRepository.deleteByPosition(position);
    }

}

Controller

package com.backend.basketMarkt.Controller;

import com.backend.basketMarkt.Entity.Player;
import com.backend.basketMarkt.Service.PlayerService;
import .springframework.beans.factory.annotation.Autowired;
import .springframework.http.HttpStatus;
import .springframework.http.ResponseEntity;
import .springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(path = "api/v1/player")
public class PlayerController {

    private final PlayerService playerService;

    @Autowired
    public PlayerController(PlayerService playerService) {
        this.playerService = playerService;
    }

    @GetMapping("/get")
    public ResponseEntity<?> getPlayers(
            @RequestParam(required = false) String playerName,
            @RequestParam(required = false) String team,
            @RequestParam(required = false) String position
    ) {
        if(team != null && position != null) {
            return ResponseEntity.ok(playerService.getPlayersByTeamAndPlayer(team, position));
        } else if (playerName != null) {
            return playerService.getPlayerByName(playerName)
                    .map(ResponseEntity::ok)
                    .orElse(ResponseEntity.notFound().build());
        } else if(position != null) {
            return ResponseEntity.ok(playerService.getPlayersByPosition(position));
        } else if (team != null) {
            return ResponseEntity.ok(playerService.getPlayersByTeam(team));
        } else {
            return ResponseEntity.ok(playerService.getPlayers());
        }
    }

    @PostMapping
    public ResponseEntity<Player> addPlayer(@RequestBody Player playerName) {
        Player newPlayer = playerService.addPlayer(playerName);
        return new ResponseEntity<>(newPlayer, HttpStatus.CREATED);
    }

    @PutMapping
    public ResponseEntity<Player> updatePlayer(@RequestBody Player playerName) {
        Player updatedPlayer = playerService.updatePlayer(playerName);
        if(updatedPlayer != null) {
            return new ResponseEntity<>(updatedPlayer, HttpStatus.OK);
        }else{
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }

    @DeleteMapping("/{playerName}")
    public ResponseEntity<String> deletePlayer(@PathVariable String playerName) {
        playerService.deleteByPlayerName(playerName);
        return new ResponseEntity<>("Player Deleted", HttpStatus.OK);
    }

    @DeleteMapping("/deleteByPosition/{position}")
    public ResponseEntity<String> deletePlayerByPosition(@PathVariable String position) {
        playerService.deleteByPosition(position);
        return new ResponseEntity<>("Player Deleted", HttpStatus.OK);
    }
}

Database

-- Table: public.Player_Stats

-- DROP TABLE IF EXISTS public."Player_Stats";

CREATE TABLE IF NOT EXISTS public."Player_Stats"
(
    id integer NOT NULL DEFAULT nextval('"Player_Stats_id_seq"'::regclass),
    player character varying(100) COLLATE pg_catalog."default",
    age integer,
    team character varying(60) COLLATE pg_catalog."default",
    pos character varying(60) COLLATE pg_catalog."default",
    games_played integer,
    games_started integer,
    minutes_played real,
    field_goals real,
    field_goals_attempted real,
    field_goals_percentage real,
    three_point_fg real,
    three_point_attempted real,
    three_point_percentage real,
    two_point_fg real,
    two_point_attempted real,
    two_point_percentage real,
    effective_fg_percentage real,
    free_throws real,
    free_throws_attempted real,
    free_throw_percentage real,
    offensive_rebounds real,
    defensive_rebounds real,
    total_rebounds real,
    assists real,
    steals real,
    blocks real,
    turnovers real,
    personal_fouls real,
    points real,
    CONSTRAINT "Player_Stats_pkey" PRIMARY KEY (id)
)

TABLESPACE pg_default;

ALTER TABLE IF EXISTS public."Player_Stats"
    OWNER to postgres;

SELECT * FROM "Player_Stats";

GRANT ALL ON TABLE public."Player_Stats" TO postgres;

When I test the GET request (/players) using Postman, it returns an empty JSON array. However, I can see the data correctly in the database when using SQL queries directly.

I have verified the database connection and it's working fine. The data is correctly inserted into the database manually. The findAll() method is supposed to return the data, but it's returning an empty array.

Why is the GET request returning an empty JSON array, even though data exists in the database?

I'm working on a Spring Boot application that connects to a PostgreSQL database. I have an entity class Player, and data is inserted into the database manually. However, when I send a GET request to retrieve the data, the response is an empty JSON array ({}). Despite this, I can see the data in the database using SQL queries directly.

Player entity

package com.backend.basketMarkt.Entity;

import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Entity
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Data
@Table(name = "Player_Stats")
public class Player {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true)
    private Integer id;

    @Column(name = "player")
    private String playerName;
    private Integer age;
    private String team;

    @Column(name = "pos")
    private String position;

    @Column(name = "games_played")
    private Integer gamesPlayed;

    @Column(name = "games_started")
    private Integer gamesStarted;

    @Column(name = "minutes_played")
    private float minutesPlayed;

    @Column(name = "field_goals")
    private float fg;

    @Column(name = "field_goals_attempted")
    private float fga;

    @Column(name = "field_goals_percentage")
    private float fgp;

    @Column(name = "three_point_fg")
    private float threePointFg;

    @Column(name = "three_point_attempted")
    private float threePointA;

    @Column(name = "three_point_percentage")
    private float threePointP;

    @Column(name = "two_point_fg")
    private float twoPointFg;

    @Column(name = "two_point_attempted")
    private float twoPointA;

    @Column(name = "two_point_percentage")
    private float twoPointP;

    @Column(name = "effective_fg_percentage")
    private float effectiveFgPercentage;

    @Column(name = "free_throws")
    private float freeThrows;

    @Column(name = "free_throws_attempted")
    private float freeThrowsAttempted;

    @Column(name = "free_throw_percentage")
    private float freeThrowsPercentage;

    @Column(name = "offensive_rebounds")
    private float offensiveRebounds;

    @Column(name = "defensive_rebounds")
    private float defensiveRebounds;

    @Column(name = "total_rebounds")
    private float totalRebounds;

    private float assists;
    private float steals;
    private float blocks;
    private float turnovers;

    @Column(name = "personal_fouls")
    private float personalFouls;

    private float points;

}

Repository

package com.backend.basketMarkt.Repository;

import com.backend.basketMarkt.Entity.Player;
import .springframework.data.jpa.repository.JpaRepository;
import .springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface PlayerRepository extends JpaRepository<Player, Integer> {
    void deleteByPlayerName(String player);

    Optional<Player> findByPlayerName(String player);
    List<Player> findByPosition(String position);
    List<Player> findByPositionAndPlayerName(String position, String player);
    List<Player> findByTeam(String team);
    List<Player> findByTeamAndPlayerName(String team, String player);
    void deleteByPosition(String position);
}

Service

package com.backend.basketMarkt.Service;

import com.backend.basketMarkt.Entity.Player;
import com.backend.basketMarkt.Repository.PlayerRepository;
import jakarta.transaction.Transactional;
import .springframework.beans.factory.annotation.Autowired;
import .springframework.http.ResponseEntity;
import .springframework.stereotype.Component;
import .springframework.stereotype.Service;
import .springframework.web.bind.annotation.GetMapping;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Component
public class PlayerService {

    final private PlayerRepository playerRepository;

    @Autowired
    public PlayerService(PlayerRepository playerRepository) {
        this.playerRepository = playerRepository;
    }

    public List<Player> getPlayers() {
        List<Player> players = playerRepository.findAll();
        System.out.println("Total players in DB: " + players.size()); // Debug için
        return players;
    }

    public Optional<Player> getPlayerByName(String player) { // repositorydeki birinci
        return playerRepository.findByPlayerName(player);
    }

    public List<Player> getPlayersByPosition(String position) { // repositorydeki ikinci
        return playerRepository.findByPosition(position);
    }

    public List<Player> getPlayersByPositionAndPlayer(String position, String player) { // repositorydeki ucuncu
        return playerRepository.findByPositionAndPlayerName(position, player);
    }

    public List<Player> getPlayersByTeam(String team) { // repositorydeki dorduncu
        return playerRepository.findByTeam(team);
    }

    public List<Player> getPlayersByTeamAndPlayer(String team, String player) { // repositorydeki besinci
        return playerRepository.findByTeamAndPlayerName(team, player);
    }

    public Player addPlayer(Player player) {
        return playerRepository.save(player);
    }

    @GetMapping("/test")
    public ResponseEntity<String> testEndpoint() {
        List<Player> players = playerRepository.findAll();
        return ResponseEntity.ok("Total players in DB: " + players.size());
    }

    public Player updatePlayer(Player player) {
        Optional<Player> existingPlayer = playerRepository.findByPlayerName(player.getPlayerName());

        if (existingPlayer.isPresent()) {
            Player playerToUpdate = existingPlayer.get();
            playerToUpdate.setPosition(player.getPosition());
            playerToUpdate.setTeam(player.getTeam());
            playerToUpdate.setAge(player.getAge());
            playerRepository.save(playerToUpdate);
            return playerToUpdate;
        }
        return null;
    }

    @Transactional
    public void deleteByPlayerName(String playerName) {
        playerRepository.deleteByPlayerName(playerName);
    }

    @Transactional
    public void deleteByPosition(String position) {
        if (position == null || position.isEmpty()) {
            throw new IllegalArgumentException("Position cannot be null or empty");
        }
        playerRepository.deleteByPosition(position);
    }

}

Controller

package com.backend.basketMarkt.Controller;

import com.backend.basketMarkt.Entity.Player;
import com.backend.basketMarkt.Service.PlayerService;
import .springframework.beans.factory.annotation.Autowired;
import .springframework.http.HttpStatus;
import .springframework.http.ResponseEntity;
import .springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(path = "api/v1/player")
public class PlayerController {

    private final PlayerService playerService;

    @Autowired
    public PlayerController(PlayerService playerService) {
        this.playerService = playerService;
    }

    @GetMapping("/get")
    public ResponseEntity<?> getPlayers(
            @RequestParam(required = false) String playerName,
            @RequestParam(required = false) String team,
            @RequestParam(required = false) String position
    ) {
        if(team != null && position != null) {
            return ResponseEntity.ok(playerService.getPlayersByTeamAndPlayer(team, position));
        } else if (playerName != null) {
            return playerService.getPlayerByName(playerName)
                    .map(ResponseEntity::ok)
                    .orElse(ResponseEntity.notFound().build());
        } else if(position != null) {
            return ResponseEntity.ok(playerService.getPlayersByPosition(position));
        } else if (team != null) {
            return ResponseEntity.ok(playerService.getPlayersByTeam(team));
        } else {
            return ResponseEntity.ok(playerService.getPlayers());
        }
    }

    @PostMapping
    public ResponseEntity<Player> addPlayer(@RequestBody Player playerName) {
        Player newPlayer = playerService.addPlayer(playerName);
        return new ResponseEntity<>(newPlayer, HttpStatus.CREATED);
    }

    @PutMapping
    public ResponseEntity<Player> updatePlayer(@RequestBody Player playerName) {
        Player updatedPlayer = playerService.updatePlayer(playerName);
        if(updatedPlayer != null) {
            return new ResponseEntity<>(updatedPlayer, HttpStatus.OK);
        }else{
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }

    @DeleteMapping("/{playerName}")
    public ResponseEntity<String> deletePlayer(@PathVariable String playerName) {
        playerService.deleteByPlayerName(playerName);
        return new ResponseEntity<>("Player Deleted", HttpStatus.OK);
    }

    @DeleteMapping("/deleteByPosition/{position}")
    public ResponseEntity<String> deletePlayerByPosition(@PathVariable String position) {
        playerService.deleteByPosition(position);
        return new ResponseEntity<>("Player Deleted", HttpStatus.OK);
    }
}

Database

-- Table: public.Player_Stats

-- DROP TABLE IF EXISTS public."Player_Stats";

CREATE TABLE IF NOT EXISTS public."Player_Stats"
(
    id integer NOT NULL DEFAULT nextval('"Player_Stats_id_seq"'::regclass),
    player character varying(100) COLLATE pg_catalog."default",
    age integer,
    team character varying(60) COLLATE pg_catalog."default",
    pos character varying(60) COLLATE pg_catalog."default",
    games_played integer,
    games_started integer,
    minutes_played real,
    field_goals real,
    field_goals_attempted real,
    field_goals_percentage real,
    three_point_fg real,
    three_point_attempted real,
    three_point_percentage real,
    two_point_fg real,
    two_point_attempted real,
    two_point_percentage real,
    effective_fg_percentage real,
    free_throws real,
    free_throws_attempted real,
    free_throw_percentage real,
    offensive_rebounds real,
    defensive_rebounds real,
    total_rebounds real,
    assists real,
    steals real,
    blocks real,
    turnovers real,
    personal_fouls real,
    points real,
    CONSTRAINT "Player_Stats_pkey" PRIMARY KEY (id)
)

TABLESPACE pg_default;

ALTER TABLE IF EXISTS public."Player_Stats"
    OWNER to postgres;

SELECT * FROM "Player_Stats";

GRANT ALL ON TABLE public."Player_Stats" TO postgres;

When I test the GET request (/players) using Postman, it returns an empty JSON array. However, I can see the data correctly in the database when using SQL queries directly.

I have verified the database connection and it's working fine. The data is correctly inserted into the database manually. The findAll() method is supposed to return the data, but it's returning an empty array.

Why is the GET request returning an empty JSON array, even though data exists in the database?

Share Improve this question edited Mar 13 at 8:43 Mark Rotteveel 110k229 gold badges156 silver badges224 bronze badges asked Mar 12 at 21:29 Nicat AbbasNicat Abbas 1 5
  • Have you tried not using @Data annotation? – zawarudo Commented Mar 12 at 22:58
  • 2 Please post your postman request as well. Looks like your endpoints are not actually called. – Abdullah Mohammad Motiullah Commented Mar 13 at 8:28
  • Place many debug points, you will see problem. – Vy Do Commented Mar 13 at 9:54
  • 1 I don't see any endpoint (/players) in your code. Are you using the correct paths? As per your code, the get path is api/v1/player/get. – Siddharth Commented Mar 13 at 10:01
  • Please provide your application.properties file and provide some logs ( the logs showing the database connection was established) – Khaled Sabri Commented Mar 13 at 19:46
Add a comment  | 

3 Answers 3

Reset to default -1

Try to quote the identifier, use back ticks:

@Table(name="`Player_Stats`")

The problem is how you have named the `Player_Stats` table.

You can rename the table using snake_case for example 'player_stats' or by changing the value of the name property in the @Table annotation as indicated in another answer to @Table(name="`Player_Stats`") .

I recommend to you to change the table name and change it in the @Table annotation too.

Steps to do it:

  1. ALTER TABLE "Player_Stats" RENAME TO player_stats;

  2. @Table(name="player_stats")

  1. Add the following property to your Hibernate configuration (in application.properties or hibernate.cfg.xml), depending on your setup:

    spring.jpa.hibernate.naming.physical-strategy=.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

    This disables Hibernate's default naming strategy, which alters the case of table and column names. The PhysicalNamingStrategyStandardImpl preserves the exact case as defined in the @Table annotation.

  2. Use the @Table annotation without escaping the name further:

    @NoArgsConstructor
    @Builder
    @Data
    @Table(name = "Player_Stats")
    public class Player {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "id", unique = true)
        private Integer id;
        ...
    }
    

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744729943a4590407.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信