public static<T> T
selectOne(Connection con
,String sql
,Class
<T> cls
,Object
...param
) throws Exception
{
ps
= con
.prepareStatement(sql
);
for(int i
=0;i
<param
.length
;i
++){
ps
.setObject(i
+1, param
[i
]);
}
rs
= ps
.executeQuery();
T t
= null
;
if (rs
.next()) {
t
= cls
.newInstance();
Field
[] fields
= cls
.getDeclaredFields();
for (Field field
: fields
) {
Column column
= field
.getAnnotation(Column
.class);
if(column
!= null
){
Object oValue
= rs
.getObject(column
.values());
if(oValue
!= null
){
String fieldName
= field
.getName();
Method m
= cls
.getDeclaredMethod("set"+fieldName
.substring(0,1).toUpperCase()
+fieldName
.substring(1),oValue
.getClass());
m
.invoke(t
, oValue
);
}
}
}
}
return t
;
}
public static<T> List
<T> selectList(Connection con
,String sql
,Class
<T> cls
,Object
...param
) throws Exception
{
List
<T> tList
= new ArrayList<T>();
ps
= con
.prepareStatement(sql
);
for(int i
=0;i
<param
.length
;i
++){
ps
.setObject(i
+1, param
[i
]);
}
rs
= ps
.executeQuery();
while(rs
.next()){
T t
= cls
.newInstance();
Field
[] fields
= cls
.getDeclaredFields();
for (Field field
: fields
) {
Column column
= field
.getAnnotation(Column
.class);
if(column
!= null
){
Object oValue
= rs
.getObject(column
.values());
if(oValue
!= null
){
String fieldName
= field
.getName();
Method m
= cls
.getDeclaredMethod("set"+fieldName
.substring(0,1).toUpperCase()
+fieldName
.substring(1),oValue
.getClass());
m
.invoke(t
, oValue
);
}
}
}
tList
.add(t
);
}
return tList
;
}
转载请注明原文地址: https://yun.8miu.com/read-132645.html