**基于SpringJDBC分装类,支持主键返回、Oracel和MySQL数据库**
该SpringJDBC分装简单易用,在DAO成继承BaseDaoImpl加上spring的注解@Repository
主键注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Id {
}
实体与数据库字段不同于时的注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Column {
//数据库字段名
public String value() default "";
}
忽略的字段注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Ignore {
}
数据库表名与实体类名不统一注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Table {
public String value();
}
Oracel中的Blog字段处理注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface BlogDeal {
}
创建BaseDaoImpl类,该类主要实现springJDBC的调用,以及简单的实体类生成SQL语句和一些反射
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
public abstract class BaseDaoImpl<T> {
/** 设置一些操作的常量 */
public static final String SQL_INSERT = "insert";
public static final String SQL_UPDATE = "update";
public static final String SQL_DELETE = "delete";
Logger logger = LoggerFactory.getLogger(BaseDaoImpl.class);
@Autowired
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
private Class<T> entityClass;
@SuppressWarnings("unchecked")
public BaseDaoImpl() {
ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
entityClass = (Class<T>) type.getActualTypeArguments()[0];
System.out.println("Dao实现类是:" + entityClass.getName());
}
public void save(T entity) {
String sql = this.makeSql(SQL_INSERT);
Object[] args = this.setArgs(entity, SQL_INSERT);
int[] argTypes = this.setArgTypes(entity, SQL_INSERT);
jdbcTemplate.update(sql.toString(), args, argTypes);
}
/**
* 插入数据返回主键,主键在实体类中用@Id注解
* @param entity
* @return
*/
public String saveToKey(T entity) {
String pkzd = pkzd();
String sql = this.makeSql(SQL_INSERT);
Object[] args = this.setArgs(entity, SQL_INSERT);
int[] argTypes = this.setArgTypes(entity, SQL_INSERT);
String i = "";
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
PreparedStatement ps = conn.prepareStatement(sql, new String[] { pkzd });
for (int j = 0; j < args.length; j++) {
if (argTypes[j] == 12) {
ps.setString(j + 1, (String) args[j]);
}
if (argTypes[j] == 3) {
ps.setDouble(j + 1, (double) args[j]);
}
if (argTypes[j] == 4) {
ps.setObject(j + 1, args[j]);
}
if (argTypes[j] == 91) {
if (args[j] != null && args[j] != "") {
java.util.Date utilDate = (Date) args[j];
java.sql.Timestamp stp = new java.sql.Timestamp(utilDate.getTime());
ps.setTimestamp(j + 1, stp);
} else {
ps.setDate(j + 1, null);
}
}
if (argTypes[j] == 2004) {
if(args[j]!=null && args[j]!="") {
InputStream sbs = new ByteArrayInputStream(args[j].toString().getBytes());
ps.setBlob(j + 1, sbs);
}else {
InputStream sbs = null;
ps.setBlob(j + 1, sbs);
}
}
}
return ps;
}
}, keyHolder);
i = keyHolder.getKeys().get(pkzd).toString();
return i;
}
/**
* 更新数据
* @param entity
*/
public void update(T entity) {
String sql = this.makeSql(SQL_UPDATE);
Object[] args = this.setArgs(entity, SQL_UPDATE);
int[] argTypes = this.setArgTypes(entity, SQL_UPDATE);
jdbcTemplate.update(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
PreparedStatement ps = conn.prepareStatement(sql);
for (int j = 0; j < args.length; j++) {
if (argTypes[j] == 12) {
ps.setString(j + 1, (String) args[j]);
}
if (argTypes[j] == 3) {
ps.setDouble(j + 1, (double) args[j]);
}
if (argTypes[j] == 4) {
ps.setObject(j + 1, args[j]);
}
if (argTypes[j] == 91) {
if (args[j] != null && args[j] != "") {
java.util.Date utilDate = (Date) args[j];
java.sql.Timestamp stp = new java.sql.Timestamp(utilDate.getTime());
ps.setTimestamp(j + 1, stp);
} else {
ps.setDate(j + 1, null);
}
}
if (argTypes[j] == 2004) {
if(args[j]!=null && args[j]!="") {
InputStream sbs = new ByteArrayInputStream(args[j].toString().getBytes());
ps.setBlob(j + 1, sbs);
}else {
InputStream sbs = null;
ps.setBlob(j + 1, sbs);
}
}
}
return ps;
}
});
}
public void delete(T entity) {
String sql = this.makeSql(SQL_DELETE);
Object[] args = this.setArgs(entity, SQL_DELETE);
int[] argTypes = this.setArgTypes(entity, SQL_DELETE);
jdbcTemplate.update(sql, args, argTypes);
}
public void delete(Serializable id) {
String sql = " DELETE FROM " + loadTableName() + " WHERE id=?";
jdbcTemplate.update(sql, id);
}
/**
* 批量删除数据
* @param object
*/
public void deleteAll(Object[] object) {
String tmp = "";
for (int i = 0; i < object.length; i++) {
if (i == object.length - 1) {
tmp += "?";
} else {
tmp += "?,";
}
}
String sql = " DELETE FROM " + loadTableName() + " WHERE " + pkzd() + " in (%s)";
// 替代占位符,将组装的语句放入总sql中
sql = String.format(sql, tmp);
// final int[] no = new int[]{7369,7499,7521,7566,7654,7698};
jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
public void setValues(PreparedStatement ps, int i) throws SQLException {
for (int j = 0; j < object.length; j++) {
ps.setObject(j + 1, object[i]);
}
}
public int getBatchSize() {
return object.length;
}
});
logger.debug(sql);
}
public T findById(Serializable id) {
String sql = "SELECT * FROM " + loadTableName() + " WHERE id=?";
RowMapper<T> rowMapper = BeanPropertyRowMapper.newInstance(entityClass);
return jdbcTemplate.query(sql, rowMapper, id).get(0);
}
public List<T> findAll() {
String sql = "SELECT * FROM " + loadTableName();
RowMapper<T> rowMapper = BeanPropertyRowMapper.newInstance(entityClass);
return jdbcTemplate.query(sql, rowMapper);
}
// 组装SQL
private String makeSql(String sqlFlag) {
StringBuffer sql = new StringBuffer();
Field[] fields = entityClass.getDeclaredFields();
if (sqlFlag.equals(SQL_INSERT)) {
sql.append(" INSERT INTO " + loadTableName());
sql.append("(");
for (int i = 0; fields != null && i < fields.length; i++) {
fields[i].setAccessible(true); // 暴力反射
// boolean ignoreField = ignoreField(fields[i]);
if (ignoreField(fields[i])) {
continue;
}
String column = alieField(fields[i]);
sql.append(column).append(",");
}
sql = sql.deleteCharAt(sql.length() - 1);
sql.append(") VALUES (");
for (int i = 0; fields != null && i < fields.length; i++) {
if (ignoreField(fields[i])) {
continue;
}
sql.append("?,");
}
sql = sql.deleteCharAt(sql.length() - 1);
sql.append(")");
} else if (sqlFlag.equals(SQL_UPDATE)) {
String pkzd = "";
sql.append(" UPDATE " + loadTableName() + " SET ");
for (int i = 0; fields != null && i < fields.length; i++) {
fields[i].setAccessible(true); // 暴力反射
if (ignoreField(fields[i])) {
continue;
}
String column = alieField(fields[i]);
if (pk(fields[i])) { // id 代表主键
pkzd = column;
continue;
}
sql.append(column).append("=").append("?,");
}
sql = sql.deleteCharAt(sql.length() - 1);
sql.append(" WHERE " + pkzd + "=?");
} else if (sqlFlag.equals(SQL_DELETE)) {
String pkzd = "";
for (int i = 0; fields != null && i < fields.length; i++) {
String column = alieField(fields[i]);
if (pk(fields[i])) { // id 代表主键
pkzd = column;
break;
}
}
sql.append(" DELETE FROM " + loadTableName() + " WHERE " + pkzd + "=?");
}
logger.debug(sql.toString());
return sql.toString();
}
// 设置参数
private Object[] setArgs(T entity, String sqlFlag) {
Field[] fields = entityClass.getDeclaredFields();
int fa = 0;
for (int i = 0; i < fields.length; i++) {
if (ignoreField(fields[i])) {
fa = fa + 1;
continue;
}
}
if (sqlFlag.equals(SQL_INSERT)) {
int flag = 0;
Object[] args = new Object[fields.length - fa];
for (int i = 0; args != null && i < fields.length; i++) {
try {
fields[i].setAccessible(true); // 暴力反射
if (ignoreField(fields[i])) {
flag = flag + 1;
continue;
}
args[i - flag] = fields[i].get(entity);
} catch (Exception e) {
e.printStackTrace();
}
}
// args = Arrays.copyOf(args, args.length-flag);
return args;
} else if (sqlFlag.equals(SQL_UPDATE)) {
Object[] tempArr = new Object[fields.length - fa];
int flag = 0;
for (int i = 0; tempArr != null && i < fields.length; i++) {
try {
fields[i].setAccessible(true); // 暴力反射
if (ignoreField(fields[i])) {
flag = flag + 1;
continue;
}
tempArr[i - flag] = fields[i].get(entity);
} catch (Exception e) {
e.printStackTrace();
}
}
Object[] args = new Object[fields.length - fa];
System.arraycopy(tempArr, 1, args, 0, tempArr.length - 1); // 数组拷贝
args[args.length - 1] = tempArr[0];
// args = Arrays.copyOf(args, args.length-flag);
return args;
} else if (sqlFlag.equals(SQL_DELETE)) {
Object[] args = new Object[1]; // 长度是1
fields[0].setAccessible(true); // 暴力反射
try {
args[0] = fields[0].get(entity);
} catch (Exception e) {
e.printStackTrace();
}
return args;
}
return null;
}
// 设置参数类型(写的不全,只是一些常用的)
private int[] setArgTypes(T entity, String sqlFlag) {
Field[] fields = entityClass.getDeclaredFields();
int fa = 0;
for (int i = 0; i < fields.length; i++) {
if (ignoreField(fields[i])) {
fa = fa + 1;
continue;
}
}
if (sqlFlag.equals(SQL_INSERT)) {
int flag = 0;
int[] argTypes = new int[fields.length - fa];
try {
for (int i = 0; argTypes != null && i < fields.length; i++) {
if (ignoreField(fields[i])) {
flag++;
continue;
}
fields[i].setAccessible(true); // 暴力反射
if(BlogDeal(fields[i])) {
argTypes[i - flag] = Types.BLOB;
continue;
}
if (fields[i].getType().getName().equals("java.lang.String")) {
argTypes[i - flag] = Types.VARCHAR;
} else if (fields[i].getType().getName().equals("class java.lang.Double")) {
argTypes[i - flag] = Types.DECIMAL;
} else if (fields[i].getType().getName().equals("class java.lang.Integer")) {
argTypes[i - flag] = Types.INTEGER;
} else if (fields[i].getType().getName().equals("java.util.Date")) {
argTypes[i - flag] = Types.DATE;
}else if (fields[i].getType().getName().equals("int")) {
argTypes[i - flag] = Types.INTEGER;
}
}
} catch (Exception e) {
e.printStackTrace();
}
// argTypes = Arrays.copyOf(argTypes, argTypes.length-flag);
return argTypes;
} else if (sqlFlag.equals(SQL_UPDATE)) {
int[] tempArgTypes = new int[fields.length - fa];
int[] argTypes = new int[fields.length - fa];
int flag = 0;
try {
for (int i = 0; tempArgTypes != null && i < fields.length; i++) {
fields[i].setAccessible(true); // 暴力反射
if (ignoreField(fields[i])) {
flag++;
continue;
}
if(BlogDeal(fields[i])) {
tempArgTypes[i - flag] = Types.BLOB;
continue;
}
if (fields[i].getType().getName().equals("java.lang.String")) {
tempArgTypes[i - flag] = Types.VARCHAR;
} else if (fields[i].getType().getName().equals("class java.lang.Double")) {
tempArgTypes[i - flag] = Types.DECIMAL;
} else if (fields[i].getType().getName().equals("class java.lang.Integer")) {
tempArgTypes[i - flag] = Types.INTEGER;
} else if (fields[i].getType().getName().equals("java.util.Date")) {
tempArgTypes[i - flag] = Types.DATE;
}else if (fields[i].getType().getName().equals("int")) {
tempArgTypes[i - flag] = Types.INTEGER;
}
}
System.arraycopy(tempArgTypes, 1, argTypes, 0, tempArgTypes.length - 1); // 数组拷贝
argTypes[argTypes.length - 1] = tempArgTypes[0];
} catch (Exception e) {
e.printStackTrace();
}
// argTypes = Arrays.copyOf(argTypes, argTypes.length-flag);
return argTypes;
} else if (sqlFlag.equals(SQL_DELETE)) {
int[] argTypes = new int[1]; // 长度是1
try {
fields[0].setAccessible(true); // 暴力反射
if (fields[0].get(entity).getClass().getName().equals("java.lang.String")) {
argTypes[0] = Types.VARCHAR;
} else if (fields[0].get(entity).getClass().getName().equals("java.lang.Integer")) {
argTypes[0] = Types.INTEGER;
}
} catch (Exception e) {
e.printStackTrace();
}
return argTypes;
}
return null;
}
@SuppressWarnings("unused")
private List<T> find(int pageNo, int pageSize, Map<String, String> where, LinkedHashMap<String, String> orderby) {
// where 与 order by 要写在select * from table 的后面,而不是where rownum<=? )
// where rn>=?的后面
StringBuffer sql = new StringBuffer(
" SELECT * FROM (SELECT t.*,ROWNUM rn FROM (SELECT * FROM " + loadTableName());
if (where != null && where.size() > 0) {
sql.append(" WHERE "); // 注意不是where
for (Map.Entry<String, String> me : where.entrySet()) {
String columnName = me.getKey();
String columnValue = me.getValue();
sql.append(columnName).append(" ").append(columnValue).append(" AND "); // 没有考虑or的情况
}
int endIndex = sql.lastIndexOf("AND");
if (endIndex > 0) {
sql = new StringBuffer(sql.substring(0, endIndex));
}
}
if (orderby != null && orderby.size() > 0) {
sql.append(" ORDER BY ");
for (Map.Entry<String, String> me : orderby.entrySet()) {
String columnName = me.getKey();
String columnValue = me.getValue();
sql.append(columnName).append(" ").append(columnValue).append(",");
}
sql = sql.deleteCharAt(sql.length() - 1);
}
sql.append(" ) t WHERE ROWNUM<=? ) WHERE rn>=? ");
logger.debug(sql.toString());
Object[] args = { pageNo * pageSize, (pageNo - 1) * pageSize + 1 };
RowMapper<T> rowMapper = BeanPropertyRowMapper.newInstance(entityClass);
return jdbcTemplate.query(sql.toString(), args, rowMapper);
}
@SuppressWarnings("unused")
private int count(Map<String, String> where) {
StringBuffer sql = new StringBuffer(" SELECT COUNT(*) FROM " + loadTableName());
if (where != null && where.size() > 0) {
sql.append(" WHERE ");
for (Map.Entry<String, String> me : where.entrySet()) {
String columnName = me.getKey();
String columnValue = me.getValue();
sql.append(columnName).append(" ").append(columnValue).append(" AND "); // 没有考虑or的情况
}
int endIndex = sql.lastIndexOf("AND");
if (endIndex > 0) {
sql = new StringBuffer(sql.substring(0, endIndex));
}
}
logger.debug(sql.toString());
return jdbcTemplate.queryForObject(sql.toString(), Integer.class);
}
/**
* 查询数量
*
* @param sql
* @return
*/
@SuppressWarnings("unused")
public int count(String sql) {
return jdbcTemplate.queryForObject(sql.toString(), Integer.class);
}
/**
* 查询数量
*
* @param sql
* @param object
* @return
*/
public int counts(String sql, Object[] object) {
return jdbcTemplate.queryForObject(sql.toString(), object, Integer.class);
}
/**
* 获取表名
*
* @return
*/
public String loadTableName() {
if (entityClass.isAnnotationPresent(Table.class)) {
Table table = (Table) entityClass.getAnnotation(Table.class);
return table.value();
} else {
return entityClass.getSimpleName();
}
}
/**
* 忽略字段
*
* @return
*/
@SuppressWarnings("unused")
private boolean ignoreField(Field f) {
if (f.isAnnotationPresent(Ignore.class)) {
Ignore ignore = (Ignore) f.getAnnotation(Ignore.class);
return true;
} else {
return false;
}
}
/**
* 数据库字段名
*
* @return
*/
@SuppressWarnings("unused")
private String alieField(Field f) {
if (f.isAnnotationPresent(Column.class)) {
Column column = (Column) f.getAnnotation(Column.class);
return column.value();
} else {
return f.getName();
}
}
/**
* 获取主键
*
* @param f
* @return
*/
@SuppressWarnings("unused")
private boolean pk(Field f) {
if (f.isAnnotationPresent(Id.class)) {
Id column = (Id) f.getAnnotation(Id.class);
return true;
} else {
return false;
}
}
/**
* 判断是否是BLOG类型
* @param f
* @return
*/
@SuppressWarnings("unused")
private boolean BlogDeal(Field f) {
if (f.isAnnotationPresent(BlogDeal.class)) {
BlogDeal column = (BlogDeal) f.getAnnotation(BlogDeal.class);
return true;
} else {
return false;
}
}
/**
* 返回主键字段
* @return
*/
@SuppressWarnings("unused")
private String pkzd() {
Field[] fields = entityClass.getDeclaredFields();
String pkzd = "";
for (int i = 0; fields != null && i < fields.length; i++) {
fields[i].setAccessible(true); // 暴力反射
String column = alieField(fields[i]);
if (pk(fields[i])) { // id 代表主键
pkzd = column;
break;
}
}
return pkzd;
}
/**
* @param 参 数: @param sql
* @param 参 数: @return
* @return 返回类型: List<Map<String,Object>>
*/
public List<Map<String, Object>> gtQueryForListMap(String sql) {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
try {
list = jdbcTemplate.queryForList(sql);
logger.debug(sql);
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
/**
* 查询语句
*
* @param sql
* @param object
* @return
*/
public List<Map<String, Object>> gtQueryForListMaps(String sql, Object[] object) {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
try {
list = jdbcTemplate.queryForList(sql, object);
logger.debug(sql);
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
/**
* 拼装查询语句使用于Oracel,在查询中返回小写的key
*
* @return
*/
public String findSql2Oracel() {
StringBuffer sql = new StringBuffer();
Field[] fields = entityClass.getDeclaredFields();
for (int i = 0; fields != null && i < fields.length; i++) {
fields[i].setAccessible(true); // 暴力反射
// boolean ignoreField = ignoreField(fields[i]);
if (ignoreField(fields[i])) {
continue;
}
String column = alieField(fields[i]) + " " + "\"" + alieField(fields[i]).toLowerCase() + "\"";
if (i == fields.length - 1) {
sql.append(column);
} else {
sql.append(column).append(",");
}
}
if(StringUtils.endsWith(sql, ",")) {
sql.deleteCharAt(sql.length() - 1);
}
String sqls = "select " + sql + " from " + loadTableName();
return sqls;
}
/**
* Oracel分页语句
* @param sql
* @param startPage 起始序号
* @param pageSize 每页多少条数据
* @return
*/
public String pagingByOracel(String sql, int startPage, int pageSize) {
// 当前页最大值
int maxPage = startPage + pageSize;
String endSql = "select * from (" + "select t.*,rownum row_ from (" + sql + ") t" + " where rownum<=" + maxPage
+ ") where row_>" + startPage;
return endSql;
}
/**
* mysql数据库的分页实现 返回分页语句
* @param oldSQL
* @param pageNo
* @param pageSize
* @return
*/
public String pagingByMySql(String oldSQL, int startPage, int pageSize) {
StringBuffer sql = new StringBuffer(oldSQL);
if (pageSize > 0) {
int firstResult = (startPage - 1)*pageSize;
if (firstResult <= 0) {
sql.append(" limit ").append(pageSize);
} else {
sql.append(" limit ").append(firstResult).append(",")
.append(pageSize);
}
}
return sql.toString();
}
}
感谢支持,觉得好的二维码支持