General Java Method that Queries DB and Returns Results in Json Format

旧街凉风 提交于 2019-12-06 09:31:38
DominicEU

Jackson has some pretty nice ways of doing it. There's some examples in this answer that should work wonders for you.

Alternatively, if Jackson isn't available to you, you could check out this

I accepted DominicEU's answer because it provided me with what I needed to get things working. Pheonix's answer in the link was good, but still lacked some details. Below shows the pom and a working example... (you'll probably want to rework the connection stuff for real implementation):

Java Code:

import com.google.gson.Gson;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class DBUtil {

    public String resultSetToJson(String query) {
        Connection connection = null;
        List<Map<String, Object>> listOfMaps = null;

        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://server:3306/databasename?user=username&password=password");
        } catch (Exception ex) {
            System.err.println("***exception trying to connect***");
            ex.printStackTrace();
        }

        try {
            QueryRunner queryRunner = new QueryRunner();
            listOfMaps = queryRunner.query(connection, query, new MapListHandler());
        } catch (SQLException se) {
            throw new RuntimeException("Couldn't query the database.", se);
        } finally {
            DbUtils.closeQuietly(connection);
        }
        return new Gson().toJson(listOfMaps);
    }
}

Maven pom:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>groupId</groupId>
    <artifactId>dbgeneric</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.6</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
    </dependencies>

</project>

I think you have two options:

  1. You could use a more general - purpose data structure to present your JSON payload in java. Something like a Map instance.
  2. You can create a class to model your result set and create instances of the model to store the payload.

Very Interesting question. I am not sure is there any library that directly does this. But we have couple of options in doing that.

  1. Through hibernate and Jackson library we can generate the output in the JSON data.
  2. We can have entity generated from the SQL and that entity we can convert into the JSON object.

We can have DataAccessLayer that can be generic fetch the data. For converting the entity to Json object, we need provide the logic in the specific entity class(Separate JSON generation class).

MesamH

The way I usually do this along with my colleagues is that we create harness or controller class, that usually points to a SQL connection. The job of the harness is to pull your information from the SQL db into your json file. However, you will need to create a stored procedure and you will need to call that stored procedure in your SQL Connection class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!