Reputation: 116
I am trying to print to system console within a lambda call, but it does not show in the output window (both within IDE and when run as mvn test)
Here is the code
public List<FieldDto> findField(String fieldKey) {
jdbcTemplate.setQueryTimeout(10);
System.out.println("\n\n\n\n ----------- seeeee ----------------------");
List<FieldDto> result = jdbcTemplate.query("select * from V_FIELD where FIELD_KEY = '" + fieldKey + "'",
(rs, rowNum) -> getFieldDto(rs, rowNum)
);
System.out.println("\n\n\n\n ----------- done ----------------------");
return result;
}
and the method getFieldDto is defined as
private FieldDto getFieldDto(ResultSet rs, int rowNum) throws SQLException {
FieldDto fieldDto = new FieldDto();
System.out.println(" .. in getFieldDto:");
try {
fieldDto.FIELD_KEY = rs.getString("FIELD_KEY");
fieldDto.CREATE_DATE = rs.getString("CREATE_DATE");
} catch (Exception ex) {
System.out.println(" exception getFieldDto:" + ex.getMessage());
throw new RuntimeException(ex);
}
return fieldDto;
}
when I run the jUnit test, the console does show the ---see--- and ----done---, console logs, but not the '.. in getFieldDto'
why is that not happening, how can I print within the Lambda calls
Upvotes: 1
Views: 887
Reputation: 83587
A lambda expression creates an instance of an anonymous inner class with a single method. The method is not called at the time of creation. Instead, it is called at some later point as a callback.
I believe you want to call the method immediately and pass the results as a parameter. So do exactly that! Do not wrap the call in a lambda expression:
List<FieldDto> result = jdbcTemplate.query("select * from V_FIELD where FIELD_KEY = '" + fieldKey + "'",
getFieldDto(rs, rowNum));
Additionally, you should be very wary about concatenating strings to create a SQL query. This possibly leaves your app open to a SQL injection attack if you concatenate a String whose value comes from user input. Instead, you should use syntax like FIELD_KEY = ?
in your query and the appropriate JDBC call which provides the parameters for the ?
placeholder. JDBC will then clean all input to reduce the risk of an attack.
Upvotes: 2