Skip to content

Instantly share code, notes, and snippets.

@Baztoune
Created August 24, 2012 13:49
Show Gist options
  • Save Baztoune/3450729 to your computer and use it in GitHub Desktop.
Save Baztoune/3450729 to your computer and use it in GitHub Desktop.
Return available fields and their type from SQL Query
public class SqlQueryHelper {
public List<SimpleEntry<String, Type>> getAvailableFieldsFromQuery(
String sqlQuery) {
List<SimpleEntry<String, Type>> availableFields = new ArrayList<SimpleEntry<String, Type>>();
Connection c = null;
Statement st = null;
Session sess = null;
try {
Session delegate = (Session) entityManager.getDelegate();
sess = delegate.getSessionFactory().openSession();
c = sess.connection();
st = c.createStatement();
ResultSet rs = st.executeQuery("select * from (" + sqlQuery
+ ") where rownum<0");
for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
availableFields.add(new SimpleEntry(rs.getMetaData()
.getColumnName(i), rs.getMetaData().getColumnClassName(
i)));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
st.close();
c.close();
sess.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return availableFields;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment