Spring Jdbctemplate

https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html

working example: https://github.com/teachkoka/jdbctemplate

application.property 

student.db.driver = org.postgresql.Driver
student.db.url = jdbc:postgresql://127.0.0.1:5432/b6
student.db.username = postgres
student.db.password = abcd12345

Repository Class

@Repository
public class StudentRepository {
    
    public static final String INSERT_STUDENT_QUERY ="INSERT INTO STUDENT(name) VALUES (?)";
    public static final String FIND_STUDENT_QUERY ="SELECT * FROM STUDENT";
    
    @Autowired
    public JdbcTemplate jdbcTemplate;
    
    public void save(String name){
        jdbcTemplate.update(INSERT_STUDENT_QUERY,name);
        
    }
    
    public List<String> findAll(){
        
        List<Map<String, Object>>  rows= jdbcTemplate.queryForList(FIND_STUDENT_QUERY);
        ArrayList<String> list = new ArrayList<String>();
        for(Map row:rows){
            list.add((String)row.get("name"));
        }
        
        return list;
        
    }

}

 

AppConfig.java

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;

@Configuration
@ComponentScan("com.teach.koka.javaconfig")
@EnableWebMvc
@PropertySource("classpath:application.properties")
public class AppConfig {

	@Autowired
	Environment env;
	
	@Bean
	public UrlBasedViewResolver urlBasedViewResolver(){
		UrlBasedViewResolver viewResolver = new UrlBasedViewResolver();
		viewResolver.setPrefix("/WEB-INF/pages/");
		viewResolver.setSuffix(".jsp");
		viewResolver.setViewClass(JstlView.class);
		
		return viewResolver;
		
	}
	
	    @Bean
	    public MessageSource messageSource() {
		 ReloadableResourceBundleMessageSource  messageSource = new ReloadableResourceBundleMessageSource();
	        messageSource.setBasenames("application");
	        messageSource.setDefaultEncoding("UTF-8");
	        return messageSource;
	    }
	    
	    /**
		 * An alternative to the DriverManager facility, a DataSource object is
		 *  the preferred means of getting a connection.
		 */
		@Bean
		public DataSource dataSource(){
			DriverManagerDataSource dataSource = new DriverManagerDataSource();
			dataSource.setDriverClassName(env.getRequiredProperty("student.db.driver"));
			dataSource.setUrl(env.getRequiredProperty("student.db.url"));
			dataSource.setUsername(env.getRequiredProperty("student.db.username"));
			dataSource.setPassword(env.getRequiredProperty("student.db.password"));
			
			return dataSource;
		}
		
		@Bean
		public JdbcTemplate jdbcTemplate(){
			 JdbcTemplate jdbcTemplate = new JdbcTemplate();
			 jdbcTemplate.setDataSource(dataSource());
		
			 return jdbcTemplate;
		}
	
}

Controller class

package com.teach.koka.javaconfig.jdbctemplate.controller;

import java.util.*;

import javax.validation.Valid;






import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.teach.koka.javaconfig.jdbctemplate.model.Student;
import com.teach.koka.javaconfig.jdbctemplate.repository.StudentRepository;


@Controller
@RequestMapping(value="/student")
public class StudentController {

	@Autowired
	StudentRepository repository;
	
	@RequestMapping(method=RequestMethod.GET)
	public String studentData(Model model){
		Student student = new Student();
		model.addAttribute("student",student);
		model.addAttribute("message","Welcome...");
		return "student-login";		
	}
	
	    @RequestMapping(method=RequestMethod.POST)
    public String postStudentData(@ModelAttribute("student") @Valid Student student,BindingResult result, Model model){
        if(result.hasErrors()){
            return "student-login";
        }
        String text ="Hey Welcome to MVC world...,"+student.getName();
        repository.save(student.getName());
        model.addAttribute("message",text);
        List list = repository.findAll();
        model.addAttribute("list",list);
        return "success";
    }
}

 

Iterator on jsp

 

<div>
<c:forEach var="student" items="${list}">
 <c:out value="${student}"/></br>
</c:forEach>
  </div>

 

Leave a Reply

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