Share on Google+Share on Google+

Spring MVC JDBC Example

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="">
	<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



Posted on: August 31, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial 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.