Home Tutorial Spring Spring3 Web Spring MVC JDBC Example


Share on Google+Share on Google+
Spring MVC JDBC Example
Posted on: August 31, 2012 at 12:00 AM
In this tutorial you will learn about the Spring MVC database connection

Spring MVC JDBC Example

To connect your Spring web application to the database you will have to create a DataSource and JdbcTemplate bean in your dispatcher servlet. The following is the mapping for your data source in a dispatcher servlet

<bean id="dataSource"
	<property name="driverClassName" value="com.mysql.jdbc.Driver" />
	<property name="url" value="jdbc:mysql://localhost:3306/jdbc" />
	<property name="username" value="root" />
	<property name="password" value="" />

Now this dataSource object is required to create a JdbcTemplate object

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
	<property name="dataSource">
		<ref bean="dataSource" />

Now in a class where you will do all the database operation you require this JdbcTemplate instance. You can siply inject this bean to your Service class as

<bean id="appService" class="roseindia.net.service.serviceImpl.AppServiceImpl">
	<property name="jdbcTemplate" ref="jdbcTemplate" />

Now in the service class you can do as follows

	private JdbcTemplate jdbcTemplate;

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	public void addStudent(Registration registration) {
		try {
			String sql = "INSERT INTO student(name,course,age,address) values(?,?,?,?)";
			jdbcTemplate.update(sql, new Object[] { registration.getName(),
					registration.getCourse(), registration.getAge(),
					registration.getAddress() });
		} catch (Exception e) {

Download Complete Source Code


Related Tags for Spring MVC JDBC Example:

Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: August 31, 2012

Recommend the tutorial

Advertisements Advertisements