Java uses reflection to make database additions and deletions to check the database

Source: Internet
Author: User
Tags stringbuffer

Currentutil is a paging tool class used when looking up

Interface

Package Com.dao;


Import java.util.List;


Import Com.util.CurrentUtil;


Public interface Basedao<t> {


/**
* @param t
* @return
*@ Author Administrator
*@ Action Database Add
*@ requires the class name to be the same as the database table name, and the field name and type are consistent with the property
*/
public<t> int Add (t t);

/**
* @param t
* @return
*@ Author Administrator
*@ Action Database Modification
*@ require primary key ID plus annotation annotation for isid
*/
public<t> int update (T t);

/**
* @param t
* @return
*@ Author Administrator
*@ Action Delete Data
*@ requires that the primary key ID plus the annotation annotation be isid and the first annotation
*/
public<t> int Delete (t ... t);


/**
* @param cu
* @return
*@ Author Administrator
*@ function to get current page data based on tool class
*/
public<t> list<t> query (Currentutil cu);



/**
* @param t
* @return
*@ Author Administrator
The *@ function simply gets the number of data bars in the table based on the object of the incoming class
*/
public<t> int Querycount (T t);
}







Implementation class


Package Com.dao.impl;
Import Java.lang.reflect.Field;
Import java.sql.Connection;
Import Java.sql.Date;
Import java.sql.PreparedStatement;
Import Java.sql.ResultSet;
Import java.util.ArrayList;
Import java.util.List;
Import Java.util.Map;


Import Com.dao.BaseDao;
Import Com.util.CurrentUtil;
Import Com.util.JdbcUtil;
Import Com.util.JdbcUtil2;

public class Basedaoimpl implements basedao{

Private Connection con;

/** (Non-javadoc)
* @see Com.dao.basedao#add (java.lang.Object)
* Add data
*/
public int Add (Object t) {

PreparedStatement Pre=null;
try{
class<? Extends object> c=t.getclass ();
StringBuffer sb=new StringBuffer ("INSERT into");
String tablename=c.getsimplename ();//Get Class name is table name
Sb.append (tablename+ "(");

Field[] Fields=c.getdeclaredfields ()//Get all property arrays
for (int i = 0; i < fields.length; i++) {
Fields[i].setaccessible (TRUE);
Sb.append (Fields[i].getname ());
if (i!=fields.length-1) {
Sb.append (",");
}
}
Sb.append (") VALUES (");
for (int i = 0; i < fields.length; i++) {
Sb.append ("?");
if (i!=fields.length-1) {
Sb.append (",");
}else{
Sb.append (")");
}
}
Pre = Jdbcutil.getoraclecon (). Preparestatement (Sb.tostring ());
for (int i = 0; i < fields.length; i++) {
Object O=fields[i].get (t);//Get property value
String Type=fields[i].gettype (). Getsimplename ()//Get property type
if ("String". Equals (type)) {
if (o==null) {
Pre.setstring ((i+1), "");
}else{
Pre.setstring ((i+1), o.tostring ());
}
}else if ("int". Equals (type)) {
if (o==null) {
Pre.setint ((i+1), 0);
}else{
Pre.setint (i+1, Integer.parseint (o.tostring ()));
}
}else if ("float". Equals (type)) {
if (o==null) {
Pre.setfloat ((i+1), 0f);
}else{
Pre.setfloat (I+1,float.parsefloat (o.tostring ()));
}
}else if ("Date". Equals (type)) {
if (o==null) {
Pre.setdate ((i+1), new Date (0));
}else{
Pre.setdate (I+1,date.valueof (o.tostring ()));
}
}
}
return Pre.executeupdate ();
}catch (Exception e) {
E.printstacktrace ();
}finally{
Jdbcutil.closecon (NULL, pre, NULL);
}
return 0;
}

/** (Non-javadoc)
* @see Com.dao.basedao#update (java.lang.Object)
* Modify Data
* Requirements must be annotated on the primary key annotation for ISID
*/
public int update (Object t) {
PreparedStatement Pre=null;
try{
class<? Extends object> c=t.getclass (); Load Reflection
StringBuffer sb=new stringbuffer ("Update");
String tablename=c.getsimplename ();//Get Class name is table name
Sb.append (tablename+ "T set");
String id= "";//PRIMARY Key ID
String idvalue= "";//primary Key ID value
String sql= "";
Object Obj=null;
Field[] Fields=c.getdeclaredfields ()//Get Property list
for (int j = 0; J < Fields.length; J + +) {
Fields[j].setaccessible (TRUE);
Obj=fields[j].get (t).//Get Properties
String Type=fields[j].gettype (). Getsimplename ()//Get property type
String tname=fields[j].getname ();//Get Property name
if (obj!=null) {
if (Fields[j].getdeclaredannotations (). length<1| |! " Isid ". Equals (Fields[j].getannotations () [0].annotationtype (). Getsimplename ())) {
if ("String". Equals (type)) {
Sb.append (tname+ "=" "+obj+");
}else if ("Date". Equals (type)) {
Sb.append (tname+ "=to_date" (' +obj+ ', ' yyyy-mm-dd '), ");
}else{
Sb.append (tname+ "=" +obj+ ",");
}
else if ("int". Equals (type)) {
Sb.append (tname+ "=" +obj+ ",");
}else if ("float". Equals (type)) {
Sb.append (tname+ "=" +obj+ ",");
}else if ("Date". Equals (type)) {
Sb.append (tname+ "=" +obj+ ",");
}else if ("Double". Equals (type)) {
Sb.append (tname+ "=" +obj+ ",");
// }
}else{//judgment if there is a note that this is the primary key ID get to the appropriate value for later use
Idvalue=obj.tostring ();
Id=tname;
}
}
}
Sb=new StringBuffer (sb.substring 0,sb.lastindexof (","));
Sb.append ("where T.") +id+ "= '" +idvalue+ "" ");
Sql=sb.tostring ();
Pre=jdbcutil.getoraclecon (). preparestatement (SQL);
return Pre.executeupdate ();
}catch (Exception e) {
E.printstacktrace ();
return 0;
}finally{
Jdbcutil.closecon (NULL, pre, NULL);
}

}


/** (Non-javadoc)
* @see Com.dao.basedao#delete (t[])
* Database deletion
* Primary key ID plus annotation
*/
public int Delete (Object ... t) {
PreparedStatement Pre=null;
try{
class<? Extends object> c=t[0].getclass ();
StringBuffer sb=new stringbuffer ("delete");
String tablename=c.getsimplename ();//Get Class name is table name
Sb.append (tablename+ "t where T.");
String id= "";
String sql= "";
Boolean isfirst=true;
Object Obj=null;
for (int i = 0; i < t.length; i++) {
class<? Extends object> cs=t[i].getclass ();
Field[] Fields=cs.getdeclaredfields ();
for (int j = 0; J < Fields.length; J + +) {
Fields[j].setaccessible (TRUE);
Obj=fields[j].get (T[i]);
if (obj==null) {
Continue
}
if (fields[j].getdeclaredannotations () .length>0&& "Isid". Equals (Fields[j].getannotations () [0]. Annotationtype (). Getsimplename ())) {
Id=fields[j].getname ();
if (Isfirst) {
Sb.append (id+ "in");
Isfirst=false;
}
Sb.append ("'" +obj+ "");
if (i!=t.length-1) {
Sb.append (",");
}else{
Sb.append (")");
}
}

}
}
Sql=sb.tostring ();
Pre=jdbcutil.getoraclecon (). preparestatement (SQL);
return Pre.executeupdate ();
}catch (Exception e) {
E.printstacktrace ();
return 0;
}finally{
Jdbcutil.closecon (NULL, pre, NULL);
}
}


/** (Non-javadoc)
* @see Com.dao.basedao#query (com.util.CurrentUtil)
@ Requires the tool class to have an object property that initializes an objects of the table to query, and returns data for the current page of the table if the object's string property does not have a value
* Default one page to show all
*/
Public list<?> query (Currentutil cu) {
PreparedStatement pre = null;//Define precompiled Statement Object
ResultSet results = null;//Defines a result set object
List list=new ArrayList (); Definition return Collection
String sql= "";
Object obj=cu.t;
try{
Class<?> C=obj.getclass (); Get class object based on class name
String Cname=c.getsimplename (); Gets the abbreviated class name, which is the table name
StringBuffer sb=new stringbuffer ("Select T.*,rownum r from" +cname+ "T where 1=1");
Field[] Fields=c.getdeclaredfields ();
for (int i = 0; i < fields.length; i++) {
Fields[i].setaccessible (TRUE);
Object value=fields[i].get (obj);
String Type=fields[i].gettype (). Getsimplename ()//Get property type
String tname=fields[i].getname ();//Get Property name
if (value!=null) {
if ("String". Equals (type)) {
Sb.append ("and T.") +tname+ "= '" +value+ "" ");
}
}
}
Sb.append (") A Where a.r>=" +cu.startpage+ "and a.r<=" +cu.endpage);
Sql=sb.tostring ();

Pre = Jdbcutil.getoraclecon (). preparestatement (SQL);
Result=pre.executequery ();
while (Result.next ()) {
Object ins=c.newinstance ();
for (int i = 0; i < fields.length; i++) {
String Type=fields[i].gettype (). Getsimplename ()//Get property type
String tname=fields[i].getname ();//Get Property name
if ("String". Equals (type)) {
Fields[i].set (INS, result.getstring (tname));
}else if ("Date". Equals (type)) {
Fields[i].set (INS, result.getdate (tname));
}else if ("int". Equals (type)) {
Fields[i].set (INS, Result.getint (tname));
}else if ("Double". Equals (type)) {
Fields[i].set (INS, result.getdouble (tname));
}else if ("float". Equals (type)) {
Fields[i].set (INS, result.getfloat (tname));
}
}
List.add (INS);
}
}catch (Exception e) {
E.printstacktrace ();
}finally{
Jdbcutil.closecon (NULL, pre, NULL);
}
return list;
}

public int Querycount (Object t) {
PreparedStatement pre = null;//Define precompiled Statement Object
ResultSet results = null;//Defines a result set object
int count = 0;
String sql= "";
Object obj=t;
try{
Class<?> C=obj.getclass (); Get class object based on class name
String Cname=c.getsimplename (); Gets the abbreviated class name, which is the table name
StringBuffer sb=new stringbuffer ("SELECT COUNT (*) Count from" +cname+ "T where 1=1");
A where a.r>=? and a.r<=?
Field[] Fields=c.getdeclaredfields ();
for (int i = 0; i < fields.length; i++) {
Fields[i].setaccessible (TRUE);
Object value=fields[i].get (obj);
String Type=fields[i].gettype (). Getsimplename ()//Get property type
String tname=fields[i].getname ();//Get Property name
if (value!=null) {
if ("String". Equals (type)) {
Sb.append ("and T.") +tname+ "= '" +value+ "" ");
}
else if ("Date". Equals (type)) {
Sb.append (tname+ "=to_date" (' +obj+ ', ' yyyy-mm-dd '), ");
}else{
Sb.append (tname+ "=" +obj+ ",");
// }
}
}
Sql=sb.tostring ();
Pre = Jdbcutil.getoraclecon (). preparestatement (SQL);
Result=pre.executequery ();
while (Result.next ()) {
Count=result.getint ("Count");
}
}catch (Exception e) {
E.printstacktrace ();
}finally{
Jdbcutil.closecon (NULL, pre, NULL);
}
return count;

}

}

Related Article

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.