Java反射机制模拟_用Java反射机制模拟hibernateJDBC操作

packageorg.keyuan.resolve;

importjava.lang.annotation.Annotation;

importjava.lang.reflect.Field;

importjava.lang.reflect.InvocationTargetException;

importjava.lang.reflect.Method;

importjava.sql.Connection;

importjava.sql.PreparedStatement;

importjava.sql.ResultSet;

importjava.sql.SQLException;

importjava.text.SimpleDateFormat;

importjava.util.ArrayList;

importjava.util.Date;

importjava.util.LinkedList;

importjava.util.List;

importjavax.persistence.Column;

importjavax.persistence.Entity;

importjavax.persistence.Id;

importorg.apache.commons.beanutils.BeanUtils;

importorg.keyuan.entity.Student;

importorg.keyuan.util.DBConnectionUtil;

/**

*

* 说明:使用java的反射机制模拟hibernate的session

*

* @author KeYuan

*

*/

publicclassSession {

privateConnection conn =null;

/**

* 添加操作

*/

publicbooleansave(Object entity)throwsSecurityException,

NoSuchMethodException, IllegalArgumentException,

IllegalAccessException, SQLException, ClassNotFoundException {

StringBuffer insertSql =newStringBuffer("insert into ");

StringBuffer insertSqlValue =newStringBuffer();

LinkedList insertParams =newLinkedList();

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,

newClass[] {});

// 同上判断这个方法有没有我们要找的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());

inti =1;

for(Object param : insertParams) {

if(paraminstanceofDate) {

SimpleDateFormat dateFormat =newSimpleDateFormat("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)

returntrue;

returnfalse;

}

/**

* 得到表的真实名

*/

privateString 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;

}

returntableName;

}

/**

* 查询字段或是属性上面有没有有效annotation

*/

privateObject[] findAnnotation(Annotation[] annotations) {

Object[] resurlt =newObject[] {false,null};

if(annotations.length ==0)

returnresurlt;

for(Annotation annotation : annotations) {

// 我们假定当他找到下列标签中任何一个标签就认为是要与数据库映射的

if(annotationinstanceofColumn) {

resurlt[0] =true;

Column column = (Column) annotation;

String tempColumnName = column.name();

if(tempColumnName !=null&& !"".equals(tempColumnName))

resurlt[1] = tempColumnName;

}

}

returnresurlt;

}

/**

*  修改操作

*/

publicbooleanupdate(Object entity)throwsSecurityException,

NoSuchMethodException, IllegalArgumentException,

IllegalAccessException, ClassNotFoundException, SQLException {

// update stuInfo stu set stu.stuName1='ddd' where stu.stuid=43

StringBuffer updateSql =newStringBuffer("update ");

LinkedList updateParams =newLinkedList();

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();

// 判断是否是主键

booleanisfindPrimarykey =false;

for(Annotation annotation : annotations) {

if(annotationinstanceofId) {

primaryKeyColumn = field.getName();

field.setAccessible(true);

primaryParam = (Integer) field.get(entity);

isfindPrimarykey =true;

break;

}

}

if(isfindPrimarykey)

continue;

Object[] findAnnotationResult = findAnnotation(annotations);

booleanisAnnotaionOverField = (Boolean) findAnnotationResult[0];

if(!isAnnotaionOverField) {

String getMethodName ="get"

+ columnName.substring(0,1).toUpperCase()

+ columnName.substring(1);

Method method = entityClass.getMethod(getMethodName,

newClass[] {});

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());

inti =1;

for(Object param : updateParams) {

if(paraminstanceofDate) {

SimpleDateFormat dateFormat =newSimpleDateFormat("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)

returntrue;

returnfalse;

}

/**

*  删除操作

*/

publicbooleandelete(Object entity)throwsIllegalArgumentException,

IllegalAccessException, ClassNotFoundException, SQLException {

// delete from stuInfo stu where stu.stuid=43

StringBuffer deleteSql =newStringBuffer("delete from ");

Integer primaryParam =null;

Class> entityClass = entity.getClass();

String tableName = getTableName(entityClass);

deleteSql.append(tableName).append(" tab ").append("where ");

Field[] fields = entityClass.getDeclaredFields();

for(Field field : fields) {

Annotation[] annotations = field.getAnnotations();

booleanisfindPrimary =false;

for(Annotation annotation : annotations) {

if(annotationinstanceofId) {

deleteSql.append("tab.").append(field.getName()).append(

"=?");

field.setAccessible(true);

primaryParam = (Integer) field.get(entity);

isfindPrimary =true;

break;

}

}

if(isfindPrimary)

break;

}

conn = DBConnectionUtil.getConnection();

System.out.println(deleteSql.toString());

PreparedStatement prep = conn.prepareStatement(deleteSql.toString());

prep.setInt(1, primaryParam);

if(prep.executeUpdate() >0)

returntrue;

returnfalse;

}

/**

* 根据Id查询某个实体对象

*/

public T get(Class entityClass, Integer id)

throwsClassNotFoundException, SQLException,

InstantiationException, IllegalAccessException, SecurityException,

NoSuchMethodException, IllegalArgumentException,

InvocationTargetException {

T entity =null;

StringBuffer selectByIdSql =newStringBuffer("select * from ");

String tableName = getTableName(entityClass);

selectByIdSql.append(tableName).append(" tab where tab.");

Field[] fields = entityClass.getDeclaredFields();

for(Field field : fields) {

Annotation[] annotations = field.getAnnotations();

booleanisfindPrimaryfield =false;

String columnName = field.getName();

for(Annotation annotation : annotations) {

if(annotationinstanceofId) {

selectByIdSql.append(columnName).append("=?");

isfindPrimaryfield =true;

break;

}

}

if(!isfindPrimaryfield) {

String getMethodName ="get"

+ columnName.substring(0,1).toUpperCase()

+ columnName.substring(1);

Method getMethod = entityClass.getMethod(getMethodName,

newClass[] {});

annotations = getMethod.getAnnotations();

for(Annotation annotation : annotations) {

if(annotationinstanceofId) {

selectByIdSql.append(columnName).append("=?");

isfindPrimaryfield =true;

break;

}

}

}

if(isfindPrimaryfield)

break;

}

System.out.println(selectByIdSql.toString());

conn = DBConnectionUtil.getConnection();

PreparedStatement prep = conn

.prepareStatement(selectByIdSql.toString());

prep.setInt(1, id);

ResultSet result = prep.executeQuery();

while(result.next()) {

entity = setData2Entity(entityClass, fields, result);

}

returnentity;

}

/**

*装result中的数据据,用反射加入到对应的实体中

*/

private T setData2Entity(Class entityClass, Field[] fields,

ResultSet result)throwsInstantiationException,

IllegalAccessException, NoSuchMethodException, SQLException,

InvocationTargetException {

// 把数据组拼到对象中去

T entity = entityClass.newInstance();

for(Field field : fields) {

String fieldName = field.getName();

String columnName = fieldName;

Annotation[] annotations = field.getAnnotations();

Object[] findAnnotationResult = findAnnotation(annotations);

booleanisfindAnotation = (Boolean) findAnnotationResult[0];

if(!isfindAnotation) {

String getMethodName ="get"

+ fieldName.substring(0,1).toUpperCase()

+ fieldName.substring(1);

Method method = entityClass.getMethod(getMethodName,

newClass[] {});

annotations = method.getAnnotations();

findAnnotationResult = findAnnotation(annotations);

isfindAnotation = (Boolean) findAnnotationResult[0];

}

String tempColumnName = (String) findAnnotationResult[1];

if(tempColumnName !=null&& !"".equals(tempColumnName))

columnName = tempColumnName;

Object value = result.getObject(columnName);

BeanUtils.setProperty(entity, fieldName, value);

}

returnentity;

}

/**

* 分页查询所有记录

**/

public List getPaging(Class entityClass,intfirstIndex,

intmaxResult)throwsClassNotFoundException, SQLException,

InstantiationException, IllegalAccessException,

NoSuchMethodException, InvocationTargetException {

List results =newArrayList();

StringBuffer pageIngSql =newStringBuffer(

"select * from (select rownum rn,tab.* from ");

String tableName = getTableName(entityClass);

pageIngSql.append(tableName).append(" tab ) where rn between ? and ?");

System.out.println(pageIngSql.toString());

conn = DBConnectionUtil.getConnection();

PreparedStatement prep = conn.prepareStatement(pageIngSql.toString());

prep.setInt(1, firstIndex);

prep.setInt(2, firstIndex + maxResult);

ResultSet result = prep.executeQuery();

Field[] fields = entityClass.getDeclaredFields();

while(result.next()) {

T entity = setData2Entity(entityClass, fields, result);

results.add(entity);

}

returnresults;

}

/**

* 得到总页数

*/

publicintgetCount(Class entityClass)

throwsClassNotFoundException, SQLException {

intcount =0;

StringBuffer countSql =newStringBuffer("select count(*) count from ");

String tableName = getTableName(entityClass);

countSql.append(tableName);

System.out.println(countSql.toString());

conn = DBConnectionUtil.getConnection();

PreparedStatement prep = conn.prepareStatement(countSql.toString());

ResultSet result = prep.executeQuery();

if(result.next()) {

count = result.getInt("count");

}

returncount;

}

//测试

publicstaticvoidmain(String[] args)throwsSecurityException,

IllegalArgumentException, NoSuchMethodException,

IllegalAccessException, SQLException, ClassNotFoundException,

InstantiationException, InvocationTargetException {

Session session =newSession();

Student student =newStudent();

student.setStuId(2);

student.setStuName("hhhh");

student.setBirthday(newDate());

/*

if (session.save(student)) {

System.out.println("添加成功");

} else {

System.out.println("添加失败");

}

*/

/*

* student.setStuId(43);

* if (session.update(student)) {

*  System.out.println("修改成功");

* }

* else {

*  System.out.println("修改失败");

*   }

*/

/*

* student.setStuId(42);

* if (session.delete(student)) {

*  System.out.println("删除成功");

*  } else {

*  System.out.println("删除失败");

*   }

*/

/*

* 根据id查询 student = session.get(Student.class, 41);

* System.out.println(student.getStuId() + " name:" +

* student.getStuName() + "  birthday:" + student.getBirthday());

*/

/*

* 分页查询

*/

intcurrentPage =1;

intmaxResult =2;

intcount = session.getCount(Student.class);

intcountPage = count / maxResult ==0? count / maxResult : count

/ maxResult +1;

intfirstIndex = (currentPage -1) * maxResult+1;

List pagingList = session.getPaging(Student.class,

firstIndex, maxResult);

System.out

.println("总页数:"+ countPage +" \t 当前第 "+ currentPage +" 页");

System.out.println("编号\t姓名\t出生年日");

for(Student student2 : pagingList) {

System.out.println(student2.getStuId() +"\t"

+ student2.getStuName() +"\t"+ student2.getBirthday());

}

}

}

测试实体类:Student

packageorg.keyuan.entity;

importjava.util.Date;

importjavax.persistence.Column;

importjavax.persistence.Entity;

importjavax.persistence.Id;

@Entity(name="stuInfo")

publicclassStudent {

@Id

privateintstuId;

privateString stuName;

privateDate birthday;

@Id

publicintgetStuId() {

returnstuId;

}

publicvoidsetStuId(intstuId) {

this.stuId = stuId;

}

@Column(name="stuName1")

publicString getStuName() {

returnstuName;

}

publicvoidsetStuName(String stuName) {

this.stuName = stuName;

}

@Column(name="birthday")

publicDate getBirthday() {

returnbirthday;

}

publicvoidsetBirthday(Date birthday) {

this.birthday = birthday;

}

}

连接工具类:DbConnectionUtil

packageorg.keyuan.util;

importjava.sql.Connection;

importjava.sql.DriverManager;

importjava.sql.SQLException;

publicclassDBConnectionUtil {

privatestaticfinalString DRIVER="Oracle.jdbc.driver.OracleDriver";

privatestaticfinalString URL ="jdbc:oracle:thin:@localhost:1521:KEYUAN";

privatestaticfinalString PASSWORD ="test";

privatestaticfinalString USER ="test";

privatestaticClass> driverClass;

static{

try{

initDriver();

}catch(ClassNotFoundException e) {

e.printStackTrace();

}

}

privatestaticvoidinitDriver()throwsClassNotFoundException{

driverClass=Class.forName(DRIVER);

}

publicstaticConnection getConnection()throwsClassNotFoundException, SQLException{

if(driverClass==null)

initDriver();

returnDriverManager.getConnection(URL,USER,PASSWORD);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值