简体   繁体   English

使用数据库Java的RestApi

[英]RestApi using Database Java

I'm learning how to create web services with RESTful Api. 我正在学习如何使用RESTful Api创建Web服务。

I have a sample database and I want to get data from this database using rest api. 我有一个示例数据库,我想使用rest api从该数据库中获取数据。

Here is my code: 这是我的代码:

@GET
@Produces(MediaType.APPLICATION_JSON)
public ArrayList<UserModel> getJson() throws ClassNotFoundException, SQLException {
    Connection connection = DatabaseConnection.getConnection();
    Statement stm = connection.createStatement();
    String sql = "select * from user";
    ResultSet rs = stm.executeQuery(sql);
    ArrayList<UserModel> res = new ArrayList<>();
    while(rs.next())
    {
        UserModel user = new UserModel();
        user.setId(rs.getInt("id"));
        user.setNome(rs.getString("nome")); 
        res.add(user);
    }
    return res;
}

Is there a better or quicker way to obtain data from a database and return the resultSet without the conversation in an ArrayList ? 是否有更好或更快的方法来从数据库获取数据并返回resultSet而无需在ArrayList进行对话?

I think this is already a good, quick and short example. 我认为这已经是一个很好的,简短的例子。 You could restrict the statement to the columns you need to avoid unnecessary data to be loaded: 您可以将语句限制为需要的列,以避免不必要的数据被加载:

String sql = "select id, nome from user"; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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