package org.keyuan.resolve;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.apache.commons.beanutils.BeanUtils;
import org.keyuan.entity.Student;
import org.keyuan.util.DBConnectionUtil;
/**
*
* 说明:使用java的反射机制模拟hibernate的session
*
* @author KeYuan
*
*/
public class Session {
private Connection conn = null;
/**
* 添加操作
*/
public boolean save(Object entity) throws SecurityException,
NoSuchMethodException, IllegalArgumentException,
IllegalAccessException, SQLException, ClassNotFoundException {
StringBuffer insertSql = new StringBuffer("insert into ");
StringBuffer insertSqlValue = new StringBuffer();
LinkedList<Object> insertParams = new LinkedList<Object>();
Class<?> entityClass = entity.getClass();
String tableName = getTableName(entityClass);
insertSql.append(tableName);
Field[] fields = entityClass.getDeclaredFields();
insertSql.append("(");
insertSqlValue.append(" values(");
for (Field field : fields) {
Annotation[] annotations = field.getAnnotations();
String columnName = field.getName();
// 查找当前属性上面是否有annotation注解
Object[] findAnnotationResult = findAnnotation(annotations);
Boolean isAnnotaionOverField = (Boolean) findAnnotationResult[0];
// 如果在field中上面没有找到annotation,继续到get属性上去找有没有annotation
if (!isAnnotaionOverField) {
// 拼接出field的get属性名
String getMethodName = "get"
+ columnName.substring(0, 1).toUpperCase()
+ columnName.substring(1);
Method method = entityClass.getMethod(getMethodName,
new Class[] {});
// 同上判断这个方法有没有我们要找的annotation
annotations = method.getAnnotations();
findAnnotationResult = findAnnotation(annotations);
isAnnotaionOverField = (Boolean) findAnnotationResult[0];
}
// 判断通过前面两步操作有没有在当前的字段上面找到有效的annotation
if (!isAnnotaionOverField)
continue;
// 到这步说明在当前的字段或字段get属性上面找到有效的annotation了
// 拼接insert sql 语句
String tempColumnName = (String) findAnnotationResult[1];
if (tempColumnName != null && !"".equals(tempColumnName))
columnName = tempColumnName;
insertSql.append(columnName).append(",");// 前面列名部分
insertSqlValue.append("?,"); // 后面?参数部分
// 得到对应的字段值并记录,作为以后?部分值
field.setAccessible(true);
insertParams.add(field.get(entity));
}
insertSql.replace(insertSql.lastIndexOf(","), insertSql.length(), ")");
insertSqlValue.replace(insertSqlValue.lastIndexOf(","), insertSqlValue
.length(), ")");
// 拼接两部分的sql
insertSql.append(insertSqlValue);
System.out.println(insertSql);
// 执行添加操作了
conn = DBConnectionUtil.getConnection();
PreparedStatement prep = conn.prepareStatement(insertSql.toString());
int i = 1;
for (Object param : insertParams) {
if (param instanceof Date) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
java.sql.Date date = java.sql.Date.valueOf(dateFormat
.format(param));
prep.setDate(i, date);
} else {
prep.setObject(i, param);
}
i++;
}
if (prep.executeUpdate() > 0)
return true;
return false;
}
/**
* 得到表的真实名
*/
private String getTableName(Class<?> entityClass) {
String tableName = entityClass.getSimpleName();
if (entityClass.isAnnotationPresent(Entity.class)) {
Entity entityAnnotation = entityClass.getAnnotation(Entity.class);
String tempTableName = entityAnnotation.name();
if (tempTableName != null && !"".equals(tempTableName))
tableName = tempTableName;
}
return tableName;
}
/**
* 查询字段或是属性上面有没有有效annotation
*/
private Object[] findAnnotation(Annotation[] annotations) {
Object[] resurlt = new Object[] { false, null };
if (annotations.length == 0)
return resurlt;
for (Annotation annotation : annotations) {
// 我们假定当他找到下列标签中任何一个标签就认为是要与数据库映射的
if (annotation instanceof Column) {
resurlt[0] = true;
Column column = (Column) annotation;
String tempColumnName = column.name();
if (tempColumnName != null && !"".equals(tempColumnName))
resurlt[1] = tempColumnName;
}
}
return resurlt;
}
/**
* 修改操作
*/
public boolean update(Object entity) throws SecurityException,
NoSuchMethodException, IllegalArgumentException,
IllegalAccessException, ClassNotFoundException, SQLException {
// update stuInfo stu set stu.stuName1='ddd' where stu.stuid=43
StringBuffer updateSql = new StringBuffer("update ");
LinkedList<Object> updateParams = new LinkedList<Object>();
String primaryKeyColumn = "";
Integer primaryParam = null;
Class<?> entityClass = entity.getClass();
String tableName = getTableName(entityClass);
updateSql.append(tableName).append(" tab set ");
Field[] fields = entityClass.getDeclaredFields();
for (Field field : fields) {
String columnName = field.getName();
Annotation[] annotations = field.getAnnotations();
// 判断是否是主键
boolean isfindPrimarykey = false;
for (Annotation annotation : annotations) {
if (annotation instanceof Id) {
primaryKeyColumn = field.getName();
field.setAccessible(true);
primaryParam = (Integer) field.get(entity);
isfindPrimarykey = true;
break;
}
}
if (isfindPrimarykey)
continue;
Object[] findAnnotationResult = findAnnotation(annotations);
boolean isAnnotaionOverField = (Boolean) findAnnotationResult[0];
if (!isAnnotaionOverField) {
String getMethodName = "get"
+ columnName.substring(0, 1).toUpperCase()
+ columnName.substring(1);
Method method = entityClass.getMethod(getMethodName,
new Class[] {});
annotations = method.getAnnotations();
findAnnotationResult = findAnnotation(annotations);
isAnnotaionOverField = (Boolean) findAnnotationResult[0];
}
if (!isAnnotaionOverField)
continue;
String tempColumnName = (String) findAnnotationResult[1];
if (tempColumnName != null && !"".equals(tempColumnName))
columnName = tempColumnName;
updateSql.append("tab.").append(columnName).append("=?,");
field.setAccessible(true);
updateParams.add(field.get(entity));
}
updateSql.replace(updateSql.lastIndexOf(","), updateSql.length(), "");
updateSql.append(" where tab.").append(primaryKeyColumn).append("=?");
System.out.println(updateSql);
conn = DBConnectionUtil.getConnection();
PreparedStatement prep = conn.prepareStatement(updateSql.toString());
int i = 1;
for (Object param : updateParams) {
if (param instanceof Date) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
java.sql.Date date = java.sql.Date.valueOf(dateFormat
.format(param));
prep.setDate(i, date);
} else {
prep.setObject(i, param);
}
i++;
}
prep.setInt(i, primaryParam);
if (prep.executeUpdate() > 0)
return true;
return false;
}
/**
* 删除操作
*/
public boolean delete(Object entity) throws IllegalArgumentException,
IllegalAccessException, ClassNotFoundException, SQLException {
// delete from stuInfo stu where stu.stuid=43
StringBuffer deleteSql = new StringBuffer("delete from ");
Integer primaryParam = null;
Class<?> entityClass = entity.getClass();
String tableName = getTableName(entityClass);