General Java Method that Queries DB and Returns Re

2019-05-23 10:04发布

What I'm looking for seems pretty straight forward to me, but my googles have failed.

I want a method that allows me to run any query and get the results in json format.

The trick is I don't want the results to need java objects as part of the process (DTOs, VOs, etc).

Any quick/easy/clean ways of doing this?

5条回答
啃猪蹄的小仙女
2楼-- · 2019-05-23 10:37

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.
查看更多
闹够了就滚
3楼-- · 2019-05-23 10:39

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>
查看更多
Explosion°爆炸
4楼-- · 2019-05-23 10:45

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).

查看更多
贪生不怕死
5楼-- · 2019-05-23 10:51

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.

查看更多
我命由我不由天
6楼-- · 2019-05-23 10:56

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

查看更多
登录 后发表回答