Open Source components: (4) write a simple ORM map with meta data and beanutils Basedao.java

Source: Internet
Author: User

1. JDBC Meta-data

Available in JDBC: Database metadata, parameter metadata, result set metadata


(1) Database meta-data

The DatabaseMetaData object can be obtained by connection the GetMetaData () method of the object. The DatabaseMetaData object contains meta information for the database.


DatabaseMetaData Java.sql.Connection.getMetaData ()

Retrieves a DatabaseMetaData object that contains metadata about the database. The metadata includes information about the database's tables, its supported SQL grammar, its stored procedures, the CAPAB Ilities of this connection, and so on.



Java.sql.DatabaseMetaData

(1) This interface is implemented by the driver manufacturer, which can get the capabilities of the database.

This interface was implemented by driver vendors to let users know the capabilities of a Database

(2) Different DBMS provides different features, different ways of implementing features, and different data types

Different relational DBMSs often support Different features, implement features in Different ways, and use Different data Types.


GetURL (): Returns a String class object that represents the URL of the database.

GetUserName (): Returns the user name that is connected to the current database management system.

Getdatabaseproductname (): Returns the product name of the database.

Getdatabaseproductversion (): Returns the version number of the database.

Getdrivername (): Returns the name of the driver driver.

Getdriverversion (): Returns the version number of the driver.

IsReadOnly (): Returns a Boolean value that indicates whether the database allows only read operations.



(2) parameter meta-data

Java.sql.ParameterMetaData

An object that can is used to get information about the types and properties for each parameter marker in a Preparedstatem Ent object.


The number of arguments in the PreparedStatement object can be obtained by parametermetadata the GetParameterCount () method of the object.

int Java.sql.ParameterMetaData.getParameterCount ()

Retrieves the number of parameters in the PreparedStatement object.



(3) result set meta-data

The ResultSetMetaData object is obtained through the GetMetaData () method of the ResultSet object.

ResultSetMetaData Java.sql.ResultSet.getMetaData ()

Retrieves the number, types and properties of this ResultSet object ' s columns.



Java.sql.ResultSetMetaData

An object that can is used to get information about the types and properties of the columns in a ResultSet object.



1.1. Database meta-data
Package com.rk.metadata;import java.sql.connection;import java.sql.databasemetadata;import  java.sql.SQLException;import com.rk.utils.JDBCUtil;//1.  database meta-data public class demo01{ Public static void main (String[] args)  throws SQLException{//  Get Connection connection conn = jdbcutil.getconnection ();//  Get database metadata Databasemetadata metadata  = conn.getmetadata ();// alt + shift + l   Quick Get method return value System.out.println ("Databaseproductname:"  + metadata.getdatabaseproductname ());//returns the product name of the database. System.out.println ("Databaseproductversion:"  + metadata.getdatabaseproductversion ());// Returns the version number of the database System.out.println ("drivername:"  + metadata.getdrivername ());// Returns the name of the driver driver System.out.println ("Getdriverversion:"  + metadata.getdriverversion ());// Returns the version number of the driver System.out.println ("URL:"  + metadata.geturl ());//Returns a String class object that represents the URLSystem.out.println of the database ("UserName: " + metadata.getusername ());//Returns the user name that is connected to the current database management system SYSTEM.OUT.PRINTLN (" ReadOnly: " +  Metadata.isreadonly ());//Returns a Boolean value indicating whether the database allows only read operations jdbcutil.closequietly (conn);}}


1.2. Parameter meta-data
Package Com.rk.metadata;import Java.sql.connection;import Java.sql.parametermetadata;import Java.sql.preparedstatement;import Java.sql.sqlexception;import COM.RK.UTILS.JDBCUTIL;//2. Parameter metadata public class Demo02{public static void Main (string[] args) throws sqlexception{//get connection Connection conn = Jdbcutil.getc Onnection ();//SQLString sql = "SELECT * from T_dogs WHERE name=? and Age>? "; PreparedStatement pstmt = conn.preparestatement (sql);//parameter meta-data parametermetadata Parametermetadata = Pstmt.getparametermetadata ();//Gets the number of arguments int count = Parametermetadata.getparametercount (); System.out.println ("Count:" + count); jdbcutil.closequietly (PSTMT); jdbcutil.closequietly (conn);}}


1.3. Result set meta-data
Package com.rk.metadata;import java.sql.connection;import java.sql.preparedstatement;import  java.sql.ResultSet;import java.sql.ResultSetMetaData;import java.sql.SQLException;import  com.rk.utils.jdbcutil;//3.  result set meta data public class demo03{public static void main ( String[] args)  throws SQLException{//  Get connection connection conn =  Jdbcutil.getconnection (); string sql =  "Select * from t_dogs"; Preparedstatement pstmt = conn.preparestatement (SQL); Resultset rs = pstmt.executequery ();//  Get the result set metadata (target: Get the name of the column through the result set metadata) resultsetmetadata  Rs_metadata = rs.getmetadata ();//  iterates over each row result while (Rs.next ()) {// 1.  Gets the number of columns Int count  = rs_metadata.getcolumncount ();// 2.  traversal, gets the name of the column for each column for (int i=0;i<count;i++) {//   Gets the name of the column string columnname = rs_metadata.getcolumnname (i+1);//Gets the column type string Columnclassname = rs_metadata.getcolumnclassname (i+1);//  Gets the value of each column of each row object columnvalue  = rs.getobject (columnName);//  test System.out.print (columnname+ "(" +columnclassname+ ") =" + Columnvalue+ "\ t");} System.out.println ();} jdbcutil.closequietly (RS); jdbcutil.closequietly (PSTMT); jdbcutil.closequietly (conn);}}


2, Basedao.java

Basedao.java

package com.rk.dao;import java.sql.connection;import java.sql.parametermetadata;import  java.sql.preparedstatement;import java.sql.resultset;import java.sql.resultsetmetadata;import  java.sql.sqlexception;import java.util.linkedlist;import java.util.list;import  org.apache.commons.beanutils.beanutils;import com.rk.utils.jdbcutil;public class basedao{/** General method of  *  update  */public void update (string sql,object... paramvalues) { connection conn = null; preparedstatement pstmt = null;try{//  Get Connection conn = jdbcutil.getconnection ();//   Create a stmt object Pstmt = conn.preparestatement (SQL);//  parameter metadata that executes the command:  Gets the number of placeholder parameters Parametermetadata metadata = pstmt.getparametermetadata ();int count =  Metadata.getparametercount ();//  sets the value of the placeholder parameter if (paramvalues != null &&  paramvalues.length>0) {//  loop gives the parameter assignment for (int i=0;i<count;i++) {Pstmt.setobject ((i+1),  paramvalues[i]);}}   Perform update pstmt.executeupdate ();} catch  (sqlexception e) {throw new runtimeexception (e);} finally{jdbcutil.closequietly (PSTMT); jdbcutil.closequietly (conn);}} Common method for/** *  queries  */public <t> list<t> query (String sql,Class<T > clazz, object... paramvalues) {connection conn = null; preparedstatement pstmt = null; resultset rs = null;try{//  the returned collection list<t> list = new linkedlist <T> ();// 1.  get Connection conn = jdbcutil.getconnection ();// 2.  Create stmt object pstmt =  conn.preparestatement (SQL);// 3.  gets the number of placeholder parameters,  and sets the value of each parameter parametermetadata pmd =  pstmt.getparametermetadata (); Int parametercount = pmd.getparametercount (); if (paramValues  != null && paramvalues.length>0) {for (int i=0;i<parametercount;i++) {Pstmt.setobject ((i+1),  paramvalues[i]);}}  4.  Execute Query rs = pstmt.executequery ();// 5.  get result set meta data resultsetmetadata rsmd  = rs.getmetadata ();// --->  gets the number of columns Int columncount = rsmd.getcolumncount ( );// 6.  Traverse Rswhile (Rs.next ()) {//  object to encapsulate T t = clazz.newinstance ();// 7.  Iterate through each column of each row,  encapsulates the data for (int i=0;i<columncount;i++) {//  gets the column name of each column string columnname =  rsmd.getcolumnname (i+1); String name = columnname.substring (0, 1). toLowerCase ()  + columnname.substring (1) ;//  gets the column name of each column,  the corresponding value Object columnvalue = rs.getobject (columnName);//  encapsulation:  Set to the properties of the T object    "Beanutils component" Beanutils.copyproperty (T, name, columnvalue);}   Add the Encapsulated object to the list collection List.add (t);} Return list;} catch  (exception e) {throw new runtimeexception (e);} Finally{jdbcutil.closequietly (RS); jdbcutil.closequietly (PSTMT); jdbcutil.closequietly (conn);}}}

dogdao.java

package com.rk.dao;import java.util.list;import com.rk.entity.doginfo;public class  Dogdao extends basedao{public void save (Doginfo dog) {String sql =  " Insert into t_dogs (Name,age,birthday)  values (?,?,?) "; Super.update (Sql,dog.getname (), Dog.getage (), Dog.getbirthday ()); Public list<doginfo> findall () {string sql =  "Select * from t_ Dogs "; Return super.query (Sql, doginfo.class);} Public doginfo findbyid (int id) {string sql =  "Select * from t_ dogs where id=?  "; List<doginfo> list = super.query (sql, doginfo.class, id);return  (list  != null && list.size () >0)? List.get (0): null;} Public void update (Doginfo dog) {string sql =  "update t_dogs set  Name=?,age=?,birthday=? where id=? "; Super.update (SQl, dog.getname (), Dog.getage (), Dog.getbirthday (), Dog.getid ());} Public void delete (int id) {string sql =  "Delete from t_dogs where  id=? "; Super.update (Sql, id);}}

demo04.java

package com.rk.metadata;import java.util.date;import java.util.list;import  Com.rk.dao.dogdao;import com.rk.entity.doginfo;public class demo04{public static void  main (String[] args) {//save//doginfo d = new doginfo ();//d.setname ("barking");// D.setage (2);//d.setbirthday (New date ());////dogdao dao = new dogdao ();//dao.save (d); /Find All//dogdao dao = new dogdao ();//list<doginfo> list = dao.findall () ;//for (doginfo dog : list)//{//system.out.println (dog);//}//find a specific ID record//dogdao dao =  new dogdao ();//doginfo d = dao.findbyid (1);//system.out.println (d);//Update//DogInfo  d = new doginfo (),//d.setid (1),//d.setname ("Wang Choi"),//d.setage (3);//d.setbirthday (new  Date ());//dogdao dao = new dogdao ();//dao.update (d);//Delete dogdao dao = new  dogdao ();d ao.delete (1);}}


Open Source components: (4) write a simple ORM map with meta data and beanutils Basedao.java

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.