Home Tutorial Spring Spring3 Web Spring MVC JDBC Example

 
 

Spring MVC JDBC Example
Posted on: August 31, 2012 at 12:00 AM
Advertisement
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"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
	<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="" />
</bean>

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" />
	</property>
</bean>

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" />
</bean>

Now in the service class you can do as follows

	@Autowired
	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) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
	}

Download Complete Source Code

Advertisement

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
 

 

 

DMCA.com