利用反射及jdbc元数据实现通用的查询方法
---------------------------------------------------------------------------------------------------------------------------------------------------------------
1.customer类:
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类:
package com.lanqiao.javatest;
public class Student {
/*
* FlowID:int,流水号
* type:int ,英语四六级
* IDcard:varchar(18),身份证号码
* examcard:varchar(15),考试证号
* studentname:varchar(20),学生姓名
* localtion:varchar(20),区域
* grade:int,成绩
*/
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 + "]";
}
}
-----------------------------------------------------------------------------------------------------------------------------------------------------------
反射方法:
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;
/**
* 反射的 Utils 函数集合
* 提供访问私有变量, 获取泛型类型 Class, 提取集合中元素属性等 Utils 函数
* @author Administrator
*
*/
public class ReflectionUtils {
/**
* 通过反射, 获得定义 Class 时声明的父类的泛型参数的类型
* 如: 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];
}
/**
* 通过反射, 获得 Class 定义中声明的父类的泛型参数类型
* 如: 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);
}
/**
* 循环向上转型, 获取对象的 DeclaredMethod
* @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 不在当前类定义, 继续向上转型
}
//..
}
return null;
}
/**
* 使 filed 变为可访问
* @param field
*/
public static void makeAccessible(Field field){
if(!Modifier.isPublic(field.getModifiers())){
field.setAccessible(true);
}
}
/**
* 循环向上转型, 获取对象的 DeclaredField
* @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 不在当前类定义, 继续向上转型
}
}
return null;
}
/**
* 直接调用对象方法, 而忽略修饰符(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 find method [" + methodName + "] on target [" + object + "]");
}
method.setAccessible(true);
try {
return method.invoke(object, parameters);
} catch(IllegalAccessException e) {
System.out.println("不可能抛出的异常");
}
return null;
}
/**
* 直接设置对象属性值, 忽略 private/protected 修饰符, 也不经过 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("不可能抛出的异常");
}
}
/**
* 直接读取对象的属性值, 忽略 private/protected 修饰符, 也不经过 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("不可能抛出的异常");
}
return result;
}
}
-----------------------------------------------------------------------------------------------------------------------------------------------------------
实现主方法:
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;
/*
* 建立一个统一的方法可以引用任何类的对象,实现数据库数据的处理
* 通过一个对象获取任何一个数据库数据
* */
public class TestPreparedStatement {
private static final Class<Customer> Customer = null;
private static final Class<Student> Student = null;
=================================================================================
//连接数据库方法
public static Connection getConnection() throws Exception{
//四连接数据必不可少的
String driverClass=null;
String jdbcUrl=null;
String user=null;
String password=null;
InputStream in=
TestPreparedStatement.class.getClassLoader().getResourceAsStream("jdbc.properties");
//其中getClass与TestConnection.classh互换使用
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;
}
//测试类
public static void testGetConn() throws Exception{
System.out.println(getConnection());
}
====================================================================================
关闭资源的方法
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类获取数据
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里面的nest()方法,把查询到的数据,student获取
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;
}
========================================================================================
//Customer类获取数据
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里面的nest()方法,把查询到的数据,student获取
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;
}
=======================================================================================
//一个通用的方法的模板:可利用反射,实现数据库查询,插入值
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();
//得到ResultSetMetaDate对象,获取数据库中的列和列名
ResultSetMetaData rsmd=(ResultSetMetaData) resultSet.getMetaData();
//创建一个Map<String,Object>对象,键:sql查询列的别名;值:列的值;
Map<String, Object> values=new HashMap<String, Object>();
//处理结果集,利用ResultSetMetaDate的方法,填充对应的map的对象
while(resultSet.next()){
//方法getColumnCount(),是获取ResultSetMetaDate对象获取数据库属性的个数
for(int i=0;i<rsmd.getColumnCount();i++){
String columnLabel=rsmd.getColumnLabel(i+1);//获取属性,它是字符串
Object columnValues=resultSet.getObject(columnLabel);
// System.out.println(columnValues);
values.put(columnLabel, columnValues);
}
}
//map不为空,利用反射创建clazz的对象
if (values.size()>0) {
entity=clazz.newInstance();
//遍历map,利用反射class对应的对象的属性赋值
for (Map.Entry<String, Object> entry: values.entrySet()) {
String fieldName=entry.getKey();
Object fieldValues=entry.getValue();
System.out.println(fieldName+":"+fieldValues);
//反射获取属性,并修改 xxxx(entity,fieldName,fieldValues);
ReflectionUtils.setFieldValue(entity, fieldName, fieldValues);
}
}
} catch (Exception e) {
e.printStackTrace();
}finally {
close(connection,preparedStatement,resultSet);
}
return entity;
}
//测试getT()方法
@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,是描述ResultSet的元数据对象,即从中可以获取到结果集中有多少列,列名是。。。。。
//用法:调用ResultSet的getMetaDate()方法,
//好用的方法:int getColumnCount(),sql语句中包含那些列
//String getColumnLabel(int column):获取指定列的别名,其中索引从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.得到ResultSetMetaDate对象,获取数据库中的列和列名
ResultSetMetaData rsmd= (ResultSetMetaData) resultSet.getMetaData();
while(resultSet.next()){
//2.{}打印每一列的列名
for(int i=0;i<rsmd.getColumnCount();i++){
String columnLabel=rsmd.getColumnLabel(i+1);//获取指定列的别名
Object columnValue=resultSet.getObject(columnLabel);//获取指定列的值
values.put(columnLabel, columnValue);
}
}
System.out.println(values);
//反射获取
Class clazz=Student.class;
Object obj=clazz.newInstance();
//强制for循环
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);
}
}
}
数据库图片:


利用反射及jdbc元数据实现通用的查询方法的更多相关文章
- Java -- JDBC_利用反射及 JDBC 元数据编写通用的查询方法
先利用 SQL 进行查询,得到结果集: 利用反射创建实体类的对象:创建对象: 获取结果集的列的别名: 再获取结果集的每一列的值, 结合 3 得到一个 Map,键:列的别名,值:列的值: 再利用反射为 ...
- JDBC学习笔记(5)——利用反射及JDBC元数据编写通用的查询方法
JDBC元数据 1)DatabaseMetaData /** * 了解即可:DatabaseMetaData是描述数据库的元数据对象 * 可以由Connection得到 */ 具体的应用代码: @Te ...
- 【转】JDBC学习笔记(5)——利用反射及JDBC元数据编写通用的查询方法
转自:http://www.cnblogs.com/ysw-go/ JDBC元数据 1)DatabaseMetaData /** * 了解即可:DatabaseMetaData是描述数据库的元数据对象 ...
- <五>JDBC_利用反射及JDBC元数据编写通用的查询方法
此类针对javaBean类写了一个通用的查询方法,List<javaBean> 通用查询更新中...:通过学习,深刻体会到学会反射就等于掌握了java基础的半壁江山! 一.使用JDBC驱动 ...
- MYSQL 之 JDBC(六): 增删改查(四)利用反射及JDBC元数据编写通用的查询
1.先利用SQL进行查询,得到结果集2.利用反射创建实体类的对象:创建Student对象3.获取结果集的列的别名:idCard.studentName4.再获取结果集的每一列的值,结合3得到一个Map ...
- JDBC--利用反射及JDBC元数据编写通用的查询方法
1.JDBC元数据(ResuleSetMetaData):描述ResultSet的元数据对象,可以从中获取到结果集中的列数和列名等: --使用ResultSet类的getMetaData()方法获得R ...
- java攻城狮之路--复习JDBC(利用BeanUtils、JDBC元数据编写通用的查询方法;元数据;Blob;事务;批量处理)
1.利用BeanUtils的前提得要加入以下两个jar包: commons-beanutils-1.8.0.jar commons-logging-1.1.1.jar package com.shel ...
- 利用反射和JDBC元数据实现更加通用的查询方法
package com.at221.jdbc; import java.io.IOException; import java.io.InputStream; import java.sql.*; i ...
- 利用反射及JDBC元数据编写通用查询方法
元数据:描述数据的数据,ResultSetMetaData是描述ResultSet的元数据对象,从它可以得到数据集有多少了,每一列的列名... ResultSetMetaData可以通过ResultS ...
随机推荐
- button点击传多个参数
// --------------------button点击传多个参数------------------------ UIButton *btn = [UIButton buttonWithTyp ...
- 连接sql server数据库的两种方式
class DB { private static SqlConnection conn; public static SqlConnection getConn() { //conn = n ...
- 避免硬编码你的PostgreSQL数据库密码
一个密码文件包含了我们需要连接的五个字段,所以我们可以使用文件权限来使密码更安全. host:port:dbname:user:password such as myhost:5432:postgre ...
- Leetcode: Frog Jump
A frog is crossing a river. The river is divided into x units and at each unit there may or may not ...
- [Reprint]c++中typename和class的区别介绍
在c++Template中,很多地方都用到了typename与class这两个关键字,而且好像可以替换,是不是这两个关键字完全一样呢? 相信学习C++的人对class这个关键字都非常明白,clas ...
- 科学计算器的Java实现
简易的科学计算器的实现 ---Java版 import javax.swing.*;//新的窗口组件包 import java.awt.*; import java.awt.event.*; publ ...
- ACdream 1104 瑶瑶想找回文串(SplayTree + Hash + 二分)
Problem Description 刚学完后缀数组求回文串的瑶瑶(tsyao)想到了另一个问题:如果能够对字符串做一些修改,怎么在每次询问时知道以某个字符为中心的最长回文串长度呢?因为瑶瑶整天只知 ...
- php操作oracle的方法类集全
在网上开始找php中操作oracle的方法类~ 果然找到一个用php+oracle制作email表以及插入查询的教程,赶忙点开来看,从头到尾仔细的看了一遍,还没开始操作,便觉得收获很大了.地址在此:h ...
- 07---Net基础加强
第六节复习 泛型和非泛型集合的区别 通常情况下,建议您使用泛型集合,因为这样可以获得类型安全的直接优点而不需要从基集合类型派生并实现类型特定的成员.此外,如果集合元素为值类型,泛型集合类型的性能通常优 ...
- iphone设置铃声
iphone同步铃声 1.下载itunes 2.打开itunes.文件->将文件添加到资料库...选择一首歌曲加进去 3.右击新加的歌曲,显示简介->选项.调整结束开始时间.不得超过40秒 ...