模仿Warp Dynamic Finder的Hibernate Dynamic Dao

看了Robbin前两天发的那帖,Warp framework - 一个相当有前途的Java轻量级Web开发框架([url]http://www.iteye.com/topic/168780[/url]),让人眼前一亮,特别是基于annotation的warp-dynamic-finder部分给人印象非常深刻,利用它,80%情况下Dao的实现不用去写了,只要定义个interface,加几个annotation轻松搞定,自己就着手实现了一个,基于spring的HibernateDaoSupport,其用法也很简单,如下:


public interface StudentDao {
@Save
Long save(Student student);

@Delete
void delete(Student student);

@Get
Student get(Long id);

@Query("from Student as s where s.name = ? and s.age = ?")
Student getByNameAndAge(String name, Integer age);//根据参数出现的次序绑定

@Query("from Student as s where s.age > :age")
List<Student> getStudentsAgeMoreThan(
@Parameter("age") Integer age);//name绑定

@Query("from Student as s where s.name like ?")
Student getStudentNameLike(
@Like(matchMode = MatchMode.START) String name);//支持like

@Query(value = "delete Student where name = ?", executeUpdate = true)
int deleteStudentByName(String name);//批量更新

@Query("from Student as s order by s.id desc")
@Conditions({
@Condition("s.name = ?"), //动态条件添加,如果第一个参数不为null,该条件会被插入query string
@Condition("s.age = ?")
})
Student query(String name, Integer age);

}



这样一个Dao就定义OK了,非常容易,有两种使用方式,一种是利用AutoInjectDynamicDaoBeanPostProcessor,在spring中的bean初始化好之后,找到有InjectDao标注的方法就,利用动态代理生成StudentDao的代理实现并注入:


<bean class="com.norther.dynamic.dao.AutoInjectDynamicDaoBeanPostProcessor">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

<bean id="studentService " class="com.norther.dynamic.dao.test.StudentService" />



public class StudentService {

private StudentDao studentDao;

@InjectDao//会被注入StudentDao动态代理实现
public void setStudentDao(StudentDao studentDao) {
this.studentDao = studentDao;
}


还有另一种方式是基于FactoryBean的DynamicDaoProxy,并自己指定要实现的Dao接口,如下:

<bean id="studentDao " class="com.norther.dynamic.dao.DynamicDaoProxy">
<property name="dao" value="com.norther.dynamic.dao.test.StudentDao" />
</bean>
<bean id="teacherDao " class="com.norther.dynamic.dao.DynamicDaoProxy">
<property name="dao" value="com.norther.dynamic.dao.test.TeacherDao" />
</bean>



非常的简单,也很初级,有什么不足,请大家多多指教,呵呵。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值