Firstly, I want to say that this question is not about JOIN or UNION. Also, there are some answers on stack overflow which I've tried, but I'm still having issues. (example: Multiple queries executed in java in single statement)
Problem:
I want to retrieve data from two tables which I can't do using JOIN or UNION since they contain different types of data and I'm after different number of rows from each table. The reason why I want to do it in one go is efficiency however if somebody is able to convince me that two calls instead of one make almost no difference in overhead then I'll happily solve my problem like that (although it would still be nice to know how to use one query only)
Code:
Based on this, I wrote the following code (excerpt):
String sql = "SET @organizationId = 0;" +
"SELECT @organizationId := Id 'Id', Name FROM Organization WHERE Id = ?;" +
"SELECT AssociatedOrganizationId FROM OrganizationAssociations WHERE OrganizationId = @organizationId;";
Connection conn = null;
try {
conn = dataSource.getConnection();
CallableStatement cs = conn.prepareCall(sql);
cs.setInt(1, organizationId);
boolean isResultSet = cs.execute();
if (!isResultSet) {
logger.error("getOrganization - retrieved result is not a ResultSet");
}
OrganizationDto organization = null;
ResultSet rs = cs.getResultSet();
if (rs.next()) {
// create organization object using retrieved data
}
rs.close();
Behaviour causing the issue:
cs.execute() always returns false.
Observations and actions I took to try to resolve the issue:
As stated here and in Java documentation, CallableStatement was designed to be used for calling stored procedures. Stored procedures themselves never return a value and this can only be achieved through OUT parameters.
Bearing that in mind, it doesn't surprise me that .execute() returns false.
I have however changed CallableStatement to PreparedStatement and Statement but that didn't change much in terms of the outcome (cs.getResultSet() still returned null)
The answers I'm seeking:
1. I'd like to know how can I achieve retrieving data from multiple tables using one query with multiple SELECT statements in jdbc. That is to be achieved without JOINS, UNIONS etc. I'd like to be able to use the query I already have if possible (query works perfectly fine - tested in HeidiSQL).
2. (Optional) If there's anybody out there who thinks that two queries would make not much difference in terms of database load and performance then I'd like to be convinced that this actually is the case.
Update #1:
To clarify, this is the data that my query returns:
ResultSet #1:
Id, Name
1, "org1_name"
ResultSet #2:
AssociatedOrganizationId
2
3