Using reflection and JDBC meta-data to implement common Query method

Source: Internet
Author: User

--------------------------------------------------------------------------------------------------------------- ------------------------------------------------

1.customer class:

Package com.lanqiao.javatest;

Import Java.sql.Date;

public class Customer {
private int id;
private String name;
Private String Email;
Private Date birth;

Public Customer () {
Super ();
}

public Customer (int ID, string name, string email, Date birth) {
Super ();
This.id = ID;
THIS.name = name;
This.email = email;
This.birth = birth;
}

public int getId () {
return ID;
}

public void setId (int id) {
This.id = ID;
}

Public String GetName () {
return name;
}

public void SetName (String name) {
THIS.name = name;
}

Public String Getemail () {
return email;
}

public void Setemail (String email) {
This.email = email;
}

Public Date Getbirth () {
return birth;
}

public void Setbirth (Date birth) {
This.birth = birth;
}

@Override
Public String toString () {
Return "Customer [id=" + ID + ", name=" + name + ", email=" + email + ", birth=" + Birth + "]";
}
}

--------------------------------------------------------------------------------------------------------------- ---------------------------------------------

Student class:

Package com.lanqiao.javatest;

public class Student {

/*
* Flowid:int, serial number
* Type:int, English level 46
* Idcard:varchar (18), ID number
* Examcard:varchar (15), Examination certificate No.
* Studentname:varchar (20), Student name
* Localtion:varchar (20), regional
* Grade:int, Grades
*/
private int flowid;
private int type;
Private String Idcard;
Private String Examcard;
Private String Studentname;
Private String localtion;
private int grade;

Public Student () {
Super ();
}

Public Student (int flowid, int type, string idcard, String Examcard, String studentname, String localtion,
int grade) {
Super ();
This.flowid = Flowid;
This.type = type;
This.idcard = Idcard;
This.examcard = Examcard;
This.studentname = Studentname;
This.localtion = localtion;
This.grade = grade;
}

public int Getflowid () {
return flowid;
}
public void Setflowid (int flowid) {
This.flowid = Flowid;
}
public int GetType () {
return type;
}
public void SetType (int type) {
This.type = type;
}
Public String Getidcard () {
return idcard;
}
public void Setidcard (String idcard) {
This.idcard = Idcard;
}
Public String Getexamcard () {
return examcard;
}
public void Setexamcard (String examcard) {
This.examcard = Examcard;
}
Public String Getstudentname () {
return studentname;
}
public void Setstudentname (String studentname) {
This.studentname = Studentname;
}
Public String getlocaltion () {
return localtion;
}
public void Setlocaltion (String localtion) {
This.localtion = localtion;
}
public int Getgrade () {
return grade;
}
public void Setgrade (int grade) {
This.grade = grade;
}

@Override
Public String toString () {
return "person [flowid=" + Flowid + ", type=" + Type + ", idcard=" + Idcard + ", examcard=" + Examcard
+ ", studentname=" + Studentname + ", localtion=" + Localtion + ", grade=" + Grade + "]";
}

}

--------------------------------------------------------------------------------------------------------------- --------------------------------------------

Reflection Method:

Package com.lanqiao.javatest;

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;

/**
* Reflection of the Utils function set
* Provide access to private variables, get generic type class, extract Utils functions such as element properties in the collection
* @author Administrator
*
*/
public class Reflectionutils {


/**
* By 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, string>
* @param clazz
* @param index
* @return
*/
@SuppressWarnings ("Unchecked")
public static class Getsuperclassgenrictype (class clazz, int index) {
Type Gentype = Clazz.getgenericsuperclass ();

if (! ( 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
*/
@SuppressWarnings ("Unchecked")
Public static<t> class<t> Getsupergenerictype (Class clazz) {
Return Getsuperclassgenrictype (clazz, 0);
}

/**
* Cycle up to get the declaredmethod of the object
* @param Object
* @param methodName
* @param parametertypes
* @return
*/
public static Method 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 move up
}
//..
}

return null;
}

/**
* Make filed accessible
* @param field
*/
public static void makeaccessible (Field field) {
if (! Modifier.ispublic (Field.getmodifiers ())) {
Field.setaccessible (TRUE);
}
}

/**
* Cycle up to get the Declaredfield of the object
* @param Object
* @param filedname
* @return
*/
public static Field Getdeclaredfield (Object object, String filedname) {

for (class<?> superclass = 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 move up
}
}
return null;
}

/**
* Call object methods directly, ignoring modifiers (private, protected)
* @param Object
* @param methodName
* @param parametertypes
* @param parameters
* @return
* @throws InvocationTargetException
* @throws IllegalArgumentException
*/
public static object InvokeMethod (Object object, String methodName, class<?> [] parametertypes,
Object [] parameters) throws invocationtargetexception{

Method method = Getdeclaredmethod (object, MethodName, parametertypes);

if (method = = null) {
throw new IllegalArgumentException ("Could not the 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 Set object property values, ignore private/protected modifiers, and do not pass setter
* @param Object
* @param fieldName
* @param value
*/
public static void SetFieldValue (Object object, String fieldName, object value) {
Field field = Getdeclaredfield (object, fieldName);

if (field = = null)
throw new IllegalArgumentException ("Could not find field [" + FieldName + "] on target [" + Object + "]");

makeaccessible (field);

try {
Field.set (object, value);
} catch (Illegalaccessexception e) {
System.out.println ("an exception that cannot be thrown");
}
}

/**
* Directly read the object's property values, ignoring the private/protected modifier, and without getter
* @param Object
* @param fieldName
* @return
*/
public static object GetFieldValue (Object object, String fieldName) {
Field field = Getdeclaredfield (object, fieldName);

if (field = = null)
throw 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;
}
}

--------------------------------------------------------------------------------------------------------------- --------------------------------------------

To implement the Main method:

Package com.lanqiao.javatest;

Import Java.io.InputStream;
Import java.sql.Connection;
Import Java.sql.Driver;
Import java.sql.PreparedStatement;
Import Java.sql.ResultSet;
Import java.sql.SQLException;
Import Java.util.HashMap;
Import Java.util.Map;
Import Java.util.Map.Entry;
Import java.util.Properties;

Import javax.management.ReflectionException;
Import Javax.swing.text.FieldView;

Import Org.junit.Test;

Import Com.mysql.jdbc.ResultSetMetaData;
Import com.mysql.jdbc.Statement;

/*
* Establish a unified approach that can reference objects of any class to implement database data processing
* Get any database data from one object
* */
public class Testpreparedstatement {


private static final class<customer> Customer = null;
private static final class<student> Student = null;

=================================================================================
Connect Database methods
public static Connection getconnection () throws exception{

Four connectivity data is essential
String Driverclass=null;
String Jdbcurl=null;
String User=null;
String Password=null;

InputStream in=
TestPreparedStatement.class.getClassLoader (). getResourceAsStream ("jdbc.properties");
Where GetClass and testconnection.classh are used interchangeably
Properties Properties=new properties ();
Properties.load (in);

Driverclass=properties.getproperty ("Driver");
Jdbcurl=properties.getproperty ("Jdbcurl");
User=properties.getproperty ("user");
Password=properties.getproperty ("password");

System.out.println (Driverclass+jdbcurl+user+password);
Driver driver= (Driver) class.forname (Driverclass). newinstance ();
Properties Info=new properties ();
Info.put ("User", "root");
Info.put ("Password", "lxn123");
Connection Connection=driver.connect (Jdbcurl, info);
return connection;
}
Test class
public static void Testgetconn () throws exception{
System.out.println (getconnection ());
}

====================================================================================

Ways to close resources

public void Close (Connection Connection,
PreparedStatement Preparedstatement,resultset ResultSet) throws exception{
if (resultset!=null) {
Resultset.close ();
}
if (preparedstatement!=null) {
Preparedstatement.close ();
}
if (connection!=null) {
Connection.close ();
}
}

===========================================================================================
Student class Get Data
Public Student getstudent (String Sql,object...args) throws exception{
Student Student=null;
Connection Connection=null;
PreparedStatement Preparedstatement=null;
ResultSet Resultset=null;

try {
Connection=testpreparedstatement.getconnection ();
Preparedstatement=connection.preparestatement (SQL);
for (int i=0;i<args.length;i++) {
Preparedstatement.setobject (i+1, args[i]);
}
Resultset=preparedstatement.executequery ();
ResultSet inside the nest () method, the query to the data, student get
if (Resultset.next ()) {
Student=new student ();
Student.setflowid (Resultset.getint (1));
Student.settype (Resultset.getint (2));
Student.setidcard (Resultset.getstring (3));
Student.setexamcard (Resultset.getstring (4));
Student.setstudentname (Resultset.getstring (5));
Student.setlocaltion (resultset.getstring (6));
Student.setgrade (Resultset.getint (7));
}
} catch (Exception e) {
E.printstacktrace ();
}finally {
Close (Connection,preparedstatement,resultset);
}

return student;

}

========================================================================================
The customer class gets the data
Public Customer GetCustomer (String Sql,object...args) throws exception{
Customer Customer=null;
Connection Connection=null;
PreparedStatement Preparedstatement=null;
ResultSet Resultset=null;

try {
Connection=testpreparedstatement.getconnection ();
Preparedstatement=connection.preparestatement (SQL);
for (int i=0;i<args.length;i++) {
Preparedstatement.setobject (i+1, args[i]);
}
Resultset=preparedstatement.executequery ();
ResultSet inside the nest () method, the query to the data, student get
if (Resultset.next ()) {
Customer=new Customer ();
Customer.setid (Resultset.getint (1));
Customer.setname (resultset.getstring (2));
Customer.setemail (Resultset.getstring (3));
Customer.setbirth (Resultset.getdate (4));
}
} catch (Exception e) {
E.printstacktrace ();
}finally {
Close (Connection,preparedstatement,resultset);
}

return customer;
}
=======================================================================================
A common method Template: can use reflection, implement database query, insert value
Public <T> T Gett (Class <T> clazz,string Sql,object...args) throws exception{
T Entity=null;

Connection Connection=null;
PreparedStatement Preparedstatement=null;
ResultSet Resultset=null;

try {
Connection=testpreparedstatement.getconnection ();
Preparedstatement=connection.preparestatement (SQL);
for (int i=0;i<args.length;i++) {
Preparedstatement.setobject (i+1, args[i]);
}
Resultset=preparedstatement.executequery ();

Get the Resultsetmetadate object, get the columns column name in the database
ResultSetMetaData rsmd= (ResultSetMetaData) resultset.getmetadata ();

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<string, object> ();

Process the result set and populate the corresponding map object with the Resultsetmetadate method
while (Resultset.next ()) {
Method getColumnCount () is the number of Get database properties for Resultsetmetadate object
for (int i=0;i<rsmd.getcolumncount (); i++) {
String Columnlabel=rsmd.getcolumnlabel (i+1);//Gets the property, which is a string
Object Columnvalues=resultset.getobject (ColumnLabel);
System.out.println (columnvalues);
Values.put (ColumnLabel, columnvalues);
}
}

Map is not empty, creating clazz objects with Reflection
if (Values.size () >0) {
Entity=clazz.newinstance ();

Traverse map to assign values using the properties of the object corresponding to the reflection class
For (map.entry<string, object> entry:values.entrySet ()) {
String Fieldname=entry.getkey ();
Object Fieldvalues=entry.getvalue ();
System.out.println (fieldname+ ":" +fieldvalues);
The reflection gets the attribute and modifies the xxxx (entity,fieldname,fieldvalues);
Reflectionutils.setfieldvalue (Entity, FieldName, fieldvalues);
}

}

} catch (Exception e) {
E.printstacktrace ();
}finally {
Close (Connection,preparedstatement,resultset);
}
return entity;
}
Test Gett () method
@Test
public void Testgett () throws exception{
String sql= "Select Id,name,email,birth from Customer where id=?";
Customer Customer=gett (customer.class,sql,2);
SYSTEM.OUT.PRINTLN (customer);

String sql1= "Select flow_id flowid,type,id_card idcard,"
+ "Exam_card examcard,student_name studentname,"
+ "Localtion,grade from Test WHERE flow_id=?;";
Student Student=gett (student.class,sql1,2);
SYSTEM.OUT.PRINTLN (student);
}
=======================================================================================
Resultsetmetadate is a metadata object that describes the resultset, that is, how many columns are available in the result set, and the column name is ....
Usage: Call ResultSet's Getmetadate () method,
Useful method: Int getColumnCount (), the SQL statement contains those columns
String getcolumnlabel (int column): Gets the alias of the specified column, where the index starts at 1

public void Testresultsetmetadate () throws exception{
Connection Connection=null;
PreparedStatement Preparedstatement=null;
ResultSet Resultset=null;

try {
String sql= "Select flow_id flowid,type,id_card idcard,"
+ "Exam_card examcard,student_name studentname,"
+ "Localtion,grade from Test WHERE flow_id=?;";
Connection=testpreparedstatement.getconnection ();
Preparedstatement=connection.preparestatement (SQL);
Preparedstatement.setint (1, 2);
Resultset=preparedstatement.executequery ();

Map<string, object> values=new hashmap<string, object> ();

1. Get the Resultsetmetadate object, get the columns column name in the database
ResultSetMetaData rsmd= (ResultSetMetaData) resultset.getmetadata ();
while (Resultset.next ()) {
2. {} print column names for each column
for (int i=0;i<rsmd.getcolumncount (); i++) {
String Columnlabel=rsmd.getcolumnlabel (i+1);//Gets the alias of the specified column
Object Columnvalue=resultset.getobject (ColumnLabel);//Gets the value of the specified column

Values.put (ColumnLabel, Columnvalue);

}
}
System.out.println (values);

Reflection acquisition
Class Clazz=student.class;
Object obj=clazz.newinstance ();
Force for Loop
For (map.entry<string, object> entry:values.entrySet ()) {
String Fieldname=entry.getkey ();
Object Fieldvalues=entry.getvalue ();
System.out.println (fieldname+ ":" +fieldvalues);
}


} catch (Exception e) {
E.printstacktrace ();
}finally {
Close (Connection,preparedstatement,resultset);
}
}

}

Database pictures:

Using reflection and JDBC meta-data to implement common Query method

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.