Apache DBUtils - Why need resultsethandler for Insert? - sql

I run an insert statement using Apache DBUtils. However, I am not sure why I have to include ResultSetHandler for this case:
String theQuery = QueryGenerator.insertintoStats();
ResultSetHandler<Object> dummyHandler = new ResultSetHandler<Object>() {
#Override
public Object handle(ResultSet rs) throws SQLException
{
return null;
}
};
try
{
queryRunner.insert(connection, theQuery, dummyHandler, Constants.UUIDSTR.toString(), name, prevbackupTime,
curbackupTime, updStartTime, delStartTime, bkupType.toString(), rowCount);
}
catch (SQLException e)
{
LOGGER.info(theQuery.toString());
LOGGER.error("Caught exception!", e);
}
Similar's the case for insertbatch which does use ResultSetHandler. I have resorted to use batch call for batch queries. Can anyone explain why we would be needing resultset handler for insert?

From documentation https://commons.apache.org/proper/commons-dbutils/apidocs/:
public <T> T insert(String sql,
ResultSetHandler<T> rsh,
Object... params)
throws SQLException
rsh - The handler used to create the result object from the ResultSet
of auto-generated keys.
If you insert values in a table which generate id upon insertion, you can retrieve it back, for example see this answer how to do this manually : https://stackoverflow.com/a/1915197/947111
You need ResultSetHandler<T> rsh to iterate over ResultSet which returned with id's which has been created.

Related

is it possible to get the execute sql that contains parameter when debugging mybatis source

I am setting a breakpoint in mybatis source BaseExecutor's queryFromDatabase function in Intellij Idea, this code block look like this:
private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
List<E> list;
localCache.putObject(key, EXECUTION_PLACEHOLDER);
try {
list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
} finally {
localCache.removeObject(key);
}
localCache.putObject(key, list);
if (ms.getStatementType() == StatementType.CALLABLE) {
localOutputParameterCache.putObject(key, parameter);
}
return list;
}
but the boundSql content shows sql like this:
select * from article where channel_id in (?)
is it possible to get the execute sql in the trace? because the channel_id has more than 100 and the sql also contains other filter condition.

Extract Data from a Data table to a text file in JPA

I'm working on data manipulation and my order is to extract all the content of a table into a text file ! I have already implemented this but apprently, I have commited a mistake while creating the request :
public void extractDonneesFichierPlat(){
TypedQuery<NotificationCnavOP> query = entityManager.createQuery("SELECT * INTO OUTFILE 'C:\\Test.txt' FROM NotificationCnavOP", NotificationCnavOP.class);
}
You cannot use "select * into outfile..." syntax in JPQL which is a separate query language different than SQL. If you want to execute native SQL queries in JPA you must use entityManager.createNativeQuery() method.
But still it is not possible to execute such 'bulk manipulation' query using this method.
The only solution I can think of is to use JDBC instead of JPA and execute:
Object o = entityManager.getDelegate();
System.out.println(o.getClass()); //prints the object class
// in my case it is org.hibernate.internal.SessionImpl
SessionImpl s = (SessionImpl)o;
Connection c = s.connection();
try {
Statement stmt = c.createStatement();
stmt.executeQuery("SELECT * INTO OUTFILE 'C:/Test.txt' FROM NotificationCnavOP");
} catch (SQLException e) {
e.printStackTrace();
}
The actual implementation of Session depends on the provider. In the case of Hibernate it is org.hibernate.internal.SessionImpl.
For newer versions of Hibernate it is org.hibernate.Session and it doesn't have the connection() method. So, you should try:
Object o = entityManager.getDelegate();
Session s = (Session)o;
s.doWork(connection -> {
try {
Statement stmt = connection.createStatement();
stmt.executeQuery("SELECT * INTO OUTFILE 'C:/Test2.txt' FROM NotificationCnavOP");
} catch (SQLException e) {
e.printStackTrace();
}
});
Both versions work in Hibernate 4.

jdbcTemplate.query works fine when passing few parameters and doesn't work for others

I have a select Oracle SQL that I am hitting using jdbcTemplate.query method. This returns a bean of the values from the table. I am passing a dynamic value to the query that will be used in the WHERE clause. However, the SQL values for few values that i am passing. But when I pass the value as NA it won't work. Any suggestions on this or help me with what am i missing?
private static final String regionSearchSql = "SELECT PRFLID, PRFLNM, RGN_CD FROM %PREFIX%MER_PRFL WHERE RGN_CD = ?";
public List<SearchProfileBean> regionSearchProfile(SearchProfileRequest searchProfileRequest) throws DatabaseQueryException {
try {
return jdbcTemplate.query((QueryUtility.getQueryWithPrefix(regionSearchSql,prefix)), new SearchProfileRowMapper(), searchProfileRequest.getRegionName());
} catch (Exception e) {
throw new DatabaseQueryException(QueryUtility.getQueryWithPrefix(regionSearchSql, prefix), e);
}
}
If i pass 'EMEA', 'LAC', 'JAPA' in searchProfileRequest.getRegionName() - the SQL returns perfect results. But if I pass 'NA' in searchProfileRequest.getRegionName(), it gives empty results. But there are rows in the table for NA.

How to get the ID of inserted row in JDBC with old driver?

I want to get auto increment id of inserted row. I know that there is a lot of examples how to do that:
link1
link2
But I use HSQL 1.8.0.10 and following code:
PreparedStatement ps = conn.prepareStatement("insert into dupa (v1) values(3)", Statement.RETURN_GENERATED_KEYS);
throws expection:
java.sql.SQLException: This function is not supported
How to get id if driver does not support the above solution. Is any other way to get auto increment key of inserted row? I want to handle as much as possible drivers. So want to use obove code in try section and use another way in catch section.
Second question: Is possible that database does not support this feature. So even if I use new driver and old database It will still not work? I tried to use hsql 2.3.2 driver but I can not to connect to 1.8.0.10 database.
The following code illustrates how to retrieve generated keys from HSQLDB 2.2.9 and later using the included JDBC 4 driver. This method returns a two element long[]. The first element contains the number of rows that were updated; the second contains the generated key if any:
static final long[] doUpdate( ... ) {
final long[] k = new long[] {0, KEY_UNDEFINED};
PreparedStatement ps = null;
try {
ps = CXN.get().prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
JdbcValue jv;
for (int i = 0; i < data.size(); i++) {
jv = data.get(i);
jv.type().setJdbcParameter(i + 1, ps, jv);
}
k[NUM_OF_ROWS] = (long) ps.executeUpdate();
if (k[NUM_OF_ROWS] > 0L) {
try (ResultSet rs = ps.getGeneratedKeys()) {
final String identColName = idCol.colName();
while (rs.next()) {
if (k[ROW_CREATED] != KEY_UNDEFINED) throw new AssertionError();
k[ROW_CREATED] = rs.getLong(identColName);
}
}
}
} catch (SQLException e) { ... }
finally {
try { if (ps != null) ps.close(); } catch (SQLException e) { }
}
return k;
}
I am unable to say whether this approach will work with old versions of HSQLDB.
You will have to use some vendor-specific solution, i.e. in mysql you would call LAST_INSERT_ID function.
I don't have valid installation of HSQL to test it, but you can give a try to the highest voted solution from this topic: how to return last inserted (auto incremented) row id in HSQL?

JDBC select query returns wrong values

I was performing JDBC select query in my web service to return some values from my database. Part of this table is attached to this question. After performing following query:
SELECT * FROM uses WHERE uses_user_fk='22';
I receive only one row, but in database are two values that meet the query conditions, as you can see in attached picture. Can anyone tell me where I made a mistake. I’m using following JDBC instruction to execute the query
ResultSet tempResultSet = statement.executeQuery(query);
Bellow image of database table uses:
Below the compete method that query the database, argument query is the same as listed earlier “SELECT * FROM uses…”. I should add that the answer for that query is 4, I also try this query without using quotes (uses_user_fk=22) but the result was the same:
protected ArrayList<Integer> queryForIds(String query, String column) throws Exception {
ArrayList<Integer> ids = new ArrayList<>();
try {
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager
.getConnection(GeneralDatabaseConstants.DATABASE_CONNECTION_URL);
statement = connect.createStatement();
ResultSet tempResultSet = statement.executeQuery(query);
if (tempResultSet.next())
ids.add(new Integer(tempResultSet.getInt(column)));
} catch (Exception e) {
throw e;
} finally {
close();
}
return ids;
}
replace
if (tempResultSet.next())
with
while (tempResultSet.next())