Similar to a jdbc tool class encapsulated by hibernate for database operations

Source: Internet
Author: User

Package project02_Order_management.util; import java. io. IOException; import java. lang. reflect. field; import java. lang. reflect. invocationTargetException; import java. lang. reflect. method; import java. SQL. connection; import java. SQL. driverManager; import java. SQL. preparedStatement; import java. SQL. resultSet; import java. SQL. SQLException; import java. util. arrayList; import java. util. list; import java. util. properti Es; /*** encapsulate the database-connection/Add/delete/modify/query/** @ author MartinDong ** @ param <T> * data object to be operated */public class BaseDAOUtil <T> {/*** declares the database Connection object */private static connection Connection; /*** declare the preprocessing object */private static PreparedStatement preparedStatement;/*** declare the SQL statement to return the result set object */private static ResultSet resultSet; /*** load the default configuration. properties resource file ** @ return */public static Properties getProperties () {return getPro Perties (null);}/*** load resource file *** @ param propertyName * input the name of the resource file to be loaded; * @ return properties returns a property configuration object */public static Properties getProperties (String propertyName) {/*** sets the default file name of the configuration resource file */if (propertyName = null) {propertyName = "configuration. properties ";}/*** declares the attribute File class, and reads the configuration using */Properties properties = new Properties (); try {/*** currentThread () is a static method of Thread. The returned result is the current process object */properties. load (Thread. cu R0000thread (). getContextClassLoader (). getResourceAsStream (propertyName);} catch (IOException e) {System. out. println (propertyName + "file loading error! "); E. printStackTrace ();} return properties;}/*** get the default database Connection object ** @ return */public static Connection getConnection () {return getConnection (getProperties ();}/*** obtain the database connection object ** @ param properties * to pass in the configured property configuration object; * @ return <B> connection </B> database Connection object */public static connection getConnection (Properties properties) {if (connection = null) {/*** load the database driver file */try {Class. forName (properties. getProperty ("j Dbc. driver ");/*** create a database connection object */try {connection = DriverManager. getConnection (properties. getProperty ("jdbc. url "), properties. getProperty ("jdbc. user "), properties. getProperty ("jdbc. password "); System. out. println ("database connection succeeded >>>>>>>>>>>>");} catch (SQLException e) {System. out. println ("database connection parameter error! "); E. printStackTrace () ;}} catch (ClassNotFoundException e) {System. out. println ("the database driver file is missing:" + properties. getProperty ("jdbc. driver ") + "! "); E. printStackTrace () ;}} return connection;}/*** Method for releasing resources; <br> ** @ param releaseSet * @ param preparedStatement * @ param connection */public static void release (ResultSet releaseSet, PreparedStatement preparedStatement, Connection connection) {if (releaseSet! = Null) {try {releaseSet. close () ;}catch (SQLException e) {e. printStackTrace () ;}} if (preparedStatement! = Null) {try {preparedStatement. close () ;}catch (SQLException e) {e. printStackTrace () ;}} if (connection! = Null) {try {connection. close ();} catch (SQLException e) {e. printStackTrace ();}}} //// // CRUD basic business // /// // *** use the default connection, and the database table name is consistent with the object class name [case insensitive] ** @ param entity * @ throws SQLException * @ throws InvocationTargetException * @ throws IllegalArgumentException * @ throws IllegalAccessException */public void save (T entity) throws IllegalAccessException, Illeg AlArgumentException, InvocationTargetException, SQLException {save (entity, getConnection ();}/*** use the database table name and object class name to [case insensitive] import external database connections; ** @ param entity * @ param connection * @ throws IllegalAccessException * @ throws exceptions * @ throws InvocationTargetException * @ throws SQLException */public void save (T entity, Connection connection) throws limit, illegalArgumentExcept Ion, InvocationTargetException, SQLException {save (entity, connection, null );} /*** Save the object to the database ** @ param entity * The data object to be operated * @ param connection * transfers the name of the table to be operated by the database connection * @ param tableName, if null is input, perform operations on tables with the same names as the input object * @ throws SQLException * @ throws InvocationTargetException * @ throws IllegalArgumentException * @ throws IllegalAccessException */public void save (T entity, connection connection, String tableNa Me) throws SQLException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {/*** obtain the type of the operation entity */Class <? Extends Object> clazz = entity. getClass ();/*** obtain all public methods of the input object; */Method [] methods = clazz. getDeclaredMethods ();/*** get all the public attributes in the input object */Field [] fields = clazz. getDeclaredFields ();/*** use the class name if the specified data table name is not input */if (tableName = null) {tableName = clazz. getSimpleName (). toLowerCase ();}/*** attribute field in the splicing class, that is, the field name in the data table */String fieldsName = ""; /*** placeholder settings */String placeholder = ""; for (int I = 0; I <fields. Length; I ++) {fieldsName = fieldsName + fields [I]. getName () + ","; placeholder = placeholder + "? "+", ";}/*** Remove unnecessary punctuation points */fieldsName = fieldsName. substring (0, fieldsName. length ()-1); placeholder = placeholder. substring (0, placeholder. length ()-1);/*** concatenate an SQL statement */String SQL = "insert into" + tableName + "(" + fieldsName + ") "+" values "+" ("+ placeholder +") "; System. out. println (SQL);/*** precompiled SQL statement */PreparedStatement pst = connection. prepareStatement (SQL);/*** assign a value to the pre-compiled statement */int index = 1; f Or (int j = 0; j <fields. length; j ++) {String str = "get" + fields [j]. getName ();/*** compare the cyclic method name */for (int k = 0; k <methods. length; k ++) {/*** if the get method name spelled out by the current attribute is the same as that in the method description set */if (str. equalsIgnoreCase (methods [k]. getName () {/*** receives the data after the specified method is executed */Object propertyObj = methods [k]. invoke (entity);/*** assign a value to the specified placeholder */pst. setObject (index ++, propertyObj) ;}}/ *** run the loaded SQL statement */pst.exe cuteUpdate ();}/* ** Use the default database connection for deletion, the passed object ** @ param entity * @ throws IllegalAccessException * @ throws exception * @ throws InvocationTargetException * @ throws SQLException */public void delete (T entity) throws entity, entity, InvocationTargetException, SQLException {deleteById (entity, getConnection ();}/*** use the input database connection to delete the specified object. ** @ param entity * @ param connection * @ Throws interval * @ throws InvocationTargetException * @ throws SQLException */public void deleteById (T entity, Connection connection) throws interval, interval, InvocationTargetException, SQLException {delete (entity, connection, null);}/***** @ param entity * object of the input operation * @ param connection * object of the input database connection * @ param id * Id * @ param tableName * Name of the table to be operated. If null is input, perform operations on tables with the same names as the input object * @ throws SQLException * @ throws InvocationTargetException * @ throws IllegalArgumentException * @ throws IllegalAccessException **/public void delete (T entity, Connection connection, string tableName) throws SQLException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {Class <? Extends Object> clazz = entity. getClass (); Method [] methods = clazz. getDeclaredMethods (); Field [] fields = clazz. getDeclaredFields (); if (tableName = null) {tableName = clazz. getSimpleName (). toLowerCase ();} String SQL = "delete from" + tableName + "where id =? "; System. out. println (SQL); PreparedStatement pst = connection. prepareStatement (SQL); Object id = null; for (int I = 0; I <fields. length; I ++) {for (int j = 0; j <methods. length; j ++) {if ("getId ". equalsIgnoreCase (methods [j]. getName () {id = methods [j]. invoke (entity) ;}} pst. setObject (1, id1_1_pst.exe cuteUpdate ();}/*** use the default database connection to modify the input object. ** @ param entity * @ throws IllegalAccessException * @ throws Ill Optional * @ throws InvocationTargetException * @ throws SQLException */public void update (T entity) throws IllegalAccessException, expiration, InvocationTargetException, SQLException {update (entity, getConnection ());} /*** use the input database connection to modify the database. ** @ param entity * @ param connection * @ throws IllegalAccessException * @ throws IllegalArgumentException * @ throws InvocationTargetE Xception * @ throws SQLException */public void update (T entity, Connection connection) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, SQLException {update (entity, connection, null );} /***** @ param entity * object entity for the input operation * @ param connection * Name of the table to be operated when the input database connection object * @ param tableName * is null, perform operations on tables with the same names as the input object * @ throws InvocationTargetException * @ throws IllegalArgument Exception * @ throws IllegalAccessException * @ throws SQLException */public void update (T entity, Connection connection, String tableName) throws IllegalAccessException, expiration, InvocationTargetException, SQLException {Class <? Extends Object> clazz = entity. getClass (); Method [] methods = clazz. getDeclaredMethods (); Field [] fields = clazz. getDeclaredFields (); if (tableName = null) {tableName = clazz. getSimpleName (). toLowerCase ();} String fieldsName = ""; // create the default data Object id of the id field = 1; // obtain the public attribute for (int I = 0; I <fields. length; I ++) {// nested loop, compares public attribute names with public method names after splicing for (int j = 0; j <methods. length; j ++) {// use attribute name + get for spelling String getFieldName = "get" + fields [I]. getName (); if (getFieldName. equalsIgnoreCase (methods [j]. getName () {// concatenate the set field in a more SQL statement and use the placeholder fieldsName = fieldsName + fields [I]. getName () + "= ?, ";} // Obtain the value of the id field if (" getId ". equalsIgnoreCase (methods [j]. getName () {id = methods [j]. invoke (entity) ;}} fieldsName = fieldsName. substring (0, fieldsName. length ()-1); String SQL = "update" + tableName + "set" + fieldsName + "where id =? "; System. out. println (SQL); PreparedStatement pst = connection. prepareStatement (SQL); int index = 1; for (int j = 0; j <fields. length; j ++) {String str = "get" + fields [j]. getName (); // compare the names of cyclic methods for (int k = 0; k <methods. length; k ++) {// if the get Method Name of the current attribute is spelled out, the execution of if (str. equalsIgnoreCase (methods [k]. getName () {// receives the Data Object propertyObj = methods [k] after the specified method is executed. invoke (entity); // assign a value to pst for the specified placeholder. setObj Ect (index ++, propertyObj) ;}} pst. setObject (index ++, id1_1_pst.exe cute ();} /*** use the default database connection to query the specified id data ** @ param entity * @ param id * @ return * @ throws InstantiationException * @ throws IllegalAccessException * @ throws IllegalArgumentException *@ throws InvocationTargetException * @ throws SQLException */public T findById (T entity, integer id) throws InstantiationException, IllegalAccessException, Illegal ArgumentException, InvocationTargetException, SQLException {return findById (entity, null, id);}/***** query data using the input database connection and input id; ** @ param entity * @ param connection * @ param id * @ return * @ throws InstantiationException * @ throws IllegalAccessException * @ throws IllegalArgumentException * @ throws InvocationTargetException * @ throws SQLException */public T findById (T entity, connection connection, In Teger id) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SQLException {return findById (entity, connection, id, null );} /***** query data by id ** @ param entity * the object to be queried * @ param connection * database connection object * @ param id * The queried id * @ param tableName * the database table name of the operation * @ return returns a query result object * @ throws SQLException * @ throws InstantiationException * @ throws IllegalAcce SsException * @ throws syntax * @ throws InvocationTargetException */public T findById (T entity, Connection connection, Integer id, String tableName) throws SQLException, InstantiationException, IllegalAccessException, conflict, invocationTargetException {Class <? Extends Object> clazz = entity. getClass (); Method [] methods = clazz. getDeclaredMethods (); Field [] fields = clazz. getDeclaredFields (); // declare the query result object T resultObject = null; if (tableName = null) {tableName = clazz. getSimpleName (). toLowerCase ();} String SQL = "select * from" + tableName + "where id =? "; System. out. println (SQL); PreparedStatement pst = connection. prepareStatement (SQL); pst. setObject (1, id); ResultSet resultSet = pst.exe cuteQuery (); if (resultSet. next () {resultObject = (T) clazz. newInstance (); for (int I = 0; I <fields. length; I ++) {String fieldName = fields [I]. getName (); Object fieldObject = resultSet. getObject (I + 1); if (fieldObject = null) {fieldObject = "null"; // prevent null pointer exceptions when data is null Constant} for (int j = 0; j <methods. length; j ++) {if ("set" + fieldName ). equalsIgnoreCase (methods [j]. getName () {methods [j]. invoke (resultObject, resultSet. getObject (fieldName) ;}}} return resultObject ;} /*** use the default database connection for Data Query ** @ param entity * @ return * @ throws InstantiationException * @ throws IllegalAccessException * @ throws IllegalArgumentException * @ throws InvocationTargetException * @ throws SQLEx Ception */public List <T> findAll (T entity) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SQLException {return findAll (entity, getConnection ());} /*** use the input database connection for Data Query ** @ param entity * @ param connection * @ return * @ throws InstantiationException * @ throws IllegalAccessException * @ throws IllegalArgumentException * @ throws InvocationTarg EtException * @ throws SQLException */public List <T> findAll (T entity, Connection connection) throws InstantiationException, IllegalAccessException, exceptions, InvocationTargetException, SQLException {return findAll (entity, connection, null );} /*** query all data in the data table ** @ param entity * the object to be queried * @ param connection * database connection object * @ param tableName * The Name Of The database table for the operation * @ return * @ throws SQLException * @ thro Ws IllegalAccessException * @ throws InstantiationException * @ throws InvocationTargetException * @ throws IllegalArgumentException */public List <T> findAll (T entity, Connection connection, String tableName) throws SQLException, InstantiationException, IllegalAccessException, illegalArgumentException, InvocationTargetException {Class <? Extends Object> clazz = entity. getClass (); Method [] methods = clazz. getDeclaredMethods (); Field [] fields = clazz. getDeclaredFields (); // declare the query result object List <T> resultObjects = new ArrayList <T> (); if (tableName = null) {tableName = clazz. getSimpleName (). toLowerCase ();} String SQL = "select * from" + tableName; System. out. println (SQL); PreparedStatement pst = connection. prepareStatement (SQL); ResultSet resultSe T = pst.exe cuteQuery (); while (resultSet. next () {T resultObject = (T) clazz. newInstance (); for (int I = 0; I <fields. length; I ++) {String fieldName = fields [I]. getName (); Object fieldObject = resultSet. getObject (I + 1); if (fieldObject = null) {fieldObject = "null" ;}for (int j = 0; j <methods. length; j ++) {if ("set" + fieldName ). equalsIgnoreCase (methods [j]. getName () {methods [j]. invoke (resultObj Ect, resultSet. getObject (fieldName) ;}}} resultObjects. add (resultObject);} return resultObjects;} public List <T> query (T entity, Connection connection, String tableName, String SQL) {return null ;} /*** you need to manually enter SQL and parameter statements: add/delete/modify/operate ** @ param SQL * @ param args * @ return */public static int upDate (String SQL, Object [] args) {try {preparedStatement = getConnection (). prepareStatement (SQL); for (int I = 1; I <= args. length; I ++) {preparedStatement. setObject (I, args [I-1]);} return preparedStatement.exe cuteUpdate ();} catch (SQLException e) {// TODO Auto-generated catch blocke. printStackTrace ();} return 0;}/*** input custom SQL statements and parameters for query; ** @ param SQL * SQL statement * @ param args * input parameter condition * @ return returns a set */public static ResultSet getObject (String SQL, Object [] args) {System. out. println (SQL); try {preparedState Ment = JDBCUtil. getConnection (). prepareStatement (SQL); if (args! = Null) {for (int I = 1; I <= args. length; I ++) {preparedStatement. setObject (I, args [I-1]) ;}} resultSet = preparedStatement.exe cuteQuery () ;} catch (SQLException e) {// TODO Auto-generated catch blocke. printStackTrace ();} return resultSet ;}}


Configuration. properties configuration file

jdbc.url=jdbc\:mysql\://localhost\:3306/order_managerjdbc.user=rootjdbc.password=adminjdbc.driver=com.mysql.jdbc.Driver


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.