4

I execute a query which should return the results as a CSV to the STDOUT.

When I execute my query in the pgAdmin I successfully get results.

However when I execute the same query using hibernate I gets the following exception:

javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not extract ResultSet

I mustn't show the tables structure but I know that the sql is fine(I've copied the entire content of "sql" then I execute it in pgAdmin); The query looks like:

String sql = "COPY (" + sqlQuery + ") TO STDOUT WITH CSV";

Then I execute it as the following:

Query query = getEntityManager().createNativeQuery(sql);

Object result = query.getSingleResult(); // I also tried the other get results method...(`getFirstresult()` has returned 0)

In any related questions I have found, I saw that the OP put the csv into a file instead of stdout.

Is it possible to return csv result using hibernate?

Thanks in advance!

roeygol
  • 4,908
  • 9
  • 51
  • 88

2 Answers2

1

AFAIK, COPY is not supported natively by PostgreSQL JDBC driver (last tested on postgresql-9.4.1208.jre7). Thus, Hibernate can not run the command.

If you really need to use COPY you should consider a CopyManager: how to copy a data from file to PostgreSQL using JDBC?

But personally, I would advocate you change your approach. Loading data with COPY looks like a kind of a hack to me.

Community
  • 1
  • 1
Boris Schegolev
  • 3,601
  • 5
  • 21
  • 34
0

You can have this done with univocity-parsers using two lines of code. You just need to get a resultset from your query and do this:

CsvRoutines routines = new CsvRoutines();
routines.write(resultset, new File("/path/to/output.csv"), "UTF-8");

The write() method takes care of everything. The resultset is closed by the routine automatically.

Jeronimo Backes
  • 6,141
  • 2
  • 25
  • 29