2012年6月3日 星期日

[Database] DataSource

有下列管理 transaction 的方式:
  • JDBC
  • JTA
    • 管理的範圍較廣,可以包含多種不同來源。
  • DataSource

連至 DB 的方式:
  • Local -> server -> DB
    • 要透過 jndi 向 server 取得 look up service -> DATASOURCE。
    • Too dependent on server.
  • Local -> DB
    • Security issue(user, password).

If web service is on Server:
  • 可以直接對應 jndi 取得 Datasource。


If NOT:
  • 方式一: 利用 InitialContext預設會使用 jndi.properties 中的 jndi name。
public class DataSourceFactory {

    private static DataSource dataSource;

    public static synchronized DataSource getDataSource()
            throws ConnectionException, NamingException {
        if (dataSource != null) {
            return dataSource;
        }

        String datasourceJndiName = Configuration.getInstance().getJndiName();
        if (datasourceJndiName == null) {
            throw new ConnectionException("cann't find datasource jndi name!");
        }
        InitialContext ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup("java:comp/env/" + datasourceJndiName);
        dataSource = ds;
        return dataSource;
    }
}
  • 方式二: springframework configuration, 透過 org.springframework.jndi.JndiObjectFactoryBean。
    • 此設定是 spring 包裝 方式一 取得 datasource 的過程。
    • 在這裡可以自行指定 jndi 變數來源。
    • 若是沒有此設定,則如 方式一 預設使用 jndi.properties 中的設定,因此若沒有在此檔中提供此資訊會掛掉。

沒有留言:

張貼留言