欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java的Spring框架中DAO数据访问对象的使用示例

程序员文章站 2024-03-09 14:58:43
spring dao之jdbc   spring提供的dao(数据访问对象)支持主要的目的是便于以标准的方式使用不同的数据访问技术, 如jdbc,hibern...

spring dao之jdbc
 
spring提供的dao(数据访问对象)支持主要的目的是便于以标准的方式使用不同的数据访问技术, 如jdbc,hibernate或者jdo等。它不仅可以让你方便地在这些持久化技术间切换, 而且让你在编码的时候不用考虑处理各种技术中特定的异常。
为了便于以一种一致的方式使用各种数据访问技术,如jdbc、jdo和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(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,提供了数据源注入 
*/ 
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实现 
*/ 
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数据访问对象的基类。 需要一个sessionfactory,同时为子类提供 hibernatetemplate。也可以选择直接通过 提供一个hibernatetemplate来初始化, 这样就可以重用后者的设置,例如sessionfactory, flush模式,异常翻译器(exception translator)等等。

本节主要讨论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实现 
*/ 
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