rose手册第三章A节:DAO层:DAO的基本配置与使用

rose 本章开始进入对DB层的支持,同进也是日常开发用得最多的章节。 3.A.1 什么是jade?

jade大概是java access data layer的意思吧,具体的来由,在章节写到末尾的时候,我再找qieqie和liaohan大侠们写一写编年史。
用jade的好处在于,尽可能减少重复的从db把数据对bean进行装配的过程,统一入口,隔离业务逻辑,方便review。
jade是在spring完成的数据层的良好实践总结,无缝接入rose中,可以算得上是rose亲密无间的好模块。

3.A.2 引入基础配置

要开始使用jade,一定要先引用jade的基础包:

pom.xml

  1. <dependency>  
  2.     <groupId>com.54chen</groupId>  
  3.     <artifactId>paoding-rose-jade</artifactId>  
  4.     <version>1.1</version>  
  5. </dependency>  

除了需要jade的包外,还需要引入数据源连接池的jar,这里使用了dbcp,还是在pom.xml中:

  1. <dependency>  
  2.     <groupId>commons-dbcp</groupId>  
  3.     <artifactId>commons-dbcp</artifactId>  
  4.     <version>1.2.2</version>  
  5. </dependency>  
  6. <dependency>  
  7.     <groupId>mysql</groupId>  
  8.     <artifactId>mysql-connector-java</artifactId>  
  9.     <version>5.1.10</version>  
  10. </dependency>  

在pom中引入了依赖之后,需要定义一个数据源,这里先不考虑多个数据源的情况。

在war项目的applicationContext.xml中增加数据源定义:

  1.  <!-- 数据源配置 dbcp -->  
  2. <bean id="jade.dataSource.com.chen.dao" class="org.apache.commons.dbcp.BasicDataSource"  
  3.     destroy-method="close">  
  4.     <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>  
  5.     <property name="url"  
  6.         value="jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&amp;characterEncoding=utf-8"></property>  
  7.     <property name="username" value="test"></property>  
  8.     <property name="password" value="test"></property>  
  9.     <!-- 运行判断连接超时任务的时间间隔,单位为毫秒,默认为-1,即不执行任务。 -->  
  10.     <property name="timeBetweenEvictionRunsMillis" value="3600000"></property>  
  11.     <!-- 连接的超时时间,默认为半小时。 -->  
  12.     <property name="minEvictableIdleTimeMillis" value="3600000"></property>  
  13. </bean>   

这里假设了mysql已经安装在本地了,用户名为test,密码为test。
jade约定了bean的id为jade.dataSource.classPackageName。
jade约定了这个bean的有效范围为classPackageName所有的DAO。
jade约定了除非有专门的定义,所有的子目录也受bean上的classpackageName所影响。

3.A.3 第一个读取数据库的实例

先需要准备一下数据库:

  1. create table test (int id, varchar(200) msg);  
  2. insert into test values(111,'adfafafasdf');  

然后准备简练的DAO声明:

  1. @DAO  
  2. public interface TestDAO {  
  3.     @SQL("select id,msg from test limit 1")  
  4.     public Test getTest();  
  5. }  

Test是一个class,里面有标准的getter和setter。

然后从一个类去调用它:

  1. @Service  
  2. public class TestService {  
  3.   
  4.     @Autowired  
  5.     private TestDAO testDAO;  
  6.   
  7.     public Test getTest() {  
  8.         return testDAO.getTest();  
  9.     }  
  10. }  

当然也可以直接用controller就调用它显示了,当然这不是一个大型项目良好的架构,架构问题在最后的章节里讲述。 3.A.4 查看演示代码

rose-example项目的HelloController已经准备好了一个action做为此节的总结。

你可以将此节发布到resin或者tomcat后访问:http://127.0.0.1/3.10 查看结果。

文中所提及代码均在 https://github.com/XiaoMi/rose/tree/master/rose-example 提供。

常期更新版:https://github.com/XiaoMi/rose/tree/master/chapter_3_A

×××小米C轮融资成功,不经意间过去的两年已经翻了数十倍,需要你加入,继续创造翻N倍的价值。chenzhen at xiaomi dot com。×××


原创文章如转载,请注明:转载自五四陈科学院[http://www.54chen.com]

捐款订阅54chen
捐赠说明

java