Example of PreparedStatement in Spring JdbcTemplate
We can execute parameterized query using Spring JdbcTemplate by the help of execute() method of JdbcTemplate class. To use parameterized query, we pass the instance of PreparedStatementCallback in the execute method.
Syntax of execute method to use parameterized query
It processes the input parameters and output results. In such case, you don't need to care about single and double quotes.
Method of PreparedStatementCallback interface
It has only one method doInPreparedStatement. Syntax of the method is given below:
Example of using PreparedStatement in Spring
We are assuming that you have created the following table inside the Oracle10g database.Employee.java
This class contains 3 properties with constructors and setter and getters.EmployeeDao.java
It contains one property jdbcTemplate and one method saveEmployeeByPreparedStatement. You must understand the concept of annonymous class to understand the code of the method.applicationContext.xml
The DriverManagerDataSource is used to contain the information about the database such as driver class name, connnection URL, username and password.
There are a property named datasource in the JdbcTemplate class of DriverManagerDataSource type. So, we need to provide the reference of DriverManagerDataSource object in the JdbcTemplate class for the datasource property.
Here, we are using the JdbcTemplate object in the EmployeeDao class, so we are passing it by the setter method but you can use constructor also.Test.java
This class gets the bean from the applicationContext.xml file and calls the saveEmployeeByPreparedStatement() method.
download this example (developed using MyEclipse IDE)
download this example (developed using Eclipse IDE)