Spring mvc Adding DAO Code

Now we gonna see how to add DAO code to our existing spring mvc application.

web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>spring-tutorial-50</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>offers</display-name>
<servlet-name>offers</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>offers</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

<description>Spring Database</description>
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/spring</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>

OffersController.java


package com.sourceforopensource.spring.web.controllers;

import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class OffersController {

/*
@RequestMapping("/")
public ModelAndView showHome() {

ModelAndView mv = new ModelAndView("home");

Map<String, Object> model = mv.getModel();

model.put("name", "<b>River</b>");

return mv;
}
*/

@RequestMapping("/")
public String showHome(Model model) {

model.addAttribute("name", "Tiffany");

return "home";
}
}

offers-servlet.xml


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:component-scan base-package="com.sourceforopensource.spring.web.controllers">
</context:component-scan>
<mvc:annotation-driven></mvc:annotation-driven>

<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsps/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>

home.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<c:out value="${name}"></c:out> <p/>

<sql:query var="rs" dataSource="jdbc/spring">
select id, name, email, text from offers
</sql:query>

<c:forEach var="row" items="${rs.rows}">
ID: ${row.id}<br/>
Name: ${row.name}<br/>
</c:forEach>

</body>
</html>

Upto now we have seen the working of spring mvc application.But, what if we have a DAO(data access object) code to be added to our web application. Which the DAO will do some CRUD operations. Lets have a look of adding the DAO code to Our spring mvc application.

we have the Offer pojo.

Offer.java


package com.sourceforopensource.spring.web.dao;

public class Offer {
private int id;
private String name;
private String email;
private String text;

public Offer() {

}

public Offer(String name, String email, String text) {
this.name = name;
this.email = email;
this.text = text;
}
public Offer(int id, String name, String email, String text) {
super();
this.id = id;
this.name = name;
this.email = email;
this.text = text;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getText() {
return text;
}

public void setText(String text) {
this.text = text;
}

@Override
public String toString() {
return "Offer [id=" + id + ", name=" + name + ", email=" + email
+ ", text=" + text + "]";
}

}

we have the OffersDAO, in this class we have configured the DataSource and JdbcTemplate. To know how to configure Datasource and JdbcTemplate http://sourceforopensource.com/spring-querying-using-jdbc-template/.

OffersDAO.java


package com.sourceforopensource.spring.web.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component("offersDao")
public class OffersDAO {

private NamedParameterJdbcTemplate jdbc;

@Autowired
public void setDataSource(DataSource jdbc) {
this.jdbc = new NamedParameterJdbcTemplate(jdbc);
}

public List<Offer> getOffers() {

return jdbc.query("select * from offers", new RowMapper<Offer>() {

public Offer mapRow(ResultSet rs, int rowNum) throws SQLException {
Offer offer = new Offer();

offer.setId(rs.getInt("id"));
offer.setName(rs.getString("name"));
offer.setText(rs.getString("text"));
offer.setEmail(rs.getString("email"));

return offer;
}

});
}

public boolean update(Offer offer) {
BeanPropertySqlParameterSource params = new BeanPropertySqlParameterSource(offer);

return jdbc.update("update offers set name=:name, text=:text, email=:email where id=:id", params) == 1;
}

public boolean create(Offer offer) {

BeanPropertySqlParameterSource params = new BeanPropertySqlParameterSource(offer);

return jdbc.update("insert into offers (name, text, email) values (:name, :text, :email)", params) == 1;
}

@Transactional
public int[] create(List<Offer> offers) {

SqlParameterSource[] params = SqlParameterSourceUtils.createBatch(offers.toArray());

return jdbc.batchUpdate("insert into offers (id, name, text, email) values (:id, :name, :text, :email)", params);
}

public boolean delete(int id) {
MapSqlParameterSource params = new MapSqlParameterSource("id", id);

return jdbc.update("delete from offers where id=:id", params) == 1;
}

public Offer getOffer(int id) {

MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue("id", id);

return jdbc.queryForObject("select * from offers where id=:id", params,
new RowMapper<Offer>() {

public Offer mapRow(ResultSet rs, int rowNum)
throws SQLException {
Offer offer = new Offer();

offer.setId(rs.getInt("id"));
offer.setName(rs.getString("name"));
offer.setText(rs.getString("text"));
offer.setEmail(rs.getString("email"));

return offer;
}

});
}

}

dao-context.xml


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:annotation-config></context:annotation-config>
<context:component-scan base-package="com.sourceforopensource.spring.web.dao">
</context:component-scan>
</beans>

Conclusion: In this post we just seen how Configure the DAO but not with using Apache DBCP. We will configure it will JNDI.

 

Balakrishna Pendyala

Author: Balakrishna Pendyala

Balakrishna is a Software Engineer working in Media Streaming Domain, and also worked on Banking and Health Care domains. His areas of interest include Object Oriented Design, SOLID Design principles, Restful Web Services and Open Source softwares including Spring, Spring Boot, and Hibernate.

If you found an error, highlight it and press Shift + Enter or click here to inform us.

Leave a Reply

Your email address will not be published. Required fields are marked *