熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java開源技術 >> 正文

Spring 數據源配置與應用

2022-06-13   來源: Java開源技術 

  Spring 數據源配置與應用

  Spring對數據庫操作都依賴數據源

  Spring有默認的數據源實現orgspringframeworkjdbcdatasourceDriverManagerDataSource但也可以配置其他的數據源實現比如DBCP的數據源public class BasicDataSource  implements javaxsqlDataSource

  一旦獲取到數據源DataSource實例就可以通過DataSource獲取到數據庫連接操作數據庫

  下面是Spring數據源的一個簡單配置和應用
    應用環境MySQL

    drop table if exists user;

/*==============================================================*/
/* Table: user                                                  */
/*==============================================================*/
create table user
(
   id                   bigint AUTO_INCREMENT not null
   name                 varchar()
   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) {
        thisid = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        thisname = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        thisage = 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>: ::<br>
* <b>Note</b>: 子類DAO
*/
public class UserDAO extends BaseDAO implements IUserDAO {
    public void insert(User user) {
        String name = usergetName();
        int age = usergetAge()intValue();

        Connection conn = null;
        Statement stmt = null;

        try {
            conn = getConnection();
            stmt = conncreateStatement();
            stmtexecute(INSERT INTO user (nameage) + VALUES( + name + + age + ));
        } catch (SQLException e) {
            eprintStackTrace();
        }
        finally {
            if (stmt != null) {
                try {
                    stmtclose();
                }
                catch (SQLException e) {
                    eprintStackTrace();
                }
            }
            if (conn != null) {
                try {
                    connclose();
                }
                catch (SQLException e) {
                    eprintStackTrace();
                }
            }
        }
    }

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

        try {
            conn = getConnection();
            stmt = conncreateStatement();

            ResultSet result = stmtexecuteQuery(
                    SELECT * FROM user WHERE id= + idintValue());
            if (resultnext()) {
                Integer i = new Integer(resultgetInt());
                String name = resultgetString();
                Integer age = new Integer(resultgetInt());

                User user = new User();
                usersetId(i);
                usersetName(name);
                usersetAge(age);

                return user;
            }
        } catch (SQLException e) {
            eprintStackTrace();
        }
        finally {
            if (stmt != null) {
                try {
                    stmtclose();
                }
                catch (SQLException e) {
                    eprintStackTrace();
                }
            }
            if (conn != null) {
                try {
                    connclose();
                }
                catch (SQLException e) {
                    eprintStackTrace();
                }
            }
        }

        return null;
    }
}

    /**
* Created by IntelliJ IDEA<br>
* <b>User</b>: leizhimin<br>
* <b>Date</b>: ::<br>
* <b>Note</b>: 基類DAO提供了數據源注入
*/
public class BaseDAO {
    private DataSource dataSource;

    public DataSource getDataSource() {
        return dataSource;
    }

    public void setDataSource(DataSource dataSource) {
        thisdataSource = dataSource;
    }

    public Connection getConnection() {
        Connection conn = null;
        try {
            conn = dataSourcegetConnection();
        } catch (SQLException e) {
            eprintStackTrace();
        }
        return conn;
    }
}

    <?xml version= encoding=UTF?>
<!DOCTYPE beans PUBLIC //SPRING/DTD BEAN/EN
        beansdtd>

<beans>
    <bean id=dataSource
          class=orgspringframeworkjdbcdatasourceDriverManagerDataSource>
        <property name=driverClassName>
            <value>commysqljdbcDriver</value>
        </property>
        <property name=url>
            <value>jdbc:mysql://localhost:/springdb</value>
        </property>
        <property name=username>
            <value>root</value>
        </property>
        <property name=password>
            <value>leizhimin</value>
        </property>
    </bean>

    <bean id=baseDAO class=comlavasoftspringnotech_jdbcBaseDAO abstract=true>
        <property name=dataSource>
            <ref bean=dataSource/>
        </property>
    </bean>

    <bean id=userDAO
          class=comlavasoftspringnotech_jdbcUserDAO parent=baseDAO>
    </bean>
</beans>

    /**
* Created by IntelliJ IDEA<br>
* <b>User</b>: leizhimin<br>
* <b>Date</b>: ::<br>
* <b>Note</b>: 客戶端測試
*/
public class SpringDAODemo {
    public static void main(String[] args) {
        ApplicationContext context = new FileSystemXmlApplicationContext(D:\\_spring\\src\\com\\lavasoft\\springnote\\ch_jdbc\\beanjdbcxml);
        User user = new User();
        usersetName(caterpillar);
        usersetAge(new Integer());
        IUserDAO userDAO = (IUserDAO) contextgetBean(userDAO);
        userDAOinsert(user);
        user = userDAOfind(new Integer());
        Systemoutprintln(name: + usergetName());
    }
}

  運行結果

    logj:WARN No appenders could be found for logger (orgreCollectionFactory)
logj:WARN Please initialize the logj system properly
name: jdbctemplate

Process finished with exit code

  注意Spring配置文件中對繼承的配置DataSource注入方式通過繼承來注入從而簡化編程
 
    上面用的是Spring的自己的數據源實現現在假如要換成apache的DBCP數據源則配置改為如下即可

    <bean id=dataSource
      class=monsdbcpBasicDataSource singleton=true>
    <property name=driverClassName>
        <value>commysqljdbcDriver</value>
    </property>
    <property name=url>
        <value>jdbc:mysql://localhost:/springdb</value>
    </property>
    <property name=username>
        <value>root</value>
    </property>
    <property name=password>
        <value>leizhimin</value>
    </property>
</bean>

  實際上僅僅是更改一下數據源的calss實現


From:http://tw.wingwit.com/Article/program/Java/ky/201311/27993.html
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.