(3) 범용 반사 메커니즘을 이용하여 증가, 삭제, 업데이트, 조회 조작(계승 기류 지원)
7611 단어 자신의 데이터베이스 프레임워크를 봉인하다
/**
* dao,
*
*/
public class BaseDao {
private DbUtil dbUtil = DbUtil.getInstance();
//public Connection connection = dbUtil.getConnection();
private final static int CURD_ADD = 0;
private final static int CURD_UPDATE = 1;
private final static int CURD_FIND = 2;
private final static int CURD_SELECT = 3;
private final static int CURD_DELETE = 4;
private final static int CURD_COUNT = 5;
private Class t;
public BaseDao(){
Type genericSuperclass = this.getClass().getGenericSuperclass();//
if(genericSuperclass instanceof ParameterizedType){
Type[] actualTypeArguments = ((ParameterizedType)genericSuperclass).getActualTypeArguments();
if(actualTypeArguments != null && actualTypeArguments.length > 0){
t = (Class) actualTypeArguments[0];
}
}
//System.out.println(t.getSimpleName());
}
/**
*
* @param t
* @return
*/
public boolean add(T t){
String sql = buildSql(CURD_ADD);
try {
PreparedStatement prepareStatement = dbUtil.getConnection().prepareStatement(sql);
prepareStatement = setPreparedStatement(t,prepareStatement,CURD_ADD);
int rst = prepareStatement.executeUpdate();
dbUtil.releaseConnection();
return rst > 0;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
/**
*
* @param t
* @return
*/
public boolean update(T t){
String sql = buildSql( CURD_UPDATE);
try {
PreparedStatement prepareStatement = dbUtil.getConnection().prepareStatement(sql);
prepareStatement = setPreparedStatement(t,prepareStatement,CURD_UPDATE);
int rst = prepareStatement.executeUpdate();
dbUtil.releaseConnection();
return rst > 0;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
/**
*
* @param id
* @return
*/
public T find(int id){
String sql = buildSql(CURD_FIND);
T newInstance = null;
try {
PreparedStatement prepareStatement = dbUtil.getConnection().prepareStatement(sql);
prepareStatement.setObject(1, id);
ResultSet executeQuery = prepareStatement.executeQuery();
if(executeQuery.next()){
newInstance = (T) t.newInstance();
newInstance = setParams(newInstance,executeQuery);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dbUtil.releaseConnection();
return newInstance;
}
/**
*
* @param newInstance
* @param executeQuery
* @return
*/
private T setParams(T newInstance, ResultSet executeQuery) {
// TODO Auto-generated method stub
//
Field[] declaredFields = newInstance.getClass().getDeclaredFields();
try {
for(Field field :declaredFields){
field.setAccessible(true);
if(field.isAnnotationPresent(Column.class)){
Column annotation = field.getAnnotation(Column.class);
if(!annotation.isForeignEntity()){
//
field.set(newInstance, executeQuery.getObject(annotation.name()));
}else{
Blob blob = executeQuery.getBlob(annotation.name());
ObjectInputStream objectInputStream = new ObjectInputStream(blob.getBinaryStream());
field.set(newInstance, objectInputStream.readObject());
}
}else{
field.set(newInstance, executeQuery.getObject(StringUtil.convertToUnderline(field.getName())));
}
}
Field[] parentFields = newInstance.getClass().getFields();
for(Field field :parentFields){
field.setAccessible(true);
if(field.isAnnotationPresent(Column.class)){
Column annotation = field.getAnnotation(Column.class);
field.set(newInstance, executeQuery.getObject(annotation.name()));
}else{
field.set(newInstance, executeQuery.getObject(StringUtil.convertToUnderline(field.getName())));
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return newInstance;
}
/**
*
* @param prepareStatement
* @return
*/
private PreparedStatement setPreparedStatement(T t,
PreparedStatement prepareStatement,int curdType) {
// TODO Auto-generated method stub
Field[] declaredFields = t.getClass().getDeclaredFields();
try {
switch (curdType) {
case CURD_ADD:{
int index = 1;
for(int i = 0;i fields = getTableFields();
String[] values = new String[fields.size()];
Arrays.fill(values, "?");
for(int i=0;i fields = getTableFields();
return StringUtil.join(fields, ",");
}
/**
*
* @param t
* @return
*/
private List getTableFields() {
// TODO Auto-generated method stub
List ret = new ArrayList();
Field[] declaredFields = t.getDeclaredFields();
for(Field field : declaredFields){
// ,
if(field.isAnnotationPresent(Column.class)){
ret.add(field.getAnnotation(Column.class).name());
continue;
}
ret.add(StringUtil.convertToUnderline(field.getName()));
}
if(BaseEntity.class.isAssignableFrom(t)){
// BaseEntity
Field[] fields = t.getFields();
for(Field field : fields){
// ,
if(field.isAnnotationPresent(Column.class)){
ret.add(field.getAnnotation(Column.class).name());
continue;
}
ret.add(StringUtil.convertToUnderline(field.getName()));
}
}
return ret;
}
/**
*
* @return
*/
private String getTableName() {
// TODO Auto-generated method stub
String tableName = StringUtil.convertToUnderline(t.getSimpleName());
// ,
if(t.isAnnotationPresent(Table.class)){
String prefix = t.getAnnotation(Table.class).prefix();
String sufix = t.getAnnotation(Table.class).sufix();
tableName = StringUtil.isEmpty(prefix) ? "" : prefix + "_";
tableName += t.getAnnotation(Table.class).tableName();
tableName += StringUtil.isEmpty(sufix) ? "" : "_" + sufix;
}
return tableName;
}
/**
*
*/
public void closeConnection(){
dbUtil.releaseConnection();
}
}
사고방식 간략 분석: 기본 구조 방법으로 구체적인 유형을 얻고buildesql는 sql문장을 결합하고SetparperedStastement는 각 조작의 예처리 집합을 얻어 결과 집합을 처리한다.