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

Spring DAO之JDBC

2013-11-23 20:26:47  來源: Java開源技術 

  Spring DAO之JDBC

  Spring提供的DAO(數據訪問對象)支持主要的目的是便於以標准的方式使用不同的數據訪問技術 如JDBCHibernate或者JDO等它不僅可以讓你方便地在這些持久化技術間切換 而且讓你在編碼的時候不用考慮處理各種技術中特定的異常

  為了便於以一種一致的方式使用各種數據訪問技術如JDBCJDO和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()
   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;
    }
}

  /**
* Created by IntelliJ IDEA<br>
* <b>User</b>: leizhimin<br>
* <b>Date</b>: ::<br>
* <b>Note</b>: DAO接口
*/
public interface IUserDAO {
    public void insert(User user);

  public User find(Integer id);
}

  import javaxsqlDataSource;
import javasqlConnection;
import javasqlSQLException;

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

  /**
* 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 JdbcTemplate getJdbcTemplate(){
        return new JdbcTemplate(getDataSource());
    }
    public void insert(User user) {
        String name = usergetName();
        int age = usergetAge()intValue();

  //        jdbcTemplateupdate(INSERT INTO user (nameage)
//                + VALUES( + name + + age + ));

  String sql = insert into user(nameage) values(??);
        getJdbcTemplate()update(sqlnew Object[]{nameage});
    }

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

  Iterator it = erator();
        if (ithasNext()) {
            Map userMap = (Map) itnext();
            Integer i = new Integer(userMapget(id)toString());
            String name = userMapget(name)toString();
            Integer age = new Integer(userMapget(age)toString());

  User user = new User();

  usersetId(i);
            usersetName(name);
            usersetAge(age);

  return user;
        }
        return null;
    }
}

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

  <beans>
    <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>

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

  <bean id=userDAO
          class=comlavasoftspringnotech_jdbc_tempUserDAO parent=baseDAO>
    </bean>

  </beans>

  import orgntextApplicationContext;
import orgntextsupportFileSystemXmlApplicationContext;

  /**
* 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_temp\\beanjdbctempxml);
        User user = new User();
        usersetName(hahhahah);
        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


From:http://tw.wingwit.com/Article/program/Java/ky/201311/28510.html
  • 上一篇文章:

  • 下一篇文章:
  • 推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.