悲しいかな、私は最近長い間何も書いていません。仕事上の理由により、私は会社が開発した基礎となるORMフレームワークと接触しました。 JDBC操作を呼び出すとき、フレームワークは冬眠のSimpleJDBCtemplateを指すことを誤って発見しました。ここでは、大学にいたときに使用した簡単なJDBCカプセル化について考えました。今、私はコードを投稿してあなたと共有します:
構成クラス:同じパッケージの下のデータベース接続構成ファイルを読み取り、一般化の考慮事項に適しています。
パッケージcom.tly.dbutil; import java.io.ioexception; import java.util.properties; public class config {private static properties prop = new Properties(); static {try {// dbconfig.properties configuration file prop.load(config.class.getResourceasStream( "dbconfig.properties")); } catch(ioException e){// todo auto-fenated catch block e.printstacktrace(); }} //定数public static final string class_name = prop.getProperty( "class_name");を設定します。 public static final string database_url = prop.getProperty( "database_url"); public static final string server_ip = prop.getProperty( "server_ip"); public static final string server_port = prop.getProperty( "server_port"); public static final string database_sid = prop.getProperty( "database_sid"); public static final string username = prop.getProperty( "username"); public static final string password = prop.getProperty( "password"); }DBCONFIG.PROPERTIES:データベース構成ファイル、XML形式などを使用することもできます。
class_name = com.mysql.jdbc.driverdatabase_url = jdbc:mysqlserver_ip = localhostserver_port = 3306database_sid = employesusname = rootpassword = 1
次は、データベース接続補助クラスDBConnです
パッケージcom.employees.dbutil; Import java.sql.connection; import java.sql.drivermanager; Import java.sql.preparedStatement; Import java.sql.Resultset; Import java.sql.sqlecception; private reparedStatement pstmt = null;プライベート結果rs = null; // 4つの方法// method1:データベースへの接続を作成しますpublic connection getConntion(){// 1:接続ドライバー、Java反射原理class.forname(config.class_name); // 2:接続インターフェイスオブジェクトを作成して、MySQLデータベースの接続オブジェクトを取得します。 3つのパラメーター:url接続文字列アカウントパスワード文字列url = config.database_url+"://"+config.server_ip+":"+config.server_port+"/"+config.database_sid; conn = drivermanager.getConnection(url、config.username、config.password); } catch(classNotFoundException e){e.printstacktrace(); } catch(sqlexception e){e.printstacktrace(); } return conn; } // method2:データベースを閉じる方法public void closeconn(){if(rs!= null){try {rs.close(); } catch(sqlexception e){e.printstacktrace(); }} if(pstmt!= null){try {pstmt.close(); } catch(sqlexception e){e.printstacktrace(); }} if(conn!= null){try {conn.close(); } catch(sqlexception e){e.printstacktrace(); }}} // method3:メソッドは、ステートメントの追加、削除、変更の送信に特に使用されますpublic intexecother(preated -statement pstmt){try {// 1。ステートメントオブジェクトを使用して、sqlステートメントint riffectedRows = pstmt.executeUpdate()を送信します。 // 2。結果を返した結果を返します。 } catch(sqlexception e){e.printstacktrace(); return -1; }} // method4:クエリステートメントを送信するために特別に使用されますpublic results execquery(preated -statement pstmt){try {// 1。ステートメントオブジェクトを使用して、sqlステートメントrs = pstmt.executequery()を送信します。 // 2。結果を返しますRs; } catch(sqlexception e){e.printstacktrace(); nullを返します。 }}}通常、上記のコードを使用すると、いくつかの単純なCRUDアプリケーションを解決できますが、多くの制限があります。たとえば、プログラムが接続するたびに、システムの負担が増加し、トランザクションもデータソースもありません。今日、公園で友人が庭に記事を書いてリフレクションを使用してオブジェクトパラメーターでCRUDを直接解決しました。私はこれを以前に書いたことがありますが、私はそれを終えていません。私は主に一般的なdbutilを書きたいです。最後に、私はそれを研究し、冬眠のsimplejdbctemplateに近づいていることがわかったので、冬眠のソースコードを見に行きました。さらに、その間にいくつかのことがあり、時間がなかったので、この問題をアイドル状態にしました。今、私はこのことを補い、自分のためにそれをレビューします。
Basedaoクラス
パッケージcom.employees.dao; import java.io.inputstream; import java.lang.reflect.method; import java.lang.Lang.Rang.Rang.Rang.Rang.ParameterizeType; Import java.sql.Connection; Import java.sql.date; Import java.preparedtatement; Importtatement; java.util.arraylist; import java.util.iterator; import java.util.list; import com.employees.dbutil.dbconn; public class Basedao <t> {dbconn conn = new dbconn();プライベート接続接続= null; @suppresswarnings( "unsused")プライベートクラス<t> persistentclass; @suppresswarnings( "unchecked")public basedao(){initconnection(); // parameterized型parameterizedType type =(parameterizedType)getClass()。getGenericSuperClass(); PersistentClass =(class <t>)type.getActualTypearguments()[0]; } / ***データベース接続を取得* / public void initconnection(){connection = conn.getConntion(); } /** * save * /public void save(t entity)スロー例外{// sqlステートメント、挿入テーブル名(string sql = " + entity.getclass()。getsimplename()。tolowercase()。 iter = list.iterator(); sql.substring(0、sql.lastindexof( "、")) +")values("; // stand up precompiled sqlステートメント挿入挿入挿入挿入挿入挿入(id、name、email)values(?、?、for(int j = 0; j <list.size(); j ++){sql += " name(id、name、email)values(?、?、?); // precompiledオブジェクト作成ステートメント= connection.preparestatement(sql)への参照を取得します。 int i = 0; //ポインターをイテレータの最後の行に移動します。 iter = list.iterator(); while(iter.hasnext()){method method = iter.next(); //これは、データベースに保存されたときに一部のフィールド値形式を変更する必要があるため、最初に返品値のタイプを決定します。たとえば、string、sqlステートメントは '"+abc+"' if(method.getReturnType()。getSimplename()。indexof( "string") } else if(method.getReturnType()。getSimplename()。indexof( "date") } else if(method.getReturnType()。getSimplename()。indexof( "inputstream") } else {statement.setint(++ i、this.getint(method、entity)); }} // conn.execother(statement); execute conn.execother; // closeconn(); } / ** *変更 * / public void update(t entity)スロー例外{string sql = "update" + entity.getClass()。getSimplename()。tolowercase() + "set"; //このクラスリストのすべてのメソッドオブジェクトコレクションを取得<メソッド>リスト= this.matchpojomethods(entity、 "get"); //ファッションメソッドオブジェクトの反復を担当する一時的なメソッドオブジェクト。メソッドtempmethod = null; //変更時にIDを変更する必要がないため、パラメーターを順番に追加する必要があるため、IDを最後に移動する必要があります。メソッドidmethod = null; iterator <method> iter = list.iterator(); while(iter.hasnext()){tempmethod = iter.next(); //メソッド名にID文字列が含まれ、長さが2の場合、IDと見なされます。 if(tempmethod.getName()。lastIndexof( "id")!= -1 && tempmethod.getName()。substring(3)。Length()== 2){// IDフィールドのオブジェクトを変数に保存して、コレクションで削除します。 idmethod = tempmethod; iter.remove(); //メソッド名が削除され、セット/get文字列がpojo + "id"(case ofsensentive)と互換性がない場合、それはidと見なされます} else if((entity.getClass()。 iter.remove(); }} //反復ポインターを最初の位置に移動しますiter = list.iterator(); while(iter.hasnext()){tempmethod = iter.next(); sql + = tempmethod.getname()。substring(3).tolowercase() + "=?"; } //最後の1つを削除する、シンボルsql = sql.substring(0、sql.lastindexof( "、")); //条件を追加しますsql + = "where" + idmethod.getName()。substring(3).tolowercase() + "=?"; // SQLスプライシングが完了し、SQLステートメントSystem.out.Println(SQL)を印刷します。 preatedStatementステートメント= this.connection.preparestatement(sql); int i = 0; iter = list.iterator(); while(iter.hasnext()){method method = iter.next(); //これは最初に返品値のタイプを決定します。たとえば、データベースに保存されたときに一部のフィールド値形式を変更する必要があるため、文字列、sqlステートメントは '"+abc+"' if(method.getReturnType()。 } else if(method.getReturnType()。getSimplename()。indexof( "date") } else if(method.getReturnType()。getSimplename()。indexof( "date") } else if(method.getReturnType()。getSimplename()。indexof( "inputstream") } else {statement.setint(++ i、this.getint(method、entity)); }} // idフィールドに値を追加if(idmethod.getReturnType()。getSimplename()。indexof( "string")!= -1){statement.setString(++ i、this.getString(idmethod、entity)); } else {statement.setint(++ i、this.getint(idmethod、entity)); } // sql statement.executeupdate()を実行します。 // Precompiled Object Statement.Close()を閉じます。 // connection.close()を閉じます。 } / ** delete * / public void delete(t entity)throws excection {string sql = "delete from" + entity.getClass()。getSimplename()。tolowercase() + "where"; //文字列「ID」メソッドIDMethod = nullでフィールドオブジェクトを保存します。 // string "id" list <method> list = this.matchpojomethods(entity、 "get")でフィールドオブジェクトを取得します。 iterator <method> iter = list.iterator(); while(iter.hasnext()){method tempmethod = iter.next(); //メソッド名にID文字列が含まれ、長さが2の場合、IDと見なされます。 if(tempmethod.getName()。lastIndexof( "id")!= -1 && tempmethod.getName()。substring(3).length()== 2){// idフィールドのオブジェクトを変数に保存し、セットで削除します。 idmethod = tempmethod; iter.remove(); //メソッド名が削除され、SET/GET文字列がpojo + "id"(case ofsensentive)と互換性がない場合、それはidと見なされます。 iter.remove(); }} sql + = idmethod.getname()。substring(3).tolowercase() + "=?"; preatedStatementステートメント= this.connection.preparestatement(sql); // IDフィールドに値を追加int i = 0; if(idmethod.getReturnType()。getSimplename()。indexof( "string") } else {statement.setint(++ i、this.getint(idmethod、entity)); } // conn.execotherを実行する(statement); // closeconn(); } / *** query by id* / public t findbyid(object object)throws exception {string sql = "select* from" + persistentclass.getSimplename()。tolowercase() + "where"; //サブクラスのコンストラクターを使用して、パラメーター化されたタイプの特定のタイプを取得します。たとえば、Basedao <t>、つまり、特定のタイプのt entity = persistentclass.newinstance()を取得します。 // pojoの主キー(または操作中のテーブル)を保存するメソッドオブジェクトを保存idmethod = null;リスト<メソッド> list = this.matchpojomethods(entity、 "set"); iterator <method> iter = list.iterator(); //フィルターメソッドオブジェクトを取得するwhile(iter.hasnext()){method tempmethod = iter.next(); if(tempmethod.getName()。indexof( "id")!= -1 && tempmethod.getName()。substring(3).length()== 2){idmethod = tempmethod; } else if((entity.getClass()。getSimplename() + "id")。equalsignorecase(tempmethod.getName()。substring(3))){idmethod = tempmethod; }} //最初の文字は小文字に変換されますsql += idmethod.getname()。substring(3,4).tolowercase() +idmethod.getName()。サブストリング(4) +"=?"; //カプセル化ステートメントの後、SQLステートメントSystem.out.Println(SQL)を印刷します。 //接続を取得済みステートメントステートメント= this.connection.preparestatement(sql); // idのタイプを判断するif(object instanceof integer){statement.setint(1、(integer)object); } else if(object instanceof string){statement.setString(1、(string)object); } // sqlを実行してクエリ結果セットを取得します。 resultet rs = conn.execquery(ステートメント); //登録すると、ループを記録しますint i = 0; // iterator iter = list.iterator()の最初の行にポインターを指します。 //(rs.next()){while(iter.hasnext()){method method = iter.next(); if(method.getParametertypes()[0] .getSimplename()。indexof( "string")!= -1){// 名前。 this.setString(method、entity、rs.getString(method.getName()。substring(3).tolowercase())); } else if(method.getParametertypes()[0] .getSimplename()。indexof( "date")!= -1){this.setDate(method、entity、rs.getDate(method.getName()。 } else if(method.getParametertypes()[0] .getSimplename()。indexof( "inputstream") } else {this.setint(method、entity、rs.getint(method.getname()。substring(3).tolowercase())); }}} //結果を閉じるrs.close(); // Precompiled Object Statement.Close()を閉じます。リターンエンティティ。 } /***現在のpojoクラスに着信文字列を持つすべてのメソッドオブジェクトをフィルタリングし、リストコレクションを返します。 */private list <method> matchpojomethods(t entity、string methodname){//すべての現在のpojoメソッドオブジェクトを取得します[] methods = entity.getclass()。getDeclaredMethods(); // container storts get string list <method> list = new arraylist <method>()を備えたすべてのメソッドオブジェクトをリストします。 //現在のpojoクラスでget文字列ですべてのメソッドオブジェクトをフィルタリングし、(int index = 0; index <methods.length; index ++){if(methods [index] .getname()。indexoname()。indexname)!= -1){list.add(methods [index]); }} return list; } /***このメソッドは、型がintまたは整数であるときにSQLステートメント値を返します。 get */ public Integer getInt(Method Method、t Entity)をexception {return(integer)method.invoke(entity、new object {] {}); } /***このメソッドは、型が文字列の場合にSQLステートメントアセンブリ値を返します。たとえば、「ABC」、Get */ public String getString(Method Method、t entity)をexception {return(string)method.invoke(entity、new object [] {}); } /***メソッドは、BLOBのタイプのときにSQLステートメントのアセンブルされた値を返します。 get */ public inputStream getBlob(メソッドメソッド、tエンティティ)を取得することに対応します。 } / ** *メソッドは、get * / public date getDate(メソッドメソッド、t entity)を取得することに対応する日付のタイプがexception {return(date)method.invoke(entity、new object [] {})をスローするときにSQLステートメントのアセンブルされた値を返します。 } / ** *パラメータータイプが整数またはintの場合、set * / public integer setint(メソッドメソッド、tエンティティ、整数arg)に対応するエンティティフィールドのパラメーターを設定します。 } / ** *パラメータータイプが文字列である場合、エンティティフィールドの設定パラメーター、SET * / public String SetString(Method Method、T Entity、String arg)に対応します。 } / ** *パラメータータイプがinputStreamの場合、エンティティフィールドの設定パラメーター、set * / public inputstream setblob(method method、t entity、inputstream arg)に対応します。 } / ** *パラメータータイプが日付の場合、エンティティフィールドの設定パラメーター、SET * / public Date SetDate(Method Method、t Entity、date arg)に対応します。 }}EmployeingDaoはBeadyaoを継承し、親クラスの方法を直接使用して、コードの再利用を追加できます
パッケージcom.employees.dao; Import java.util.arraylist; Import java.util.list; import com.employees.po.employees; public class employesdao extendsao extends basedao <Employees> {//従業員情報の追加パブリックブールンアドフォーポリー担当者(最終従業員)の操作は例外(従業員); trueを返します。 } //従業員情報をテーブルに追加するパブリックリスト<従業員> addemployees(int id)throws exception {list <employess> lstumploplyees = new arraylist <employeps>();従業員の従業員= FindByID(ID); //現在囲まれているデータをObject Lystemployees.Add(従業員)にロードします。 lystemplopilysを返します。 } public void deleteemp(最終従業員エンティティ)スロー例外{this.delete(entity); } public void updateEmp(最終従業員エンティティ)スロー例外{this.update(entity); }}POレイヤーのコードを投稿しませんが、Junit4を使用してテストを行います
パッケージcom.employees.dao; import org.junit.test; import com.employees.po.employees; public class employesdaotest {@test public void testadd()throws exception {employees emp = new Employees(); emp.setpname( "tly"); emp.setpsex( "MALE"); emp.setpbeliefs( "xxxxx"); emp.setpaddr( "tianhe"); emp.setphobby( "Play Basketball"); emp.setpsubject( "Computer"); emp.setptel( "123456"); employesdao dao = new EmployeingDao(); dao.addemployees(emp); } @test public void testupdate()スロー例外{employessdao dao = new EmployeingDao();従業員emp = dao.findbyid(14); emp.setptel( "999999"); dao.updateemp(emp); } @test public void testdelete()スロー例外{employeesdao dao = new EmployeingDao();従業員Emp = dao.findbyid(15); dao.deleteemp(emp); }}テスト後、これらの3つの方法は正常に実行できますが、時間は急いでいます。一部のコードは他の仲間によって使用されます。一部の場所は非常に包括的とは見なされない場合や、一部のコードが冗長になる場合があります。 Beasedaoでの一般的なCRUD操作は完全に書かれていません。友達が興味がある場合は、クエリ、バッチ操作など、再度書くことができます。テストが合格した場合は、コピーを送信することを忘れないでください。
上記のシンプルで一般的なJDBC補助パッケージ(例)は、私があなたと共有するすべてのコンテンツです。参照を提供できることを願っています。wulin.comをもっとサポートできることを願っています。