com.mario6.common.db.mapper.ClassInfo Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of spring-jdbc Show documentation
Show all versions of spring-jdbc Show documentation
一个简单的jdbc封装库,大多数api接口与spring-jdbc类似
The newest version!
package com.mario6.common.db.mapper;
import com.mario6.common.db.util.Utils;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
/**
* 存储类的反射得到的一些信息
*/
public class ClassInfo {
private ClassOnlyInfo classInfo;
private FieldInfo idFieldInfo;
private List otherFieldsInfo;
private static ConcurrentHashMap cache = new ConcurrentHashMap<>();
private ClassInfo(Class clazz, boolean fastFailed) {
this.classInfo = new ClassOnlyInfo(clazz);
Field[] fields = clazz.getDeclaredFields();
this.otherFieldsInfo = new ArrayList<>(fields.length);
boolean isId = false;
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
int modifiers = field.getModifiers();
if( Modifier.isStatic(modifiers) ) {
// 忽略静态字段
continue;
}
// TODO 可能需要考虑Id注解重复的情况
Id annotation = field.getAnnotation(Id.class);
if(annotation != null && !isId) {
this.setIdField(field);
isId = true;
} else {
this.addOtherFields(field);
}
}
if(!isId && fastFailed) {
throw new IllegalArgumentException("实体类未标示@Id主键字段 " + clazz.getName());
}
}
/**
* 静态工厂方法
*/
public static ClassInfo newInstance(Class clazz, boolean fastFailed) {
ClassInfo classInfo = cache.get(clazz);
// TODO 修复可能出现的多线程重复计算问题
if(classInfo == null) {
classInfo = new ClassInfo(clazz, fastFailed);
cache.put(clazz, classInfo);
} else if(fastFailed == true) {
if(classInfo.idFieldInfo == null) {
throw new IllegalStateException("Id字段未标示");
}
}
return classInfo;
}
public static ClassInfo newInstance(Class clazz) {
return newInstance(clazz, true);
}
/**
* 获得insert语句的列列表
* @param snake 蛇形命名
* @return
*/
public List getInsertColumns(boolean snake) {
return doGetInsertColumns(null, false, snake);
}
/**
* 获得insert语句的列列表, 对null敏感
* @param snake 蛇形命名
* @return
*/
public List getInsertColumnsSelective(T obj, boolean snake) {
return doGetInsertColumns(obj, true, snake);
}
/**
* 获得insert语句列列表
* @param obj 该类型对象,当切仅当selective==false时可以为null
* @param selective 空值不插入
* @param snake 字段蛇形命名
* @return
*/
private List doGetInsertColumns(T obj, boolean selective, boolean snake) {
ArrayList results = new ArrayList<>(this.otherFieldsInfo.size());
List otherFieldsInfo = this.otherFieldsInfo;
for(int i =0; i getInsertValues(T obj) {
return doGetInsertValues(obj, false);
}
/**
* 获得insert语句的列的值,对null敏感
* @param obj
* @return
*/
public List