JDBC: Writing a common query method using reflection and JDBC meta-data

Source: Internet
Author: User
Tags class definition object object


Several issues were encountered:

1. The column name returned from Oracle is in uppercase, then reflected, and cannot find a relative entitlement.

The number type in 2.oracle returns, it becomes the BigDecimal

public static void Main (string[] args) {String sql = "Select Idcard, Examcard," + "studentname," + "Lacation Location,gra De "+" from student WHERE Idcard =? "; Student s = Get (Student.class, SQL, 7); System.out.println (s);} String sql = "SELECT ID, name, email, birth" <span style= "White-space:pre" ></span>//<span style= " White-space:pre "></span>+" from customers WHERE id =? "; public static <T> t get (class<t> clazz, String sql, Object ... args) {t entity = NULL; Connection Connection = null; PreparedStatement preparedstatement = null; ResultSet ResultSet = null;try {//1. Get ResultSet Object connection = jdbc_tools.getconnection ();p reparedstatement = Connectio N.preparestatement (SQL); for (int i = 0; i < args.length; i++) {Preparedstatement.setobject (i + 1, args[i]);} ResultSet = Preparedstatement.executequery ();//2. Get ResultSetMetaData object ResultSetMetaData rsmd = Resultset.getmetadata ();//3. Create a map<string, Object> object, key: The alias of the SQL query column,//value: The value of the column Map<striNg, object> values = new hashmap<> ();//4. Process the result set. Use ResultSetMetaData to populate 3 corresponding Map objects if (Resultset.next ()) {for (int i = 0; i < Rsmd.getcolumncount (); i++) {//from Resultsetme Tadata gets the alias of the column string ColumnLabel = Rsmd.getcolumnlabel (i + 1);//Gets the value of the column from the result set object Columnvalue = Resultset.getobject (i + 1) ; Values.put (ColumnLabel, Columnvalue);}} 5. If Map is not an empty set, use reflection to create a clazz corresponding object if (values.size () > 0) {entity = Clazz.newinstance ();//5. Traverse the Map object and assign a value to the corresponding property of the Class object using reflection . For (map.entry<string, object> entry:values.entrySet ()) {String fieldName = Entry.getkey (); Object value = Entry.getvalue ();//system.out.println (fieldname+ ":" +value); Reflectionutils.setfieldvalue (Entity, fieldName, value); Problem//system.out.println (Reflectionutils.getdeclaredfield (Entity,fieldname));}}} catch (Exception e) {e.printstacktrace ();} finally {Jdbc_tools.relasesource (ResultSet, connection, PreparedStatement) ;} return entity;}}

Reflectionutils.setfieldvalue (Entity, fieldName, value);

Java.lang.IllegalArgumentException:Can not set int field Xuezaipiao3. Student.grade to Java.math.BigDecimal
at Sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException (unsafefieldaccessorimpl.java:164)
Span style= "White-space:pre" > at Sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException ( unsafefieldaccessorimpl.java:168)
at Sun.reflect.UnsafeIntegerFieldAccessorImpl.set (unsafeintegerfieldaccessorimpl.java:98)
at Java.lang.reflect.Field.set (field.java:741)
at Xuezaipiao3. Reflectionutils.setfieldvalue (reflectionutils.java:156)
at Xuezaipiao3. Thinkinjdbc.get (thinkinjdbc.java:77)
at Xuezaipiao3. Thinkinjdbc.main (thinkinjdbc.java:45)
Student [Idcard=0, Examcard=0, Studentname=null, location=7, GRADE=0]


The number type in Oracle returns BigDecimal through the ResultSet getObject (), cannot be coerced, and Resultsetmeta The alias of the column retrieved by Data Getcolumnlabel () is uppercase

There is no such problem with MySQL

Oracle 10g for


Reflectionutils


Package Xuezaipiao3;import Java.lang.reflect.field;import Java.lang.reflect.invocationtargetexception;import Java.lang.reflect.method;import Java.lang.reflect.modifier;import Java.lang.reflect.parameterizedtype;import java.lang.reflect.type;/** * reflected Utils function set * Provides access to private variables, gets generic type class, extracts Utils functions such as element properties in the collection * @author Administrator * */PUBL IC class Reflectionutils {/** * through reflection, gets the type of the generic parameter of the parent class declared when the class is defined * such as: public EmployeeDAO extends Basedao<employee, Strin g> * @param <T> * @param clazz * @param index * @return */@SuppressWarnings ("unchecked") public static Class GetS Uperclassgenrictype (Class clazz, int index) {Type gentype = Clazz.getgenericsuperclass (); Gentype instanceof Parameterizedtype) {return object.class;} Type [] params = ((Parameterizedtype) gentype). Getactualtypearguments (); if (index >= params.length | | Index < 0) { return object.class;} if (! ( Params[index] instanceof Class) {return object.class;} Return (Class) Params[index];} /** * The generic parameter type of the parent class declared in the class definition is obtained by reflection * such as: public EmployeeDAO extends Basedao<employee, string> * @param <T> * @param clazz * @return */@SuppressWa Rnings ("unchecked") public static<t> class<t> Getsupergenerictype (class<t> clazz) {return Getsuperclassgenrictype (clazz, 0);} /** * cycle up, get Declaredmethod * @param object * @param methodName * @param parametertypes * @return */public static M Ethod Getdeclaredmethod (Object object, String methodName, class<?>[] parametertypes) {for (class<?> Superclass = Object.getclass (); Superclass! = Object.class; Superclass = Superclass.getsuperclass ()) {try {//superclass.getmethod (methodName, parametertypes); return Superclass.getdeclaredmethod (MethodName, parametertypes);} catch (Nosuchmethodexception e) {//method is not in the current class definition, continue to transition upward}//...} return null;} /** * makes filed accessible * @param field */public static void makeaccessible (Field field) {if (! Modifier.ispublic (Field.getmodifiers ())) {field.setaccessible (true);}} /** * Cycle up to get the Declaredfield * @param object * @param filedname * @return */public static Field Getdeclaredfield (Object object, String filedname) {for (class<?> s Uperclass = Object.getclass (); Superclass! = Object.class; Superclass = Superclass.getsuperclass ()) {try {return Superclass.getdeclaredfield (filedname);} catch ( Nosuchfieldexception e) {//field is not in the current class definition, continue to transition upward}}return null;}  /** * Call object method directly, ignoring modifier (private, Protected) * @param object * @param methodName * @param parametertypes * @param parameters * @return * @throws invocationtargetexception * @throws illegalargumentexception */public static Object InvokeMethod (Ob Ject object, String methodName, class<?> [] parametertypes,object [] parameters) throws invocationtargetexception{ METHOD = Getdeclaredmethod (object, MethodName, parametertypes); if (method = = null) {throw new IllegalArgumentException ("Could not Find method [" + MethodName + "] on target [" + Object + "]");} Method.setaccessible (true); try {return Method.invoke (object, parameters);} catch (IllegalaccesSexception e) {System.out.println ("an exception that cannot be thrown");} return null;} /** * Directly Sets object property values, ignores private/protected modifiers, and does not pass Setter * @param object * @param fieldName * @param value */public static V OID SetFieldValue (Object object, String fieldName, Object value) {Field field = Getdeclaredfield (object, FieldName), if (fi Eld = = null) throw new IllegalArgumentException ("Could not the Find field [" + FieldName + "] on target [" + Object + "]"); Accessible (field); try {Field.set (object, value);} catch (Illegalaccessexception e) {System.out.println ("exception not possible to throw");}} /** * Directly reads the object's property values, ignores the private/protected modifier, and does not go through getter * @param object * @param fieldName * @return */public static objec T GetFieldValue (Object object, String fieldName) {Field field = Getdeclaredfield (object, FieldName); if (Field = = null) thro W New IllegalArgumentException ("Could not find field [" + FieldName + "] on target [" + Object + "]"); Makeaccessible (field Object result = Null;try {result = Field.get (Object);} catch (Illegalaccessexception e) {SYstem.out.println ("an exception that cannot be thrown");} return result;}}


JDBC: Writing a common query method using reflection and JDBC meta-data

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.