Calling an insert inside of a ResultHandler gives null pointer exception - spring

I am implementing a filter which, under certain conditions, has to make inserts in some tables.
First of all I call my result handler like this:
DateTime midnight = ...//date
MyHandler handler = new MyHandler();
MyFilter filterChain = new MyFilter();
handler.addFilter(filterChain);
//query is a select based on the date passed as parameter
session.select("com.MyRequestMapper.getAllRequests", midnight.toDateTime(), handler);
This is my handler:
#Component
public class MyHandler implements ResultHandler{
#Autowired
private AnotherTableMapper mapper;
...
public void handleResult(ResultContext ctx){
MyRequest req = (MyRequest)ctx.getResultObject();
if(this.filter.apply(req))
mapper.insertRequest(req);
}
This insert gives me the following:
### Error querying database. Cause: java.lang.NullPointerException
### The error may exist in com/MyRequestMapper.java (best guess)
### The error may involve com.MyRequestMapper.getAllRequests
### The error occurred while handling results
### SQL: SELECT* FROM MY_REQUESTS where request_date = ?
### Cause: java.lang.NullPointerException
...but I am performing an insert not a select! And on top of that the insert is not made on All_REQUESTS table!
Why is that?

Related

Spring Boot SimpleJdbcCall fails when Oracle Function has no input values

There are two Oracle functions that I need to call from a Spring Boot application. They are both in the same schema. One of the functions takes a String input value. The call to that function returns the expected result with no errors. The other function takes no input values. The call to that function results in the following exception: java.sql.SQLException: Missing IN or OUT parameter at index:: 1. I'm not sure why this is happening. I'll show the code for both the Oracle function and the Spring Boot call below.
Oracle Function:
create or replace FUNCTION "GETUNIQUEID" RETURN VARCHAR2
IS
returnuniqueid VARCHAR2(26);
BEGIN
SELECT to_char(sysdate, 'MMDDYY-HH24MISS-')||manchester.globalpid.nextval INTO returnuniqueid FROM DUAL;
RETURN (returnuniqueid);
END GETUNIQUEID
Spring Boot code:
#Autowired
private JdbcTemplate jdbcTemplate;
private SimpleJdbcCall simpleJdbcCallFunction;
#Override
public void run(String... args) throws Exception {
simpleJdbcCallFunction = new SimpleJdbcCall(jdbcTemplate)
.withFunctionName("GETUNIQUEID");
String uniqueId = simpleJdbcCallFunction.executeFunction(String.class);
}
The exception thrown is java.sql.SQLException: Missing IN or OUT parameter at index:: 1
Thanks very much for taking a look at this issue.

JDK8 Functional Programming a function can throw a exception?

I have one requirement
Get the employee information from the employee repository.
Update the employee information with some additional information.
Transform the employee object to gatewayRequest object.
call the gateway service and get the response.
from the response get the return code of the gateway call.
For this requirement, i am using functional programming to achieve the result.
Here I have created the multiple functions in my Service layer
final Function<String, Employee> getRegisteredEmployee =
localId -> employeeRepository.findById(employeeId).
orElseThrow(() -> new ResourceNotFoundException("ResourceNotFound"));
final Function<Employee, Employee> updateEmployeAddressandSave =
employe -> {
String status = //some logic to identitythe Employee
Employee e = new Employee(employee.getName(),employee.getAddress ,"INTERNAL_EMPLOYEE")
Employee emp = employeeRepository.save(e);
return emp;
};
Likewise, I created different functions and then I am using the andThen method of the functional interface to get the results
getRegisteredEmployee.
andThen(updateEmployeAddressandSave).
andThen(transformTheEmployeeToGatewayRequest).
andThen(allgateWayClinet).apply(12);
According to the functional programming model, a function should take input and give some output; it should not throw any exception. But in my example getRegisteredEmployee throws an exception if employee is not found.
Hence, am I not following the functional programming core principles?
what is the alternate way to throw the exception in functional programming?
While not adhering to principles, it is technically possible to create a functional interface that will throw a checked exception.
#FunctionalInterface
interface CheckedFunction<A, B> {
B apply(A a) throws Exception;
}
(Since you're using andThen you'll need to implement that as well using the default keyword. Remember, though, that the functional interface must have at most one non-default method, so you'll have to provide the andThen implementation defaulted.)
So, as an example, you would be able to do something like:
public void doThings(Integer id) throws Exception {
CheckedFunction<Integer, Employee> fn = (id) -> someMethodThatReturnsAnEmployeeOrThrows(id);
fn.apply(id)
.map( ... ) // ... some other stuff
}
As I mentioned, this doe not adhere to principles; I only go down this path when I absolutely have to bubble the exception up. Other Java 8 features such as Optional are more appropriate in this situation. (Since it looks like you're using spring's JPA implementation, you can define your findById method to return an Optional<Employee>.)
Method getRegisteredEmployee can return an Optional object instead of throwing an exception.
final Function<String, Employee> getRegisteredEmployee =
localId -> employeeRepository.findById(employeeId);
final Function<Employee, Employee> updateEmployeAddressandSave =
employe -> {
if(employe.isPresent()) {
employe.get();
...
String status = //some logic to identitythe Employee
Employee e = new Employee(employee.getName(),employee.getAddress ,"INTERNAL_EMPLOYEE")
Employee emp = employeeRepository.save(e);
return new Optional(emp);
} else {
return Optional.empty();
}
};
etc...

Spring Data Rest ava.lang.IllegalArgumentException

I am getting
java.lang.IllegalArgumentException: Cannot get property 'objects' on null object
error when I intentionally test spring data rest api simulating a user passing bad url as in
http://myurl/findByDate?year=&month="
The year and month are Integers , but in this case I am simulating the user not passing any value.
The app is using the:
public interface myRepo extends PagingAndSortingRepository<myClass, Long> {}
interface and there is no explicit controller provided in a controller class. The data rest interface provides the following:
#Query("Select c from myPOJO c where (YEAR(c.myDate) = :year AND MONTH(c.myDate) = :month)")
Page findByDate(#Param("year") int year,
#Param("month") int month,
Pageable pageable);
I can see why the exception is being thrown ... but providing a generic exception handler to handle it does not seem to resolve the issue.
#ControllerAdvice
public class ExceptionControllerAdvice {
#ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> exceptionHandler(Exception ex) {
ErrorResponse error = new ErrorResponse();
error.setErrorCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
error.setMessage("Please contact your administrator");
//return new ResponseEntity<ErrorResponse>(error, HttpStatus.OK);
return new ResponseEntity<ErrorResponse>(error, HttpStatus.METHOD_NOT_ALLOWED);
}
}
Any advise on how to trap this data rest exception would be appreciate it.
java.lang.IllegalArgumentException: Cannot get property 'objects' on null object
Thank you
This is resolved by using the object Integer instead of the primitive Int for the param. This appears to handle the conversion to default value and avoid nulls.
Thanks

Spring Batch onSkipInWrite to get Item object rather than entity object

I am using spring batch for reading data from csv.
The Item Class is EmployeeItem where I set the values from CSV.
During persist when any exception is thrown for example DataIntegrity Violation, the process is skipped and the skipped data is written to the error file.
onSkipInWrite where I will get only the Employee entity.
public void onSkipInWrite(Employee item, Throwable t) {
errorItemWriter.write(items);
}
If its a validation error during the process time
public void onSkipInProcess(EmployeeItem item, Throwable t) {
}
I will get an EmployeeItem object which I can directly write the skipped data to the error file, but in the case of onSkipInWrite I will get the Employee entity only.
I have to reset the values from Employee to EmployeeItem
Any possibility to get the EmployeeItem in onSkipInWrite?

Hibernate not executing queries until response is commited

I am doing few hibernate save operations in spring's transactional service class.
My expectation is that by the time method execution finishes hibernate should write data to database.
But hibernate is actually executing those queries only when controller is about to return a response.
My sample code is as follows.
#Controller
public class TestController {
#Autowired
private SaveService saveService;
#RequestMapping(value = "saveData", method = RequestMethod.POST)
public String saveData(HttpServletRequest request, Model model) {
try {
saveService.saveData(object1, object2, object3); // LINE 1
sendEmail(); // LINE 2
//some code here // LINE 3
} catch(Exception e) {
//log exception
//return error message
}
}
}
#Service("saveService")
#Transactional
public class SaveServiceImpl implements SaveService {
#Autowired
private SaveDAO saveDAO;
public void saveData(Object objec1, Object objec2, Object objec3) {
saveDAO.save(object1);
saveDAO.save(object2);
saveDAO.save(object3);
}
}
In above code I am calling SaveService.saveData() method from controller. And if save is successful I want to go ahead and send an email. But if for some reason SaveService.saveData() throws an exception i don't want
to send the email.
When I performed some tests it was observed that even if SaveService.saveData() throws an exception it's not thrown
until the email is sent from controller. I want that if a call to saveService.saveData() at 'LINE 1' in controller
throws an exception the next line that sends email should not get executed.
I wanted to know if this is expected hibernate behavior and if it is what can I do to tell hibernate to execute
queries before exiting service methods.
Thank you.
This behavior is due to hibernate optimizations. Hibernate will wait until the last time possible to execute the sentences.
You can avoid this with session.flush(), Flushing the session forces Hibernate to synchronize the in-memory state of the Session with the database (i.e. to write changes to the database).
The problem here is when an exception occurs, your the variables/objects are not initialized in the catch block and you are accessing it.
As it looks like you have just added a snippet of the code in question, so I guess the variables object1, object2, object3 needs to initalized to null.
for example: object1=null

Resources