本源码内容如下:
- spring boot项目
- 用的druid连接池
- druid监控页面配置
- 数据操作用spring jdbctemplate
- 进一步封装spring jdbctemplate支持用对象进行增删改查
- 封装jdbctemplate的是单独一个项目,可以打包到任务项目中使用
详细介绍请查看 http://cxytiandi.com/blog/detail/3881
封装部分代码
public <T> T getByParams(Class<T> entityClass, String[] params, Object... values) {
String[] fieldNames = BeanUtils.getFieldNames(entityClass, "");
return doGetByParams(entityClass, fieldNames, params, values);
}
public <T> T getByParams(Class<T> entityClass, String[] fieldNames, String[] params, Object... values) {
return doGetByParams(entityClass, fieldNames, params, values);
}
private <T> T doGetByParams(Class<T> entityClass, String[] fieldNames, String[] params, Object... values) {
StringBuilder sql = getParamSql(entityClass, fieldNames, params, values);
return get(entityClass, sql.toString(), values);
}
public <T> List<T> findByParams(Class<T> entityClass, String[] params, Object... values) {
String[] fieldNames = BeanUtils.getFieldNames(entityClass, "");
return doFindByParams(entityClass, fieldNames, params, values);
}
使用部分代码
@Transactional
public void save() {
Users u = new Users();
u.setMobile("13112021223");
//id自增不需要插入所以排除
cxytiandiJdbcTemplate.save(Users.class, u, "id");
}
@Transactional
public void updateUser(Users user) {
//根据ID修改用户信息,只修改mobile字段
cxytiandiJdbcTemplate.updateByContainsFields(Users.class, user, "id", "mobile");
}
@Transactional
public void deleteUser() {
cxytiandiJdbcTemplate.deleteByParams(Users.class, new String[]{"id", "mobile"}, 2, "13858521245");
}
public List<Users> findByParams() {
return cxytiandiJdbcTemplate.findByParams(Users.class, new String[]{"mobile"}, "13985854512");
}
public long count() {
return cxytiandiJdbcTemplate.count(Users.class);
}
public long count(String mobile) {
return cxytiandiJdbcTemplate.count(Users.class, "mobile", mobile);
}
public List<Users> queryAllUsers() {
return cxytiandiJdbcTemplate.list(Users.class);
}
public List<Users> getUsersByPage(int page, int limit) {
PageQueryParam param = new PageQueryParam(page, limit);
return cxytiandiJdbcTemplate.listForPage(Users.class, param.getStart(), param.getLimit());
}