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>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章