论坛首页 Java企业应用论坛

Spring JDBC 使用继承的JdbcDaoSupport 的方式获取JdbcTemplate 为null

浏览 2498 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2016-06-18  
参考  Spring + JdbcTemplate + JdbcDaoSupport examples 写一个小DEMO .遇到的问题,纠结一天了,希望有人能帮忙解决。不胜感激。 QQ:121005752

applicationContext.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"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	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.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

	<bean id="userDao" class="com.example.dao.impl.UserDaoImpl">
		<property name="dataSource" ref="dataSource" />
	</bean>

	<bean id="dataSource"
		class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://localhost:3306/mysql" />
		<property name="username" value="root" />
		<property name="password" value="root" />
	</bean>

	<context:component-scan base-package="com.example" />

	<mvc:annotation-driven />
</beans>


UserDao.java
package com.example.dao;

import java.util.HashMap;

public interface UserDao {
	public HashMap findByName(String name);
}



UserDaoImpl.java
package com.example.dao.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;

import com.example.dao.UserDao;

public class UserDaoImpl extends JdbcDaoSupport implements UserDao {


	public HashMap findByName(String name) {
		HashMap<String, String> map = new HashMap<String, String>();

		String sql = "select * from t_user a  where a.username = 'SUPERUSR'";
		JdbcTemplate jdbcTemplate = this.getJdbcTemplate() ;
		System.out.println("--> jdbcTemplate: " + jdbcTemplate);

		List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);

		if (list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				Map<String, Object> tmp = list.get(i);
				map.put("username", (String)tmp.get("USER_NAME"));
				map.put("passwor", (String)tmp.get("PASSWORD"));
				System.out.println("-->username: " + (String)tmp.get("USER_NAME"));
			}
		}

		return map;
	}

}
   发表时间:2016-06-19  
说具体问题是什么,有异常的话把异常日志贴上
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics