Please wait. This can take some minutes ...
Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance.
Project price only 1 $
You can buy this project and download/modify it how often you want.
com.simple.orm.dao.BaseDaoAdapter Maven / Gradle / Ivy
package com.simple.orm.dao;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.Column;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Id;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
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;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
public abstract class BaseDaoAdapter implements BaseDao, ApplicationContextAware {
private JdbcTemplate jdbcTemplate;
private final Class entityClass;
private final String tableName;
private final List fields=new ArrayList();
private String defaultOrderColumnLabel=""; //默认的排序列名
private String defaultBy=""; //默认排序方式
private final Query query;
@SuppressWarnings("unchecked")
public BaseDaoAdapter() {
Type paramType = getClass().getGenericSuperclass();
if (paramType instanceof ParameterizedType) {
ParameterizedType pty = (ParameterizedType) paramType;
this.entityClass = (Class) pty.getActualTypeArguments()[0];
Table table = entityClass.getAnnotation(Table.class);
tableName = table.name();
initFields(entityClass);
query=new QueryImpl();
} else {
entityClass = null;
tableName = null;
query=null;
}
}
/**
* 加载类中所有的属相和方法
* @param clazz 映射对象的CLASS
*/
private void initFields(Class> clazz){
Class> searchType = clazz;
while (!Object.class.equals(searchType) && searchType != null) {
Field[] temp = searchType.getDeclaredFields();
for(Field field:temp){
fields.add(field);
OrderBy ob=field.getAnnotation(OrderBy.class);
if(ob!=null){
Column column = field.getAnnotation(Column.class);
if (column == null || (defaultOrderColumnLabel = column.name()).equals("")) {
continue;
}
defaultBy=(StringUtils.isEmpty(ob.value())?"ASC":ob.value());
}
}
searchType = searchType.getSuperclass();
}
}
/**
* 设置某个属性排序
* @param property 属性名称
* @param by ASC|DESC
* @return 返回查询对象
* @throws SQLException 抛出数据库异常
*/
public Query setOrderBy(String property,String by) throws SQLException{
String columnLabel =getColumnLabelByProperty(property);
return new QueryImpl(columnLabel, by);
}
public M find(Serializable id) throws SQLException {
return query.find(id);
}
public M find(String property, Object value) throws SQLException {
return query.find(property, value);
}
public List query(String property, Object value) throws SQLException {
return query.query(property, value);
}
public List query(String property, Object value, Integer start, Integer num) throws SQLException {
return query.query(property, value, start, num);
}
public List query() throws SQLException {
return query.query();
}
public List query(M m, Integer start, Integer num) throws SQLException {
return query.query(m, start, num);
}
public List query(Integer start, Integer num) throws SQLException {
return query.query(start, num);
}
public List query(M m) throws SQLException {
return query.query(m);
}
public M insert(M m)throws SQLException {
try {
StringBuilder columns=new StringBuilder();
StringBuilder values=new StringBuilder();
final List lvs=new ArrayList();
Field IdField=null;
for (Field field : fields) {
Id pk = field.getAnnotation(Id.class);
if (pk != null) {
IdField=field;
}
field.setAccessible(true);
Object v=field.get(m);
if(v!=null){
Column column = field.getAnnotation(Column.class);
String columnLabel;
if (column == null || (columnLabel = column.name()).equals("")) {
continue;
}
if(field.getType().isEnum()){ //如果是枚举类型
Enum em=(Enum) v;
Enumerated enumerated=field.getAnnotation(Enumerated.class);
EnumType enumType;
if(enumerated!=null && (enumType=enumerated.value())!=null && enumType.equals(EnumType.ORDINAL)){
v=em.ordinal();
}else{
v=em.name();
}
}
columns.append(columnLabel+",");
values.append("?,");
lvs.add(v);
}
}
if(columns.length()==0 || values.length()==0){
throw new SQLException("在 执行 save 异常 因为" + entityClass + "实体类中没有有效数据");
}
final String sql="INSERT INTO "+tableName+"("+columns.substring(0, columns.length()-1)+")VALUES("+values.substring(0, values.length()-1)+");";
KeyHolder key=new GeneratedKeyHolder();
jdbcTemplate.update(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
PreparedStatement preState = con.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
for (int i = 0; i < lvs.size(); i++) {
preState.setObject(i+1, lvs.get(i));
}
return preState;
}
}, key);
IdField.setAccessible(true);
IdField.set(m, key.getKey());
return m;
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
public Integer count(M m) throws SQLException {
try {
StringBuilder conds=new StringBuilder();
final List lvs=new ArrayList();
for (Field field : fields) {
field.setAccessible(true);
Object v=field.get(m);
if(v!=null){
Column column = field.getAnnotation(Column.class);
String columnLabel;
if (column == null || (columnLabel = column.name()).equals("")) {
continue;
}
if(field.getType().isEnum()){ //如果是枚举类型
Enum em=(Enum) v;
Enumerated enumerated=field.getAnnotation(Enumerated.class);
EnumType enumType;
if(enumerated!=null && (enumType=enumerated.value())!=null && enumType.equals(EnumType.ORDINAL)){
v=em.ordinal();
}else{
v=em.name();
}
}
conds.append(" m."+columnLabel+"=? AND");
lvs.add(v);
}
}
if(conds.length()==0){
throw new SQLException("在执行 count " + entityClass + "实例中没有设置条件");
}
String sql="SELECT COUNT(*) FROM "+tableName+" m WHERE "+conds.substring(0, conds.length()-3);
return jdbcTemplate.queryForObject(sql, Integer.class, lvs.toArray());
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return 0;
}
public Integer count() throws SQLException {
String sql="SELECT COUNT(*) FROM `"+tableName+"` m ;";
return jdbcTemplate.queryForObject(sql, Integer.class);
}
public Integer count(String property, Object value) throws SQLException {
String sql = "select count(*) from " + tableName + " m where m." + getColumnLabelByProperty(property) + "=?";
return jdbcTemplate.queryForObject(sql, Integer.class,value);
}
public M update(M m) throws SQLException{
try {
StringBuilder sets=new StringBuilder();
final List lvs=new ArrayList();
String primaryName=null;
Object primaryValue=null;
for (Field field : fields) {
Id pk = field.getAnnotation(Id.class);
if (pk != null) {
Column column = field.getAnnotation(Column.class);
if (column != null && !column.name().equals("")) {
primaryName=column.name();
field.setAccessible(true);
primaryValue=field.get(m);
if(primaryValue==null){
throw new SQLException("在执行 update " + entityClass + "实例中发现主要属性"+field.getName()+"中的值为null");
}
} else {
throw new SQLException("在执行 update " + entityClass + "中没有发现 @Id 主键标识");
}
continue;
}
field.setAccessible(true);
Object v=field.get(m);
Column column = field.getAnnotation(Column.class);
String columnLabel;
if (column == null || (columnLabel = column.name()).equals("")) {
continue;
}
if(v!=null && field.getType().isEnum()){ //如果是枚举类型
Enum em=(Enum) v;
Enumerated enumerated=field.getAnnotation(Enumerated.class);
EnumType enumType;
if(enumerated!=null && (enumType=enumerated.value())!=null && enumType.equals(EnumType.ORDINAL)){
v=em.ordinal();
}else{
v=em.name();
}
}
sets.append("m." + columnLabel + "=?,");
lvs.add(v);
}
lvs.add(primaryValue);
String sql="UPDATE `"+tableName+"` m SET "+sets.substring(0, sets.length()-1)+" WHERE m."+primaryName+"=?";
jdbcTemplate.update(sql, lvs.toArray());
return m;
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
public Integer update(Map setValues, Map condValues) throws SQLException {
if(setValues==null || setValues.isEmpty()){
throw new SQLException("在执行 update " + entityClass + "实例中没有发现需要更新的值");
}
StringBuilder sets=new StringBuilder();
StringBuilder conds=new StringBuilder();
final Object[] pramas=new Object[setValues.size()+condValues.size()];
int setIndex=0;
int condIndex=setValues.size();
for (Field field : fields) {
Column column = field.getAnnotation(Column.class);
String columnLabel;
if (column == null || (columnLabel = column.name()).equals("")) {
continue;
}
String property=field.getName();
//设置set值
if(setValues.containsKey(property)){
sets.append("m."+columnLabel+"=?,");
Object v=setValues.get(property);
if(v!=null && field.getType().isEnum() && v instanceof Enum){ //如果是枚举类型
Enum em=(Enum) v;
Enumerated enumerated=field.getAnnotation(Enumerated.class);
EnumType enumType;
if(enumerated!=null && (enumType=enumerated.value())!=null && enumType.equals(EnumType.ORDINAL)){
v=em.ordinal();
}else{
v=em.name();
}
}
pramas[setIndex]=v;
setIndex++;
}
//设置条件值
if(condValues.containsKey(property)){
conds.append(" m."+columnLabel+"=? AND");
Object v=condValues.get(property);
if(v!=null && field.getType().isEnum() && v instanceof Enum){ //如果是枚举类型
Enum em=(Enum) v;
Enumerated enumerated=field.getAnnotation(Enumerated.class);
EnumType enumType;
if(enumerated!=null && (enumType=enumerated.value())!=null && enumType.equals(EnumType.ORDINAL)){
v=em.ordinal();
}else{
v=em.name();
}
}
pramas[condIndex]=v;
condIndex++;
}
}
if(sets.length()==0){
throw new SQLException("在执行 update " + entityClass + "实例中没有发现需要更新的值");
}
if(conds.length()==0){
throw new SQLException("在执行 update " + entityClass + "实例中没有设置条件");
}
String sql="UPDATE `"+tableName+"` m SET "+sets.substring(0, sets.length()-1)+" WHERE "+conds.substring(0, conds.length()-3);
return jdbcTemplate.update(sql, pramas);
}
public Integer update(String setProperty, Object setValue, final String condProperty, final Object condValue) throws SQLException {
return update(setProperty, setValue, new HashMap(){{
put(condProperty, condValue);
}});
}
public Integer update(final String setProperty,final Object setValue, Map condValues) throws SQLException {
return update(new HashMap(){{
put(setProperty, setValue);
}}, condValues);
}
public Integer update(Map setValues, final String condProperty, final Object condValue) throws SQLException {
return update(setValues, new HashMap(){{
put(condProperty, condValue);
}});
}
public Integer deleteById(Serializable id) throws SQLException {
String sql = "delete from " + tableName + " where " + getPrimaryColumnLabel() + "=?";
return jdbcTemplate.update(sql, id);
}
public Integer delete(M m) throws SQLException {
try {
StringBuilder conds=new StringBuilder();
final List lvs=new ArrayList();
for (Field field : fields) {
field.setAccessible(true);
Object v=field.get(m);
if(v!=null){
Column column = field.getAnnotation(Column.class);
String columnLabel;
if (column == null || (columnLabel = column.name()).equals("")) {
continue;
}
if(field.getType().isEnum()){ //如果是枚举类型
Enum em=(Enum) v;
Enumerated enumerated=field.getAnnotation(Enumerated.class);
EnumType enumType;
if(enumerated!=null && (enumType=enumerated.value())!=null && enumType.equals(EnumType.ORDINAL)){
v=em.ordinal();
}else{
v=em.name();
}
}
conds.append(" "+columnLabel+"=? AND");
lvs.add(v);
}
}
if(conds.length()==0){
throw new SQLException("在执行 delete " + entityClass + "实例中没有设置条件");
}
String sql="DELETE FROM "+tableName+" WHERE "+conds.substring(0, conds.length()-3);
return jdbcTemplate.update(sql, lvs.toArray());
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return 0;
}
protected final JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
private class entityRowMapper implements RowMapper {
public M mapRow(ResultSet rs, int rowNum) throws SQLException {
M m = null;
try {
ResultSetMetaData rsmd = rs.getMetaData();
int count = rsmd.getColumnCount();
String[] columnLabels = new String[count];
for (int i = 0; i < count; i++) {
columnLabels[i] = rsmd.getColumnLabel(i + 1);
}
m = entityClass.newInstance();
for (Field field : fields) {
Column column = field.getAnnotation(Column.class);
String columnLabel;
if (column == null || (columnLabel = column.name()).equals("")
|| !Arrays.asList(columnLabels).contains(columnLabel)) {
continue;
}
Object value = getResultSetValue(rs, columnLabel, field.getType());
field.setAccessible(true);
field.set(m, value);
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
return m;
}
}
protected final RowMapper getRowMapper(){
return new entityRowMapper();
}
/**
* 获取主键字段名
* @return 返回主键的字段名称
* @throws SQLException 抛出数据库异常
*/
protected final String getPrimaryColumnLabel() throws SQLException {
for (Field field : fields) {
Id pk = field.getAnnotation(Id.class);
if (pk != null) {
Column column = field.getAnnotation(Column.class);
if (column != null && !column.name().equals("")) {
return column.name();
} else {
throw new SQLException("在" + entityClass + "中没有发现 @Id 主键标识");
}
}
}
throw new SQLException("在" + entityClass + "中没有发现 @Id 主键标识");
// return "id";
}
/**
* 获取主键的属性
* @return 返回主键的属性
* @throws SQLException 抛出数据库异常
*/
protected final String getPrimaryProperty() throws SQLException {
for (Field field : fields) {
Id pk = field.getAnnotation(Id.class);
if (pk != null) {
return field.getName();
}
}
throw new SQLException("在" + entityClass + "中没有发现 @Id 主键标识");
}
/**
* 根据属性获取对应字段名
* @param property 映射对象的属性名称
* @return 返回属性对应的字段名称
* @throws SQLException 抛出数据库异常
*/
protected final String getColumnLabelByProperty(String property) throws SQLException {
for (Field field : fields) {
if (field!=null && field.getName().equals(property)) {
Column column = field.getAnnotation(Column.class);
if (column != null && !column.name().equals("")) {
return column.name();
} else {
throw new SQLException("在" + entityClass + "中没有发现 属性为" + property + " @column 标识");
}
}
}
throw new SQLException("在" + entityClass + "中没有发现 属性为" + property + " @column 标识");
}
/**
* 获取对象中某个属性的值
* @param m 映射的对象
* @param property 需要获取的属性名称
* @return 返回 m 对象中 property 的值
*/
protected Object getValueByProperty(M m,String property) {
for(Field field:fields){
if(field.getName().equals(property)){
field.setAccessible(true);
return ReflectionUtils.getField(field, m);
}
}
return null;
}
protected final static Object getResultSetValue(ResultSet rs, String columnLabel, Class> requiredType)
throws SQLException {
Object value = null;
// Explicitly extract typed value, as far as possible.
if (String.class.equals(requiredType)) {
return rs.getString(columnLabel);
} else if (boolean.class.equals(requiredType) || Boolean.class.equals(requiredType)) {
value = rs.getBoolean(columnLabel);
} else if (byte.class.equals(requiredType) || Byte.class.equals(requiredType)) {
value = rs.getByte(columnLabel);
} else if (short.class.equals(requiredType) || Short.class.equals(requiredType)) {
value = rs.getShort(columnLabel);
} else if (int.class.equals(requiredType) || Integer.class.equals(requiredType)) {
value = rs.getInt(columnLabel);
} else if (long.class.equals(requiredType) || Long.class.equals(requiredType)) {
value = rs.getLong(columnLabel);
} else if (float.class.equals(requiredType) || Float.class.equals(requiredType)) {
value = rs.getFloat(columnLabel);
} else if (double.class.equals(requiredType) || Double.class.equals(requiredType)
|| Number.class.equals(requiredType)) {
value = rs.getDouble(columnLabel);
} else if (BigDecimal.class.equals(requiredType)) {
return rs.getBigDecimal(columnLabel);
} else if (java.sql.Date.class.equals(requiredType)) {
return rs.getDate(columnLabel);
} else if (java.sql.Time.class.equals(requiredType)) {
return rs.getTime(columnLabel);
} else if (java.sql.Timestamp.class.equals(requiredType) || java.util.Date.class.equals(requiredType)) {
return rs.getTimestamp(columnLabel);
} else if (byte[].class.equals(requiredType)) {
return rs.getBytes(columnLabel);
} else if (Blob.class.equals(requiredType)) {
return rs.getBlob(columnLabel);
} else if (Clob.class.equals(requiredType)) {
return rs.getClob(columnLabel);
}else if(requiredType.isEnum()){//如果是枚举类型
try {
Object columnValue=rs.getObject(columnLabel);
if(columnValue==null){
return null;
}
Object[] objs=requiredType.getEnumConstants();
if(columnValue instanceof String){
for(Object obj:objs){
Enum em=(Enum) obj;
if(em.name().toUpperCase().equals(((String) columnValue).toUpperCase())){
return obj;
}
}
}else if(columnValue instanceof Integer){
for(Object obj:objs){
Enum em=(Enum) obj;
if(em.ordinal()==Integer.parseInt(String.valueOf(columnValue))){
return obj;
}
}
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
}
return (rs.wasNull() ? null : value);
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
}
private class QueryImpl implements Query{
private String orderColumnLabel,by;
public QueryImpl() {
this.orderColumnLabel=defaultOrderColumnLabel;
this.by=defaultBy;
}
public QueryImpl(String orderColumnLabel,String by) throws SQLException {
this.orderColumnLabel=orderColumnLabel;
this.by=by;
}
public String orderBy() throws SQLException{
if(StringUtils.isEmpty(orderColumnLabel)){
return "";
}
return " ORDER BY m."+orderColumnLabel+" "+by;
}
public M find(Serializable id) throws SQLException {
String sql = "select * from " + tableName + " m where m." + getPrimaryColumnLabel() + "=?";
List list=jdbcTemplate.query(sql, new entityRowMapper(), id);
if(list==null || list.size()==0){
return null;
}
return list.get(0);
}
public M find(String property, Object value) throws SQLException {
String sql = "select * from " + tableName + " m where m." + getColumnLabelByProperty(property) + "=?"+orderBy()+" LIMIT 0,1";
List list=jdbcTemplate.query(sql, new entityRowMapper(), value);
if(list==null || list.size()==0){
return null;
}
return list.get(0);
}
public List query(String property, Object value) throws SQLException {
String sql = "select * from " + tableName + " m where m." + getColumnLabelByProperty(property) + "=?"+orderBy();
return jdbcTemplate.query(sql, new entityRowMapper(), value);
}
public List query(String property, Object value, Integer start, Integer num) throws SQLException {
String sql = "select * from " + tableName + " m where m." + getColumnLabelByProperty(property) + "=?"+orderBy()+" LIMIT ?,?";
return jdbcTemplate.query(sql, new entityRowMapper(), value,start,num);
}
public List query(M m, Integer start, Integer num) throws SQLException {
try {
StringBuilder conds=new StringBuilder();
final List lvs=new ArrayList();
for (Field field : fields) {
field.setAccessible(true);
Object v=field.get(m);
if(v!=null){
Column column = field.getAnnotation(Column.class);
String columnLabel;
if (column == null || (columnLabel = column.name()).equals("")) {
continue;
}
if(field.getType().isEnum()){ //如果是枚举类型
Enum em=(Enum) v;
Enumerated enumerated=field.getAnnotation(Enumerated.class);
EnumType enumType;
if(enumerated!=null && (enumType=enumerated.value())!=null && enumType.equals(EnumType.ORDINAL)){
v=em.ordinal();
}else{
v=em.name();
}
}
conds.append(" m."+columnLabel+"=? AND");
lvs.add(v);
}
}
if(conds.length()==0){
throw new SQLException("在执行 query " + entityClass + "实例中没有设置条件");
}
String sql="SELECT * FROM "+tableName+" m WHERE "+conds.substring(0, conds.length()-3) +orderBy()+" LIMIT ?,?";
lvs.add(start);
lvs.add(num);
return jdbcTemplate.query(sql, new entityRowMapper(), lvs.toArray());
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
public List query(M m) throws SQLException{
try {
StringBuilder conds=new StringBuilder();
final List lvs=new ArrayList();
for (Field field : fields) {
field.setAccessible(true);
Object v=field.get(m);
if(v!=null){
Column column = field.getAnnotation(Column.class);
String columnLabel;
if (column == null || (columnLabel = column.name()).equals("")) {
continue;
}
if(field.getType().isEnum()){ //如果是枚举类型
Enum em=(Enum) v;
Enumerated enumerated=field.getAnnotation(Enumerated.class);
EnumType enumType;
if(enumerated!=null && (enumType=enumerated.value())!=null && enumType.equals(EnumType.ORDINAL)){
v=em.ordinal();
}else{
v=em.name();
}
}
conds.append(" m."+columnLabel+"=? AND");
lvs.add(v);
}
}
if(conds.length()==0){
throw new SQLException("在执行 query " + entityClass + "实例中没有设置条件");
}
String sql="SELECT * FROM "+tableName+" m WHERE "+conds.substring(0, conds.length()-3)+orderBy();
return jdbcTemplate.query(sql, new entityRowMapper(), lvs.toArray());
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
public List query(Integer start, Integer num) throws SQLException {
String sql="SELECT m.* FROM `"+tableName+"` m "+orderBy()+" LIMIT ?,?";;
return jdbcTemplate.query(sql,new entityRowMapper(),start,num);
}
public List query() throws SQLException {
String sql="SELECT m.* FROM `"+tableName+"` m "+orderBy();
return jdbcTemplate.query(sql,new entityRowMapper());
}
}
}