欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java的Spring框架中DAO數(shù)據(jù)訪問對象的使用示例

 更新時間:2016年03月04日 08:53:18   作者:leizhimin  
這篇文章主要介紹了Java的Spring框架中DAO數(shù)據(jù)訪問對象的使用示例,分為在Spring中DOA與JDBC以及與Hibernate的配合使用兩種情況來進行演示,需要的朋友可以參考下

Spring DAO之JDBC
 
Spring提供的DAO(數(shù)據(jù)訪問對象)支持主要的目的是便于以標準的方式使用不同的數(shù)據(jù)訪問技術, 如JDBC,Hibernate或者JDO等。它不僅可以讓你方便地在這些持久化技術間切換, 而且讓你在編碼的時候不用考慮處理各種技術中特定的異常。
為了便于以一種一致的方式使用各種數(shù)據(jù)訪問技術,如JDBC、JDO和Hibernate, Spring提供了一套抽象DAO類供你擴展。這些抽象類提供了一些方法,通過它們你可以 獲得與你當前使用的數(shù)據(jù)訪問技術相關的數(shù)據(jù)源和其他配置信息。
Dao支持類:
JdbcDaoSupport - JDBC數(shù)據(jù)訪問對象的基類。 需要一個DataSource,同時為子類提供 JdbcTemplate。
HibernateDaoSupport - Hibernate數(shù)據(jù)訪問對象的基類。 需要一個SessionFactory,同時為子類提供 HibernateTemplate。也可以選擇直接通過 提供一個HibernateTemplate來初始化, 這樣就可以重用后者的設置,例如SessionFactory, flush模式,異常翻譯器(exception translator)等等。
JdoDaoSupport - JDO數(shù)據(jù)訪問對象的基類。 需要設置一個PersistenceManagerFactory, 同時為子類提供JdoTemplate。 
JpaDaoSupport - JPA數(shù)據(jù)訪問對象的基類。 需要一個EntityManagerFactory,同時 為子類提供JpaTemplate。 
本節(jié)主要討論Sping對JdbcDaoSupport的支持。
下面是個例子:

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

 

/** 
* Created by IntelliJ IDEA.<br> 
* <b>User</b>: leizhimin<br> 
* <b>Date</b>: 2008-4-22 15:34:36<br> 
* <b>Note</b>: DAO接口 
*/ 
public interface IUserDAO { 
  public void insert(User user); 

  public User find(Integer id); 
}
 
 
import javax.sql.DataSource; 
import java.sql.Connection; 
import java.sql.SQLException; 

/** 
* Created by IntelliJ IDEA.<br> 
* <b>Note</b>: 基類DAO,提供了數(shù)據(jù)源注入 
*/ 
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; 
  } 
}
 
 
/** 
* Created by IntelliJ IDEA.<br> 
* <b>User</b>: leizhimin<br> 
* <b>Date</b>: 2008-4-22 15:36:04<br> 
* <b>Note</b>: DAO實現(xiàn) 
*/ 
public class UserDAO extends BaseDAO implements IUserDAO { 

  public JdbcTemplate getJdbcTemplate(){ 
    return new JdbcTemplate(getDataSource()); 
  } 
  public void insert(User user) { 
    String name = user.getName(); 
    int age = user.getAge().intValue(); 

//    jdbcTemplate.update("INSERT INTO user (name,age) " 
//        + "VALUES('" + name + "'," + age + ")"); 

    String sql = "insert into user(name,age) values(?,?)"; 
    getJdbcTemplate().update(sql,new Object[]{name,age}); 
  } 

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

    Iterator it = rows.iterator(); 
    if (it.hasNext()) { 
      Map userMap = (Map) it.next(); 
      Integer i = new Integer(userMap.get("id").toString()); 
      String name = userMap.get("name").toString(); 
      Integer age = new Integer(userMap.get("age").toString()); 

      User user = new User(); 

      user.setId(i); 
      user.setName(name); 
      user.setAge(age); 

      return user; 
    } 
    return null; 
  } 
}

 

<?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.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> 

  <bean id="baseDAO" class="com.lavasoft.springnote.ch05_jdbc03_temp.BaseDAO" abstract="true">
    <property name="dataSource"> 
      <ref bean="dataSource"/> 
    </property> 
  </bean> 

  <bean id="userDAO" 
     class="com.lavasoft.springnote.ch05_jdbc03_temp.UserDAO" parent="baseDAO"> 
  </bean> 

</beans>

 

import org.springframework.context.ApplicationContext; 
import org.springframework.context.support.FileSystemXmlApplicationContext; 

/** 
* Created by IntelliJ IDEA.<br> 
* <b>User</b>: leizhimin<br> 
* <b>Date</b>: 2008-4-22 15:59:18<br> 
* <b>Note</b>: 測試類,客戶端 
*/ 
public class SpringDAODemo { 
  public static void main(String[] args) { 
    ApplicationContext context = new FileSystemXmlApplicationContext("D:\\_spring\\src\\com\\lavasoft\\springnote\\ch05_jdbc03_temp\\bean-jdbc-temp.xml"); 
    User user = new User(); 
    user.setName("hahhahah"); 
    user.setAge(new Integer(22)); 
    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 DAO之Hibernate
 
HibernateDaoSupport - Hibernate數(shù)據(jù)訪問對象的基類。 需要一個SessionFactory,同時為子類提供 HibernateTemplate。也可以選擇直接通過 提供一個HibernateTemplate來初始化, 這樣就可以重用后者的設置,例如SessionFactory, flush模式,異常翻譯器(exception translator)等等。

本節(jié)主要討論Sping對HibernateTemplate的支持。

下面是個例子:
 

drop table if exists user; 

/*==============================================================*/ 
/* Table: user                         */ 
/*==============================================================*/ 
create table user 
( 
  id          bigint AUTO_INCREMENT not null, 
  name         varchar(24), 
  age         int, 
  primary key (id) 
); 

 

/** 
* Created by IntelliJ IDEA.<br> 
* <b>Note</b>: Hiberante實體類 
*/ 
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; 
  } 
}

 

<?xml version="1.0" encoding="utf-8"?> 
<!DOCTYPE hibernate-mapping 
  PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 

<hibernate-mapping> 

  <class name="com.lavasoft.springnote.ch06_hbm_02deTx.User" 
      table="user"> 

    <id name="id" column="id"> 
      <generator class="native"/> 
    </id> 

    <property name="name" column="name"/> 

    <property name="age" column="age"/> 

  </class> 

</hibernate-mapping>

 

/** 
* Created by IntelliJ IDEA.<br> 
* <b>User</b>: leizhimin<br> 
* <b>Date</b>: 2008-4-23 15:37:43<br> 
* <b>Note</b>: DAO接口 
*/ 
public interface IUserDAO { 
  public void insert(User user); 
  public User find(Integer id); 
} 
 
import org.hibernate.SessionFactory; 
import org.springframework.orm.hibernate3.HibernateTemplate; 

/** 
* Created by IntelliJ IDEA.<br> 
* <b>User</b>: leizhimin<br> 
* <b>Date</b>: 2008-4-23 15:15:55<br> 
* <b>Note</b>: DAO實現(xiàn) 
*/ 
public class UserDAO implements IUserDAO { 
  private HibernateTemplate hibernateTemplate; 

  public void setSessionFactory(SessionFactory sessionFactory) { 
    this.hibernateTemplate =new HibernateTemplate(sessionFactory); 
  } 

  public void insert(User user) { 
    hibernateTemplate.save(user); 
    System.out.println("所保存的User對象的ID:"+user.getId()); 
  } 

  public User find(Integer id) { 
    User user =(User) hibernateTemplate.get(User.class, id); 
    return user; 
  } 
}

 

<?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="sessionFactory" 
     class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" 
     destroy-method="close"> 
    <property name="dataSource"> 
      <ref bean="dataSource"/> 
    </property> 
    <property name="mappingResources"> 
      <list> 
        <value>com/lavasoft/springnote/ch06_hbm_02proTx/User.hbm.xml</value> 
      </list> 
    </property> 
    <property name="hibernateProperties"> 
      <props> 
        <prop key="hibernate.dialect"> 
          org.hibernate.dialect.MySQLDialect 
        </prop> 
      </props> 
    </property> 
  </bean> 


  <bean id="userDAO" class="com.lavasoft.springnote.ch06_hbm_02proTx.UserDAO"> 
    <property name="sessionFactory"> 
      <ref bean="sessionFactory"/> 
    </property> 
  </bean> 
</beans>

 

import org.springframework.context.ApplicationContext; 
import org.springframework.context.support.FileSystemXmlApplicationContext; 

/** 
* Created by IntelliJ IDEA.<br> 
* <b>Note</b>: 測試類、客戶端 
*/ 
public class SpringHibernateDemo { 
  public static void main(String[] args) { 
    ApplicationContext context =new FileSystemXmlApplicationContext("D:\\_spring\\src\\com\\lavasoft\\springnote\\ch06_hbm_02proTx\\bean-hbm_tx.xml"); 

    // 建立DAO物件 
    IUserDAO userDAO = (IUserDAO) context.getBean("userDAO"); 

    User user = new User(); 
    user.setName("caterpillar"); 
    user.setAge(new Integer(30)); 

    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. 
所保存的User對象的ID:18 
name: jdbctemplate 

Process finished with exit code 0

相關文章

  • 關于springboot中的SPI機制

    關于springboot中的SPI機制

    這篇文章主要介紹了springboot中的SPI機制,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-01-01
  • 使用java判斷輸入年份是否為閏年完整代碼

    使用java判斷輸入年份是否為閏年完整代碼

    閏年的引入確保了我們的日歷與地球運行軌道的對齊,使得時間的計算更加準確,在編程中判斷給定年份是否為閏年是一項常見的任務,這篇文章主要給大家介紹了關于使用java判斷輸入年份是否為閏年的相關資料,需要的朋友可以參考下
    2023-10-10
  • 詳解HttpClient用法

    詳解HttpClient用法

    HttpClient是Apache Jakarta Common下的子項目,用來提供高效的、最新的、功能豐富的支持HTTP協(xié)議的客戶端編程工具包,并且它支持HTTP協(xié)議最新的版本和建議,這篇文章主要介紹了詳解HttpClient用法,需要的朋友可以參考下
    2021-01-01
  • java中的?HashMap?的加載因子是0.75原理探討

    java中的?HashMap?的加載因子是0.75原理探討

    在Java中,HashMap是一種常用的數(shù)據(jù)結構,用于存儲鍵值對,它的設計目標是提供高效的插入、查找和刪除操作,在HashMap的實現(xiàn)中,加載因子(Load?Factor)是一個重要的概念,本文將探討為什么Java中的HashMap的加載因子被設置為0.75
    2023-10-10
  • Java格式化輸出printf()解讀

    Java格式化輸出printf()解讀

    這篇文章主要介紹了Java格式化輸出printf()解讀,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • IntelliJ?IDEA2022.3?springboot?熱部署含靜態(tài)文件(最新推薦)

    IntelliJ?IDEA2022.3?springboot?熱部署含靜態(tài)文件(最新推薦)

    這篇文章主要介紹了IntelliJ?IDEA2022.3?springboot?熱部署含靜態(tài)文件,本文結合實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-01-01
  • 深入了解Java中的反射機制(reflect)

    深入了解Java中的反射機制(reflect)

    Java的反射機制允許我們對一個類的加載、實例化、調用方法、操作屬性的時期改為在運行期進行,這大大提高了代碼的靈活度,本文就來簡單講講反射機制的具體使用方法吧
    2023-05-05
  • Google Guava 緩存工具使用詳解

    Google Guava 緩存工具使用詳解

    這篇文章主要介紹了Guava自加載緩存LoadingCache使用指南,通過這些內容介紹,了解了LoadingCache的基本原理和用法,包括如何創(chuàng)建和配置緩存,以及如何結合Java?8的特性來優(yōu)化代碼,需要的朋友可以參考下
    2023-12-12
  • 解決在Idea 2020.2下使用 Lombok的注解不生效的問題(插件安裝了,依賴也寫了,自動注解也設置了)

    解決在Idea 2020.2下使用 Lombok的注解不生效的問題(插件安裝了,依賴也寫了,自動注解也設置了)

    這篇文章主要介紹了在Idea 2020.2下使用 Lombok的注解不生效的問題(插件安裝了,依賴也寫了,自動注解也設置了),本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-08-08
  • Java實戰(zhàn)花店商城系統(tǒng)的實現(xiàn)流程

    Java實戰(zhàn)花店商城系統(tǒng)的實現(xiàn)流程

    只學書上的理論是遠遠不夠的,只有在實戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用java+Springboot+Maven+mybatis+Vue+Mysql實現(xiàn)一個花店商城系統(tǒng),大家可以在過程中查缺補漏,提升水平
    2022-01-01

最新評論