`
crmjava
  • 浏览: 7441 次
  • 性别: Icon_minigender_1
  • 来自: 北京
最近访客 更多访客>>
社区版块
存档分类
最新评论

chapter04 Spring对持久层的支持

阅读更多

chapter04 Spring对持久层的支持

  Spring对持久层的支持:① JDBC② O/R MappingHibernateTopLink等)

一、Spring对持久层支持采用的策略:

  1Spring对持久层不发明重复的轮子,即没有重新实现新的持久层方案,对现有持久层方案做封装,更利于使用。

  2、采用DAO模式

  3、提供了大量的模板类来简化编程(HibernateDaoSupportJdbcTemplate等)

  4、重新设计了一套完善的异常体系结构

    类型丰富,细化异常类型

全都是运行时异常(RuntimeException

5.简化了API的使用。对事物问题等进行了封装,提供了模板类

模板类的特点:

1)线程安全的

 

二、SpringJDBC的支持

  1、配置数据源

方式一:采用Spring内置的数据源,Spring内置实现 DriverManagerDataSource

       课堂使用的是测试数据源。而真正的开发中是不使用测试数据源的

<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/hibdb</value>

         </property>

         <property name="username">

           <value>root</value>

         </property>

         <property name="password">

           <value>windows</value>

         </property>

       </bean>

    方式二:采用开源数据库产品如DBCPC3P0

DBCP提供的BasicDataSource

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destory-method=”close”>

    <property name="driverClassName">

      <value>com.mysql.jdbc.Driver</value>

    </property>

    <property name="url">

      <value>jdbc:mysql://localhost:3306/hibdb</value>

    </property>

    <property name="username">

      <value>root</value>

    </property>

    <property name="password">

      <value>windows</value>

    </property>

    </bean>

    方式三: 直接使用容器提供的数据源(如TomcatWeblogicSun Application Server

    JNDI数据源:(mysql5,tomcat5.5)

       step1:

       server.xml中:

       <Resource name="jdbc/mydatasource" auth="Container" description="DB Connection"

    type="javax.sql.DataSource" username="root" password="windows"

    driverClassName="com.mysql.jdbc.Driver"

    url="jdbc:mysql://localhost:3306/tarena" maxActive="5" />

    step2:

    context.xml中(conf\context.xml):

    <ResourceLink   name="jdbc/mydatasource"          global="jdbc/mydatasource"   type="javax.sql.DataSourcer"/>

    step3:

    beans-config.xml:

    <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">

        <property name="jndiName">

          <value>java:comp/env/jdbc/mydatasource</value>

        </property>

      </bean>

2、配置JdbcTemplate模板类(封装了绝大多数数据库操作)

   将数据源注入到jdbcTemplate

3、配置DAO

4、配置Service

 

编程步骤:

Step1:编写实体,提供相应的DAO接口

Step2:编写dao的实现。提供jdbcTemplate模板的属性,及getset方法

Step3:使用jdbcTemplate提供的相应的操作数据库的方法,操作数据库,这里要注意在使用jdbcTemplateupdate方法时,如果sql语句中传了参数过去,一定要将参数数组也传入update方法,例如:

String sql="update Customer set name=?,age=? where id=?";

                     Object[]paramValues=new Object[]{customer.getName(),customer.getAge(),customer.getId()};

        jt.update(sql,paramValues);

返回对象的方法:

String sql="select * from Customer where name=?";

              Object [] paramValues=new Object[]{name};

              return (Customer) jt.queryForObject(sql, paramValues,new CustomerRowMap());

其中我们要做一步将结果集转换为对象的操作,如下:

//将结果集(一行)变成一个对象

public class CustomerRowMap implements RowMapper{

       @Override

       public Object mapRow(ResultSet arg0, int arg1) throws SQLException {

          Customer c=new Customer();

          c.setId(arg0.getInt("id"));

          c.setName(arg0.getString("name"));

          c.setAge(arg0.getInt("age"));

              return c;

       }

}

返回集合的方法:

String sql="select * from Customer";          

              return  jt.query(sql, new CustomerRowMap());

Step4:写业务层代码。使用dao接口。

Step5: 配置数据源

Step6: 配置JdbcTemplate

    <bean id="jdbcTemplate"

    class="org.springframework.jdbc.core.JdbcTemplate">

    <property name="dataSource">

      <ref bean="dataSource" />

    </property>

</bean>    

Step7:配置DAO

<!-- 因为如果有多个dao,而且每个dao都有jt对象,所以为了多个dao能够继承定义一个抽象类-->

<bean id="abstractDAO" abstract="true">

     <property name="jt" ref="jdbcTemplate"></property>

    </bean>

<bean id="customerDao" class="dao.impl.CustomerDAOJdbcImpl" parent="abstractDAO">

    </bean>

     注意:  查询时,使用RowMapper

另外一种实现DAO的方式:

不需要为DAO的实现类提供JdbcTemplate对象。而是使用继承JdbcDaoSupport类,然后用getJdbcTemplate()方法驱获得该对象的实例。调用相应的方法,配置文件中不再配置jdbcTemplate而是为dao提供数据源的属性即可:

<!-- 配置数据源 -->

       <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/tarena</value>

              </property>

              <property name="username">

                     <value>root</value>

              </property>

              <property name="password">

                     <value>1234</value>

              </property>

       </bean>

       <!-- 配置DAO -->

       <bean id="customerDAO" class="dao.jdbc.CustomerDAOJdbcImpl2">

              <property name="dataSource" ref="dataSource"/>

       </bean>

       <!-- 配置Service -->

       <bean id="customerService" class="service.spring.CustomerServiceSpringImpl">

              <property name="customerDAO" ref="customerDAO"/>

       </bean>

DAO的写法:

public class CustomerDAOJdbcImpl2 extends JdbcDaoSupport implements CustomerDAO{

       public void delete(String name) {

              // TODO Auto-generated method stub

              String sql = "delete from Customer where name=?";

              Object[] params = new Object[]{name};

              getJdbcTemplate().update(sql,params);

       }

三、SpringHibernate的支持

    Step1  配置数据源

    Step2  配置sessionfactory提供数据库的连接信息及映射文件

    <bean id="mySessionFactory"

      class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

      <property name="dataSource">

      <ref bean="dataSource" />

      </property>

      <property name="mappingResources">

      <list>

        <value>lab6/Order.hbm.xml</value>

      </list>

      </property>

      <property name="hibernateProperties">

      <props>

        <prop key="hibernate.dialect">

        org.hibernate.dialect.MySQLDialect

        </prop>

        <prop key="hibernate.show_sql">true</prop>

      </props>

      </property>

</bean>

 Step3: 配置模板类,跟jdbc一样,或者继承HibernateDaoSupport,这种方法不用配置模板类。或者配置模板类,在dao中提供模板类对象的属性

 Step4: dao的方法:

String sql="from Customer  c where c.name=:name";

getHibernateTemplate().findByNamedParam(sql, "name", name).get(0); findByNamedParam(sql, "name", name)该方法返回的是一个list,第二个参数是占位符的名字,如果有多个参数?

String sql="from Customer  c where c.name=:name and c.age=:age";

        return (Customer) getHibernateTemplate().findByNamedParam(sql,new String[]{"name","age"}, new Object[]{name,age}).get(0);

//当模板类的方法不能满足需求的时候。我们自定义的方法的写法

public Customer findByName(final String name) {

              HibernateTemplate template = getHibernateTemplate();

              return (Customer) template.execute(new HibernateCallback(){

//这里的execute方法除了能查询还能做除了更新操作以为的查询

                     public Object doInHibernate(Session arg0) throws HibernateException, SQLException {

                            String hql = "from Customer c where c.name=:name";

                            Query query = arg0.createQuery(hql);

                            query.setString("name", name);//红色部分一定要注意

                            return query.uniqueResult();

                     }

              });

}

  Step5配置DAO

    <bean id="orderDao" class="lab6.OrderDAOHibernateImpl">

    <property name="sessionFactory">

      <ref bean="mySessionFactory" />

    </property>

    </bean>

    注意:以上配置是要求dao 继承HibernateDaoSupport

   Step6:dao放在service

关键在模板类的编写

<?xml version="1.0" e

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics