DAO模型设计实现数据的 增,删,改,查方法
连接数据库方法,及反射获取数据,以前的方法相同,测试类 是在DAO模型下建立的
--------------------------------------------------------------
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 + "]";
}
}
------------------------------------------------------------------------
ReflectionUtils类,实现反射方法:
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 static org.junit.Assert.fail;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Date;
import java.sql.Driver;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.junit.Test;
import com.mysql.jdbc.ResultSetMetaData;
/*
* DAO:Date Access Object:数据库访问对象
* 用处:访问数据信息的类,包含了对数据的增删改查操作(insect,delect,update,select);
* 而不包含任何业务相关的信息
* 好处:更容易实现功能的模块化,更容易实现代码的维护和升级
* 使用jdbc编写DAO使用的一些方法,
*
* */
public class TestDAO {
//连接数据库
public Connection getConnection() throws Exception{
//四个必要步骤
String driverClass=null;
String jdbcUrl=null;
String user=null;
String password=null;
InputStream in=
TestDAO.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties=new Properties();
properties.load(in);
driverClass=properties.getProperty("driver");
jdbcUrl=properties.getProperty("jdbcUrl");
user=properties.getProperty("user");
password=properties.getProperty("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;
}
//此时getconnection方法
public void testConnection() throws Exception{
System.out.println(getConnection());
}
//实现delect,update,insect功能
public void update(String sql,Object...args) throws Exception{
//Object...args:可变参数,可以当数组使用,不用知道他的大小,直接传就行了
Connection connection=null;
PreparedStatement preparedStatement=null;
try {
connection=getConnection();
preparedStatement=connection.prepareStatement(sql);
for(int i=0;i<args.length;i++){
preparedStatement.setObject(i+1, args[i]);
}
//更新
preparedStatement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally {
TestDAO.close1(connection, preparedStatement);
}
}
//查询一条记录,返回对应的对象
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=getConnection();
preparedStatement=connection.prepareStatement(sql);
for(int i=0;i<args.length;i++){
preparedStatement.setObject(i+1, args[i]);
}
resultSet=preparedStatement.executeQuery();
//ResultSetMetaData可以获得数据库的属性,及其值
ResultSetMetaData rsmd=(ResultSetMetaData) resultSet.getMetaData();
Map <String, Object> values=new HashMap<String, Object>();
while(resultSet.next()){
for(int i=0;i<rsmd.getColumnCount();i++){
String conlumnLabel=rsmd.getColumnLabel(i+1);
Object conlumnValues=resultSet.getObject(conlumnLabel);
values.put(conlumnLabel, conlumnValues);
}
}
if(values.size()>0){
entity=clazz.newInstance();//利用反射获取的数据
//强制for循环
for(Map.Entry<String, Object> entry: values.entrySet()){
String fieldName=entry.getKey();
Object fieldValues=entry.getValue();
System.out.println(fieldName+":"+fieldValues);
ReflectionUtils.setFieldValue(entity, fieldName, fieldValues);
}
}
} catch (Exception e) {
// TODO: handle exception
}finally {
TestDAO.close(connection,preparedStatement,resultSet);
}
return entity;
}
public <T> List<T> getForList(Class<T> clazz,String sql,Object...args){
return null;
}
// public <T> E getForValues(Class<T> clazz,String sql,Object...args){
//
// return null;
// }
//关闭资源方法
public static void close1(Connection connection,PreparedStatement preparedStatement)
throws Exception{
if (preparedStatement!=null) {
preparedStatement.close();
}if (connection!=null) {
connection.close();
}
}
public static 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();
}
}
}
----------------------------------------------------------------
功能的实现类,测试增删改查:
package com.lanqiao.javatest;
import static org.junit.Assert.*;
import java.sql.Date;
import org.junit.Test;
public class DAOTest {
TestDAO dao=new TestDAO();
@Test
//改
public void testUpdate() throws Exception {
String sql="update customer set name='apanpan' where id=?;";
dao.update(sql, 3);
}
//查
@Test
public void testGetT() throws Exception {
String sql="select id,name,email,birth from customer where id=?";
Customer customer=dao.getT(Customer.class, sql, 2);
System.out.println(customer);
}
//增
@Test
public void testInsert() throws Exception {
String sql="insert into customer(id,name,email,birth) values(?,?,?,?);";
dao.update(sql,"3","panpan","aiqiyi",new Date(new java.util.Date().getTime()));
}
//删
@Test
public void testDelect() throws Exception{
String sql="delete from customer where id=?";
dao.update(sql, 2);
}
}
DAO模型设计实现数据的 增,删,改,查方法的更多相关文章
- 好用的SQL TVP~~独家赠送[增-删-改-查]的例子
以前总是追求新东西,发现基础才是最重要的,今年主要的目标是精通SQL查询和SQL性能优化. 本系列主要是针对T-SQL的总结. [T-SQL基础]01.单表查询-几道sql查询题 [T-SQL基础] ...
- iOS FMDB的使用(增,删,改,查,sqlite存取图片)
iOS FMDB的使用(增,删,改,查,sqlite存取图片) 在上一篇博客我对sqlite的基本使用进行了详细介绍... 但是在实际开发中原生使用的频率是很少的... 这篇博客我将会较全面的介绍FM ...
- iOS sqlite3 的基本使用(增 删 改 查)
iOS sqlite3 的基本使用(增 删 改 查) 这篇博客不会讲述太多sql语言,目的重在实现sqlite3的一些基本操作. 例:增 删 改 查 如果想了解更多的sql语言可以利用强大的互联网. ...
- django ajax增 删 改 查
具于django ajax实现增 删 改 查功能 代码示例: 代码: urls.py from django.conf.urls import url from django.contrib impo ...
- ADO.NET 增 删 改 查
ADO.NET:(数据访问技术)就是将C#和MSSQL连接起来的一个纽带 可以通过ADO.NET将内存中的临时数据写入到数据库中 也可以将数据库中的数据提取到内存中供程序调用 ADO.NET所有数据访 ...
- MVC EF 增 删 改 查
using System;using System.Collections.Generic;using System.Linq;using System.Web;//using System.Data ...
- python基础中的四大天王-增-删-改-查
列表-list-[] 输入内存储存容器 发生改变通常直接变化,让我们看看下面列子 增---默认在最后添加 #append()--括号中可以是数字,可以是字符串,可以是元祖,可以是集合,可以是字典 #l ...
- 简单的php数据库操作类代码(增,删,改,查)
这几天准备重新学习,梳理一下知识体系,同时按照功能模块划分做一些东西.所以.mysql的操作成为第一个要点.我写了一个简单的mysql操作类,实现数据的简单的增删改查功能. 数据库操纵基本流程为: 1 ...
- MongoDB增 删 改 查
增 增加单篇文档 > db.stu.insert({sn:'001', name:'lisi'}) WriteResult({ "nInserted" : 1 }) > ...
随机推荐
- javascript异步加载的三种解决方案
默认情况javascript是同步加载的,也就是javascript的加载时阻塞的,后面的元素要等待javascript加载完毕后才能进行再加载,对于一些意义不是很大的javascript,如果放在页 ...
- 遍历Map集合的方法
创建一个MAP的栗子: Map<String, Integer> tempMap = new HashMap<String, Integer>(); tempMap.put(& ...
- Geek version acm pc^2 direction for user
gogogogogogogogogogogogogogogogogogogogogogogogogogogogogogogogogogogogogogogogogogogogogogogogogogo ...
- tostring() 作用
tostring() 作用 -->显示类中属性的值 -->不想显示该类的内存地址
- css样式重写
//我们经常想修改插件的某一个或几个样式特性,并保留其它的样式.而不是把某个css全部重写一遍. /*原有样式*/.ninew {padding: 0 10px;width: 600px;height ...
- linux时钟同步
方法1. ntpdate ip 搜索时钟服务器.找一个靠谱的时钟ip执行以上命令即可 可以把这个加入crontab中定时同步.# /usr/sbin/ntpdate 210.72.145.44 > ...
- 夺命雷公狗ThinkPHP项目之----企业网站6之栏目的添加(主要用模型来验证字段)
我们刚才的控制器已经写好了,那么我们现在就来完成我们的模型, 首先我们在Model目录下创建一个CategoryModel.class.php 代码如下: <?php namespace Adm ...
- 夺命雷公狗---微信开发17----自定义菜单的事件推送,响应菜单的CLICK
废话不多说,index.php 代码如下所示: <?php /** * wechat php test */ //define your token require_once "com ...
- clock
Prime Time中的clock分析包括: 1)Multiple clocks,clock from port/pin,virtual clock. 2)Clock network delay an ...
- JFreeChart在制作折线图
JFreeChart在制作折线图的时候可以使用两种不同的方式 package Line; import java.awt.Color; import java.awt.Font; import org ...