Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.leapfrog.sms.dao.impl; import com.leapfrog.sms.constant.SqlConstant; import com.leapfrog.sms.dao.CourseDAO; import com.leapfrog.sms.entity.Course; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementSetter; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; import org.springframework.web.bind.annotation.ResponseBody; /** * * @author KARNAZE */ @Repository(value = "CourseDAO") public class CourseDAOImpl implements CourseDAO { @Autowired private JdbcTemplate jdbcTemplate; @Override public List<Course> getAll() { return jdbcTemplate.query(SqlConstant.COURSE_GETALL, new RowMapper<Course>() { @Override public Course mapRow(ResultSet rs, int i) throws SQLException { return mapData(rs); } }); } @Override public Course getById(int id) { return jdbcTemplate.queryForObject(SqlConstant.COURSE_GETBYID, new Object[] { id }, new RowMapper<Course>() { @Override public @ResponseBody Course mapRow(ResultSet rs, int i) throws SQLException { return mapData(rs); } }); } @Override public int insert(Course t) { return jdbcTemplate.update(SqlConstant.COURSE_INSERT, new Object[] { t.getName(), t.getPrice(), t.getDescription(), t.getStatus() }); } @Override public int delete(int id) { return jdbcTemplate.update(SqlConstant.COURSE_DELETE, new Object[] { id }); } @Override public List<Course> search(String param) { final String parameter = param; PreparedStatementSetter setter = new PreparedStatementSetter() { @Override public void setValues(PreparedStatement ps) throws SQLException { ps.setString(1, "%" + parameter + "%"); } }; return jdbcTemplate.query(SqlConstant.COURSE_SEARCH, setter, new RowMapper<Course>() { @Override public Course mapRow(ResultSet rs, int i) throws SQLException { return mapData(rs); } }); } private Course mapData(ResultSet rs) throws SQLException { Course course = new Course(); course.setId(rs.getInt("id")); course.setName(rs.getString("name")); course.setDescription(rs.getString("description")); course.setPrice(rs.getDouble("price")); course.setStatus(rs.getBoolean("status")); return course; } }