jdbc 系列文章列表, 请查看目录: 《jdbc学习笔记》
笔者上篇博客介绍了如何使用JDBC来实现类似于Hibernate中对单表增删查改的EntityManager, 但是对于单表查询, 删除都需要传入目标对象的类型, 这个有点儿繁琐. 熟悉Spring Data JPA 的同学, 应该知道, 在Spring Data JPA 中, 对单表的操作, 只需要继承一个BaseRepository 对象即可. 那么我们也对此来封装一个BaseDao 对象.
1. BaseDao 介绍
BaseDao 基于笔者写的EntityManager 而实现.
1.1 BaseDao API
方法签名方法描述参数说明
public boolean save(Object entity)保存实体entity: 任意实体 public boolean deleteById(Integer id)根据id删除实体id: 主键 public boolean update(Object entity)更新实体entity: 数据库实体 public T findById(Integer id)根据id查询id: 主键 public List queryAll()查询所有实体
1.2 BaseDao 源码
public class BaseDao<T> {
private Class
<T> clz
;
public BaseDao() {
ParameterizedType parameterizedType
= (ParameterizedType
) this.getClass().getGenericSuperclass();
this.clz
= (Class
<T>) parameterizedType
.getActualTypeArguments()[0];
}
public boolean save(Object entity
){
return EntityManager
.save(entity
);
}
public boolean deleteById(Integer id
) {
return EntityManager
.deleteById(clz
, id
);
}
public boolean update(Object entity
) {
return EntityManager
.update(entity
);
}
public T
findById(Integer id
) {
return EntityManager
.findById(clz
, id
);
}
public List
<T> queryAll() {
return EntityManager
.queryAll(clz
);
}
}
2. 测试
基于笔者之前创建的UserPO 来测试.
2.1 创建UserDao
UserDao 只需要继承BaseDao 即可, 就直接继承了BaseDao的所有方法.
public class UserDao extends BaseDao<UserPO> {
}
2.2 测试用例
笔者这里只举一个查询所有的例子演示一下效果即可.
public class UserDaoTest {
private UserDao userDao
= new UserDao();
@Test
public void queryAll(){
List
<UserPO> userPOList
= userDao
.queryAll();
userPOList
.forEach(System
.out
::println
);
}
}