Spring 資料來源配置與應用
 
Spring對資料庫操作都依賴資料來源。
Spring有預設的資料來源實現org.springframework.jdbc.datasource.DriverManagerDataSource,但也可以配置其他的資料來源實現,比如DBCP的資料來源public class BasicDataSource  implements javax.sql.DataSource。
 
一旦獲取到資料來源DataSource例項,就可以通過DataSource獲取到資料庫連線,運算元據庫。
 
下面是Spring資料來源的一個簡單配置和應用。
應用環境:MySQL5
 
 
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;
    }
}

 
public interface IUserDAO {
    public void insert(User user);

    public User find(Integer id);
}

 
/**
* Created by IntelliJ IDEA.<br>
* <b>User</b>: leizhimin<br>
* <b>Date</b>: 2008-4-22 11:40:18<br>
* <b>Note</b>: 子類DAO
*/

public class UserDAO extends BaseDAO implements IUserDAO {
    public void insert(User user) {
        String name = user.getName();
        int age = user.getAge().intValue();

        Connection conn = null;
        Statement stmt = null;

        try {
            conn = getConnection();
            stmt = conn.createStatement();
            stmt.execute(“INSERT INTO user (name,age) “ + “VALUES(`” + name + “`,” + age + “)”);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        finally {
            if (stmt != null) {
                try {
                    stmt.close();
                }
                catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                }
                catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public User find(Integer id) {
        Connection conn = null;
        Statement stmt = null;

        try {
            conn = getConnection();
            stmt = conn.createStatement();

            ResultSet result = stmt.executeQuery(
                    “SELECT * FROM user WHERE id=” + id.intValue());
            if (result.next()) {
                Integer i = new Integer(result.getInt(1));
                String name = result.getString(2);
                Integer age = new Integer(result.getInt(3));

                User user = new User();
                user.setId(i);
                user.setName(name);
                user.setAge(age);

                return user;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        finally {
            if (stmt != null) {
                try {
                    stmt.close();
                }
                catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                }
                catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

        return null;
    }
}

 
/**
* 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;
    }
}

<?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.springframework.jdbc.datasource.DriverManagerDataSource”>
        <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_jdbc02.BaseDAO” abstract=”true”>
        <property name=”dataSource”>
            <ref bean=”dataSource”/>
        </property>
    </bean>

    <bean id=”userDAO”
          class=”com.lavasoft.springnote.ch05_jdbc02.UserDAO” parent=”baseDAO”>
    </bean>
</beans>

 
/**
* Created by IntelliJ IDEA.<br>
* <b>User</b>: leizhimin<br>
* <b>Date</b>: 2008-4-22 11:41:34<br>
* <b>Note</b>: 客戶端測試
*/

public class SpringDAODemo {
    public static void main(String[] args) {
        ApplicationContext context = new FileSystemXmlApplicationContext(“D:\_spring\src\com\lavasoft\springnote\ch05_jdbc02\bean-jdbc.xml”);
        User user = new User();
        user.setName(“caterpillar”);
        user.setAge(new Integer(30));
        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

 
 
注意:Spring配置檔案中對繼承的配置,DataSource注入方式,通過繼承來注入,從而簡化程式設計。
 
上面用的是Spring的自己的資料來源實現,現在假如要換成apache的DBCP資料來源,則配置改為如下即可:
    <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>
 
實際上僅僅是更改一下資料來源的calss實現。