这类办法和Hibernate/Ibatis比拟能够就义一些功能,然而免除了大批的设置装备摆设文件,假如对字段有特别的请求,可以
经由过程annotation来界说。
Annotation可是个好器材,依据jdk手册:Annotations can be read from source files, class files, or reflectively at run time.
所以可以充实使用反射读取annotation来削减代码。
上面是一些例子
@com.acme.util.Name(first=Alfred, middle=E., last=Neuman)
@Table(tableName="Customer")
@ManyToOne(column = "parent_id", fieldType=java.util.HashSet.class,type = Customer.class,lazy=false)
读取的办法是在反射外面利用上面的办法
<T extends Annotation> T xxx = getAnnotation(Class<T> annotationClass)
固然,完成必需声明annotationClass,上面是手册的一个复杂例子
/**
* Describes the Request-For-Enhancement(RFE) that led
* to the presence of the annotated API element.
界说一个标签记号
*/
public @interface RequestForEnhancement {
int id();
String synopsis();
String engineer() default "[unassigned]";
String date(); default "[unimplemented]";
}
这个标签,和它的属性都在下面声了然,上面是某个函数中需求用到这个标签的示例
@RequestForEnhancement(
id = 2868724,
synopsis = "Enable time-travel",
engineer = "Mr. Peabody",
date = "4/1/3007"
)
public static void travelThroughTime(Date destination) { ... }
因而咱们假如想要挪用这个标签
for (Method m : Class.forName('假定是travelThroughTime地点的类名').getMethods()) {
if (m.isAnnotationPresent(RequestForEnhancement.class)) {
RequestForEnhancement rfe = m.getAnnotation(RequestForEnhancement.class);
上面就能够获得rfe的属性了
}
}
Commons Attributes也是一个替换jdk尺度annotation的计划
===================
另外还有一些办法,可以便利咱们疾速的将RS酿成可操作的对象,复杂举几个例子以下
1 commons dbutils
Custom RowProcessor
java.lang.Object[] toArray(java.sql.ResultSet rs)
Convert a ResultSet row into an Object[].
java.lang.Object toBean(java.sql.ResultSet rs, java.lang.Class type)
Convert a ResultSet row into a JavaBean.
java.util.List toBeanList(java.sql.ResultSet rs, java.lang.Class type)
Convert a ResultSet into a List of JavaBeans.
java.util.Map toMap(java.sql.ResultSet rs)
Convert a ResultSet row into a Map.
Custom BeanProcessor
java.lang.Object toBean(java.sql.ResultSet rs, java.lang.Class type)
Convert a ResultSet row into a JavaBean.
java.util.List toBeanList(java.sql.ResultSet rs, java.lang.Class type)
Convert a ResultSet into a List of JavaBeans.
2 commons beanutils
ResultSetDynaClass (Wraps ResultSet in DynaBeans)
Connection conn = ...;
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery
("select account_id, name from customers");
Iterator rows = (new ResultSetDynaClass(rs)).iterator();
while (rows.hasNext()) {
DynaBean row = (DynaBean) rows.next();
System.out.println("Account number is " +
row.get("account_id") +
" and name is " + row.get("name"));
}
rs.close();
stmt.close();
============
总得来讲,利用反射机制可以极大得便利对数据的各类操作,使操作变得加倍通明,无需设置装备摆设文件