Spring JDBC provides a simplified approach to interact with relational databases by reducing boilerplate JDBC code. It uses JdbcTemplate to handle common tasks like connection management, query execution, and exception handling efficiently.
- Eliminates the need for manual resource handling like Connection, Statement, and ResultSet closing.
- Provides JdbcTemplate to execute SQL queries and updates easily.
- Converts SQL exceptions into a consistent, unchecked exception hierarchy for better handling
Prerequisite:
- Basic understanding of JDBC
- Installed MySQL database
- Java IDE (IntelliJ IDEA or Eclipse)
- Spring and MySQL Connector JAR files
Step-by-Step Implementation
Step 1: Create Java Project
- Create a simple Java project in IntelliJ IDEA or Eclipse.
- Set up the project structure (src folder, packages, etc.).
- Ensure Java is properly configured in the IDE.
Step 2: Setup Database
- Create a MySQL database (e.g., studentdb).
- Create a table (e.g., hostelstudentinfo).
- Insert sample records into the table for testing.
- Verify data using MySQL Workbench or CLI.
👁 Data Inside our MySQL DatabaseStep 3: Create DAO Class
- Create StudentDAO class.
- Define DB properties: driver , url , username , password
- Use setter injection for these properties.
- Create method selectAllRows() to fetch data using JDBC.
Step 4: Add Dependencies (JARs)
- Add Spring JDBC JAR.
- Add MySQL Connector JAR.
- Ensure libraries are added to build path correctly.
- Verify no missing dependency errors.
Step 5: Configure Spring Bean (beans.xml)
- Define
StudentDAO bean. - Inject database values using setter injection.
- Configure: Driver class , Database URL , Username & password
- Ensure correct XML schema setup.
Spring Configuration (beans.xml):
Step 6: Create Main Class
- Load Spring Application Context using ClassPathXmlApplicationContext.
- Retrieve StudentDAO bean using getBean().
- Call selectAllRows() method.
- Run the application to fetch data.
Output: After running the program, the following output will be displayed:
Retrieving all student data..
1 Asish 300.5 Veg
2 Vicky 245.89 Non Veg
3 Anshul 123.67 Veg
You can see we have successfully fetched the data from the MySQL Database.