REST API连接到数据库使用JDBC忽略从数据库中带来的数据时返回一个空列表

问题描述 投票:0回答:1

Im做我自己的一个项目,该项目的重点是让一个在Java API休息,并使用JDBC从数据库中的数据带来的。问题是,当我进行连接和使用的主要方法,一切工作正常,但是当我试图通过一个GET请求来检索数据,它返回一个空列表检索数据。这是端点

@Path("/users")
public class UserResource {
UserService userService = new UserService();

@GET
@Path("/all")
@Produces(MediaType.APPLICATION_JSON)
public Response getAllUsers() throws InterruptedException {
    List<User> users = userService.getAllUsers();
    GenericEntity<List<User>> wrapper = new GenericEntity<List<User>>(users) {
    };
    return Response.ok(wrapper).build();
}

}

这是使用JDBC连接到数据库中的类

public class ConnectionJDBC {

private static String USERNAME = "root";
private static String PASSWORD = "root";
private static String CONSTRING = "jdbc:mysql://localhost:3306/";
private static String DATABASE = "users_db";

static Connection connection;

public ConnectionJDBC() {
}

public static Connection getConnectionToDB() {
    try {
        String url = CONSTRING + DATABASE;
        connection = DriverManager.getConnection(url, USERNAME, PASSWORD);
        if (connection != null) {
            System.out.println("Connected");
        } else {
            System.out.println("Connection faild");
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Something went wrong before establishing the connection");
    }
    return connection;

}

public List<User> getUsers() {
    connection = getConnectionToDB();
    String query = "SELECT * FROM users_db.user_info;";
    List<User> userListRetrived = new ArrayList<>();

    try {
        PreparedStatement statement = connection.prepareStatement(query);
        ResultSet dataRetrieved = statement.executeQuery();
        while (dataRetrieved.next()) {
            User user = new User(dataRetrieved.getInt("id"), 
                    dataRetrieved.getString(2),
                    dataRetrieved.getString(3));
            userListRetrived.add(user);
            return userListRetrived;

        }
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Something went wrong when retriving the data");
    }
    return userListRetrived;

}

}

UserService类是这里

public class UserService {
private ConnectionJDBC connectionJDBC = new ConnectionJDBC();

public UserService() {
}

public List<User> getAllUsers() {
    ConnectionJDBC connectionJDBC = new ConnectionJDBC();
    List<User> usersList = connectionJDBC.getUsers();
    return usersList;
}

}

用户类是普通的java bean。这感觉就像getUsers方法忽略了从数据库将数据,而是返回实例化的空单来代替。我使用的球衣和部署在Glassfish项目。如何我可以修复或解释这种情况下任何线索?

提前谢谢了!

java jdbc jax-rs
1个回答
0
投票

你没有援引userService.getUsers()从userResource()类方法。请按以下步骤更新userResource()类代码

GenericEntity<List<User>> wrapper = new GenericEntity<List<User>>(userService.getUsers());
© www.soinside.com 2019 - 2024. All rights reserved.