链接数据库配置properties apicationcontext.xml配置文件

properties配置文件中写入链接数据库

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:aop="http://www.springframework.org/schema/aop" 
       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/aop
                           http://www.springframework.org/schema/aop/spring-aop.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd">
	<!-- 加载配置文件 
		"classpath:"	前缀表示src下  或者类路径下"
		在配置文件之后通过${key}获得内容 
	-->
	<context:property-placeholder location="classpath:com/itheima/e_properties/jdbcInfo.properties"/>
	<!-- 创建数据源 -->				
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="${jdbc.driverClass}"></property>
		<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
		<property name="user" value="${jdbc.user}"></property>
		<property name="password" value="${jdbc.password}"></property>
	</bean>
	
	
	
	<!-- 配置dao
		*dao 继承JdbcDaoSupport,之后只需要注入数据源,底层自动创建模板
	 -->
	<bean id="UserDao" class="com.itheima.e_properties.UserDao">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
 
</beans>

使用jdbcTemplate 模板操作dao层代码

package com.itheima.e_properties;

import java.util.List;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import com.itheima.a_domain.User;

public class UserDao extends JdbcDaoSupport{
	
	
	
	public void update(User user) {
		String sql="update t_user set username=?,password=? where id=?";
		Object[] args= {user.getUsername(),user.getPassword(),user.getId()};
		this.getJdbcTemplate().update(sql, args);
	
	}
	public List<User> findAll() {
		// TODO 自动生成的方法存根
		
		return this.getJdbcTemplate().query("select * from t_user", new BeanPropertyRowMapper<User>(User.class));
	}
}

posted @ 2019-07-22 21:40  丶宇  阅读(324)  评论(0编辑  收藏  举报