Spring DAO之JDBC

Spring DAO之JDBC
 
Spring提供的DAO(数据访问对象)支持主要的目的是便于以标准的方式使用不同的数据访问技术, 如JDBC,Hibernate或者JDO等。它不仅可以让你方便地在这些持久化技术间切换, 而且让你在编码的时候不用考虑处理各种技术中特定的异常。
 
为了便于以一种一致的方式使用各种数据访问技术,如JDBC、JDO和Hibernate, Spring提供了一套抽象DAO类供你扩展。这些抽象类提供了一些方法,通过它们你可以 获得与你当前使用的数据访问技术相关的数据源和其他配置信息。
 
Dao支持类:
 
JdbcDaoSupport - JDBC数据访问对象的基类。 需要一个DataSource,同时为子类提供 JdbcTemplate。
 
HibernateDaoSupport - Hibernate数据访问对象的基类。 需要一个SessionFactory,同时为子类提供 HibernateTemplate。也可以选择直接通过 提供一个HibernateTemplate来初始化, 这样就可以重用后者的设置,例如SessionFactory, flush模式,异常翻译器(exception translator)等等。
 
JdoDaoSupport - JDO数据访问对象的基类。 需要设置一个PersistenceManagerFactory, 同时为子类提供JdoTemplate。
 
JpaDaoSupport - JPA数据访问对象的基类。 需要一个EntityManagerFactory,同时 为子类提供JpaTemplate。
 
 
本节主要讨论Sping对JdbcDaoSupport的支持。
 
下面是个例子:
 
drop table if exists user;

/*==============================================================*/
/* Table: user                                                  */
/*==============================================================*/
create table user
(
   id                   bigint AUTO_INCREMENT not null,
   name                 varchar(24),
   age                   int,
   primary key (id)
);
 
public class User {
     private Integer id;
     private String name;
     private Integer age;

     public Integer getId() {
         return id;
    }

     public void setId(Integer id) {
         this.id = id;
    }

     public String getName() {
         return name;
    }

     public void setName(String name) {
         this.name = name;
    }

     public Integer getAge() {
         return age;
    }

     public void setAge(Integer age) {
         this.age = age;
    }
}
 
/**
* Created by IntelliJ IDEA.<br>
* <b>User</b>: leizhimin<br>
* <b>Date</b>: 2008-4-22 15:34:36<br>
* <b>Note</b>: DAO接口
*/
public interface IUserDAO {
     public void insert(User user);

     public User find(Integer id);
}
 
 
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
* Created by IntelliJ IDEA.<br>
* <b>User</b>: leizhimin<br>
* <b>Date</b>: 2008-4-22 13:53:56<br>
* <b>Note</b>: 基类DAO,提供了数据源注入
*/
public class BaseDAO {
     private DataSource dataSource;

     public DataSource getDataSource() {
         return dataSource;
    }

     public void setDataSource(DataSource dataSource) {
         this.dataSource = dataSource;
    }

     public Connection getConnection() {
        Connection conn = null;
         try {
            conn = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
         return conn;
    }
}
 
 
/**
* Created by IntelliJ IDEA.<br>
* <b>User</b>: leizhimin<br>
* <b>Date</b>: 2008-4-22 15:36:04<br>
* <b>Note</b>: DAO实现
*/
public class UserDAO extends BaseDAO implements IUserDAO {

     public JdbcTemplate getJdbcTemplate(){
         return new JdbcTemplate(getDataSource());
    }
     public void insert(User user) {
        String name = user.getName();
         int age = user.getAge().intValue();

//        jdbcTemplate.update("INSERT INTO user (name,age) "
//                + "VALUES('" + name + "'," + age + ")");

        String sql = "insert into user(name,age) values(?,?)";
        getJdbcTemplate().update(sql, new Object[]{name,age});
    }

     public User find(Integer id) {
        List rows = getJdbcTemplate().queryForList(
                 "SELECT * FROM user WHERE id=" + id.intValue());

        Iterator it = rows.iterator();
         if (it.hasNext()) {
            Map userMap = (Map) it.next();
            Integer i = new Integer(userMap.get( "id").toString());
            String name = userMap.get( "name").toString();
            Integer age = new Integer(userMap.get( "age").toString());

            User user = new User();

            user.setId(i);
            user.setName(name);
            user.setAge(age);

             return user;
        }
         return null;
    }
}
 
<? xml version ="1.0" encoding ="UTF-8" ?>
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
        "http://www.springframework.org/dtd/spring-beans.dtd">

< beans >
     < bean id ="dataSource"
           class ="org.apache.commons.dbcp.BasicDataSource" singleton ="true" >
         < property name ="driverClassName" >
             < value >com.mysql.jdbc.Driver </ value >
         </ property >
         < property name ="url" >
             < value >jdbc:mysql://localhost:3306/springdb </ value >
         </ property >
         < property name ="username" >
             < value >root </ value >
         </ property >
         < property name ="password" >
             < value >leizhimin </ value >
         </ property >
     </ bean >

     < bean id ="baseDAO" class ="com.lavasoft.springnote.ch05_jdbc03_temp.BaseDAO" abstract ="true" >
         < property name ="dataSource" >
             < ref bean ="dataSource" />
         </ property >
     </ bean >

     < bean id ="userDAO"
           class ="com.lavasoft.springnote.ch05_jdbc03_temp.UserDAO" parent ="baseDAO" >
     </ bean >

</ beans >
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

/**
* Created by IntelliJ IDEA.<br>
* <b>User</b>: leizhimin<br>
* <b>Date</b>: 2008-4-22 15:59:18<br>
* <b>Note</b>: 测试类,客户端
*/
public class SpringDAODemo {
     public static void main(String[] args) {
        ApplicationContext context = new FileSystemXmlApplicationContext( "D:\\_spring\\src\\com\\lavasoft\\springnote\\ch05_jdbc03_temp\\bean-jdbc-temp.xml");
        User user = new User();
        user.setName( "hahhahah");
        user.setAge( new Integer(22));
        IUserDAO userDAO = (IUserDAO) context.getBean( "userDAO");
        userDAO.insert(user);
        user = userDAO.find( new Integer(1));
        System.out.println( "name: " + user.getName());
    }
}
 
运行结果:
log4j:WARN No appenders could be found for logger (org.springframework.core.CollectionFactory).
log4j:WARN Please initialize the log4j system properly.
name: jdbctemplate

Process finished with exit code 0

你可能感兴趣的:(DAO,spring,jdbc,职场,休闲)