梦相随1006

版权归 梦相随1006 所有,未经 https://www.cnblogs.com/xin1006 作者许可,严禁转载

导航

Spring03-jdbc

1,Spring集成Jdbc,需要导入spring包和数据库驱动包,这里我们使用的是mysql驱动包

2,选择一个数据源(DBCP,C3P0),这里我们使用DBCP,需要导入DBCP驱动包

3,创建jdbc.properties文件,设置数据库的连接信息

3,在beans.xml中导入相应的properties文件

4,写相应的dao,并且为这个dao创建jdbcTemplate对象,它需要DataSource构造

  --实体类:

package com.yangw.spring.model;

public class User {

    private int id;
    private String name;
    private int age;
    
    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 int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    
    /**
     *
     * create table t_user(
          id int auto_increment primary key ,
          name varchar(50),
          age int );
     */
    
}

  --UserDao接口与实现类

package com.yangw.spring.dao;

import java.util.List;

import com.yangw.spring.model.User;

public interface IUserDao {

    public void addUser(User user);
    
    public void delUser(int id);
    
    public User loadUser(int id);
    
    public List<User> loadAllUser();
}
package com.yangw.spring.dao;

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

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Repository;

import com.yangw.spring.model.User;

@Repository("userJdbcDao")
public class UserDao implements IUserDao {

    private JdbcTemplate  jdbcTemplate;
    
    @Resource //注入dataSoucre
    public void setDataSource(DataSource dataSource){
        jdbcTemplate=new JdbcTemplate(dataSource);
    }
    @Override
    public void addUser(final User user) {
        //插入一条数据,但是自增的主键id没法得到
        //jdbcTemplate.update("insert into t_user(name,age) values(?,?)",user.getName(),user.getAge());
        
        final String sql="insert into t_user(name,age) values(?,?)";
        
        //获取自增的key的方法
        KeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(
            new PreparedStatementCreator() {
                public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
                    PreparedStatement ps =conn.prepareStatement(sql,new String[]{"id"});
                    ps.setString(1, user.getName());
                    ps.setInt(2, user.getAge());
                    return ps;
                }
            }, keyHolder);
        
        System.out.println(keyHolder.getKey());
    }

    @Override
    public void delUser(int id) {
        jdbcTemplate.update("delete from t_user where id=?",id);
    }

    @Override
    public User loadUser(int id) {
        String sql="select * from t_user where id=?";
        return jdbcTemplate.queryForObject(sql, new Object[]{id}, new UserMapper());
    }
    @Override
    public List<User> loadAllUser() {
        
        //获取记录数
        String sql1="select count(*) from t_user";
        int count=jdbcTemplate.queryForInt(sql1);
        System.out.println("count:"+count);
        
        //获取记录的一个字段值
        String sql2="select name from t_user";
        List<String> names=jdbcTemplate.queryForList(sql2, String.class);
        for(String name:names){
            System.out.println("name--->"+name);
        }
        
        //获取记录的几个字段的值
        String sql3="select name,age from t_user";
        SqlRowSet sqlRowSet=jdbcTemplate.queryForRowSet(sql3);
        while(sqlRowSet.next()){
            System.out.println("name--->"+sqlRowSet.getString("name")+"--age-->"+sqlRowSet.getInt("age"));
            
        }
        
        //获取所有记录
        String sql="select * from t_user";
        return jdbcTemplate.query(sql, new UserMapper());
    }

    /**
     * 在多个地方用的话,建议写成内部类,而不是匿名内部类
     * 如果在外部也会大量使用,建议写成独立的一个类
     * @author Administrator
     *
     */
    private class UserMapper implements RowMapper<User>{

        @Override
        public User mapRow(ResultSet rs, int rowNum) throws SQLException {
            User user=new User();
            user.setId(rs.getInt("id"));
            user.setName(rs.getString("name"));
            user.setAge(rs.getInt("age"));
            System.out.println(rowNum+"rowNum"); //rowNum是每次迭代的下标
            return user;
        }    
    }

}

 

--测试类

 

package com.yangw.spring.test;

import java.util.List;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.yangw.spring.dao.IUserDao;
import com.yangw.spring.model.User;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/beans.xml")
/**
 * 当使用了@RunWith,@ContextConfiguration注解之后,就可以直接在Test中进行依赖注入
 * @author Administrator
 */
public class TestJdbc {
    
    @Resource
    private IUserDao userJdbcDao;
   
    @Test
    public void testJdbc(){
        
       User user=new User();
       user.setName("lisi");
       user.setAge(20);
       userJdbcDao.addUser(user);
    }
    @Test
    public void testLoadUser(){
        User user=userJdbcDao.loadUser(1);
        System.out.println(user.getName());
    }
    @Test
    public void testLoadAllUsers(){
        List<User> users=userJdbcDao.loadAllUser();
        System.out.println(users.size());
    }
}

 

 

  --配置文件bean.xml

<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:aop="http://www.springframework.org/schema/aop"
     xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context-3.0.xsd
            http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop.xsd">

   <!--1, 打开Spring的annotation -->
   <context:annotation-config/>
   <!-- 2, 设定Spring去那些包中找annotation -->
   <context:component-scan base-package="com.yangw.spring" />
    
   <!--
           使用dbcp没有成功, 加的是commons-dbcp-1.4.jar 
          class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
因此使用下面的spring框架提供的作了测试
--> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" > <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <context:property-placeholder location="jdbc.properties"/> </beans>

 

  --jdbc.properties文件

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_test
jdbc.username=root
jdbc.password=123456

 

posted on 2013-10-22 10:00  梦相随1006  阅读(186)  评论(0编辑  收藏  举报