Implementation of an object-oriented Java Bean Query method __java

Source: Internet
Author: User
Tags bulk insert error handling reflection stringbuffer

There is a rush. NET project, consider the package of persistent layer query as far as possible object-oriented, looked at this article, think the author thought well, so want to take to the composition. NET version.

Absrtact: In order to overcome the shortcoming of writing many SQL statements to implement data query in Java Bean method, the object-blocking of the query condition is
, this paper presents an object-oriented query method for Java bean. By setting the query condition object, the query method presented in this paper can
It can effectively improve the development efficiency of the system to realize the data query of different conditions conveniently.
Keywords: reflection mechanism; persistence; Java Bean

Java-based database application development typically incorporates JDBC into different Java beans, implementing database tables to business objects
Mappings to complete access to the database by calling these Java beans. [1, 2] The main flaw in this design approach is that it increases the weight of the work
Reusability, indirectly increased the development workload, the second is to modify and maintain a large amount of work. Using the Java reflection and tagging mechanism, [3] the author proposes a
A support Class (Persister) for Java bean persistence. This paper mainly expounds the design and implementation of object-oriented query method of Persister class.
1 Persistence support class
Add, modify, and delete business data for complex Java bean design problems that simultaneously encapsulate database tables and Operations methods
In addition to, loading, and querying, such as persistent methods are stripped from the Java bean, which is done by the Persistence Class (Persister), the Java Bean is primarily responsible for
The encapsulation of database tables and validation of data legitimacy reduces the complexity of Java bean implementations. The Persister class pairs incoming Java
The Bean's instance object Bean Instance, uses the reflection mechanism to dynamically access its field name and field values, and generates the corresponding SQL language
To implement a query or update operation on a database table by executing a SQL statement, enabling support for Java bean Persistence operations. Persister
The primary field properties and methods of a class are defined as follows.
public class persister{P rivate Connection Connection. public void Insertmany (L ist beanl ist);//Bulk Insert the object in the Bean list into a datasheet pub LIC void Delete (Object bean Instance);//deletes the row public void Deletemany (List beanl ist) corresponding to the bean Instance in the database table; Bulk Delete Row public void Update (object bean Instance) for all bean objects in the Bean list in the database table;//Extract the data in the Bean Instance and update the corresponding record in the database table public void U Pdatemany (List beanl ist);//Bulk Update database table row public Boolean load (object bean Instance) for all bean objects in the bean list;//by Bean Instance the specified primary key value extracts the number from the database table and populates the Bean instance property List <. > Query (Class < > clazz, Conditionholder conditionholder)//query to return the list of objects for Java beans that match the query criteria, Conditionholder encapsulates query criteria String Gettablename (class <? > Beanclass);//return bean corresponding database table name string[] Getidname (class < ? > Beanclass); Returns the primary key field name of the bean's corresponding database table ⋯public persister (Connection Connection) {this. Connection = Connection;}}

2 Design of Query condition class
Define query criteria that are directly determined by field (field), relational operator (operator), query value (value) as individual conditional expression
A complex compound condition expression can be obtained by combining a single conditional expression with, or, or not three different ways. Because of the database field's
The value range is limited, for the "non" operation can always find its corresponding range, so that "non" operation with "not equal" to the equivalent treatment.
Therefore, the conditional combination mode only considers logic "and" and "logic" or "two ways." In order to be able to use simpler expressions to define the search
, the object-oriented encapsulation of individual conditional expression and conditional combination method can be implemented to realize an Object-oriented data query method.
(1) Individual conditional expression class. There are 10 different types of differences by relational operators:
The equal class corresponds to the "field = value" Expression in SQL
NotEqual class corresponds to the "Field < > value" expression in SQL
GreaterThan class corresponds to the "field > value" Expression in SQL
LessThan class corresponds to the "field < value" Expression in SQL
Greaterequal class corresponds to the "Field > = value" expression in SQL
Lessequa class corresponds to the "Field < = value" expression in SQL
IsNull class corresponds to the "field isNull" Expression in sql
The Isnotnull class corresponds to the "field is notnull" expression in sql
L Ike class corresponds to "field like value" Expression in SQL
Notl Ike class corresponds to "field not like value" expression in SQL
(2) Conditional combination method class. Contains two object classes with (and and) and or (or). Responsible for encapsulating individual conditional expressions or composite bars
Pieces of expressions to implement more complex compound condition expressions.
Based on (1), (2), it is easy to implement a description of query condition expressions such as Inl ist (in ...), Between (between ...).
The common feature of a single conditional expression class and a conditional combination method class is to encapsulate the query condition expression and generate the corresponding SQL where
For the generation of the unified SQL WHERE clause interface, the introduction of query conditions Interface class condition:
Public interface Condition {public void GenerateSQL (StringBuffer sbsql, List values);}
The only way to condition the interface class is to generate the corresponding placeholder GenerateSQL based on the query condition expression encapsulated by the object.
The SQL WHERE clause is appended to the Sbsql after the incoming parameter (SQL statement). Add the encapsulated query value to the corresponding argument list at the same time
Values. All individual conditional expression classes and conditional combination mode classes are required to implement condition interface classes. The following are only the L IKE classes and and
Class is described as an example.
2.1 single condition expression class L IKE
Encapsulates the "field like value" string matching criterion and generates the corresponding L IKE condition clause.

public class L Ike imp lements Condition {//Implementation Condition interface p rivate string fieldName;//corresponding field name p rivate String value; /corresponding query value public L ike (string fieldName, String value) {this. fieldName = FieldName; this. value = value; Neratesql (StringBuffer sbsql, List values) {sbsql. Append (fieldName);//Add the query's field name to the SQL WHERE clause sbsql. Append ("Like?") ; Add placeholder values in the WHERE clause of the SQL. Add (value); The query value is added to the corresponding argument list values in}}

2.2 Conditional combination Method class and
Used to encapsulate complex conditional expressions that combine a single condition or a compound conditional expression by "and" Logic, and live
WHERE clause in "(⋯and⋯)" format where "⋯" represents either a single condition or a compound condition expression. The definition is as follows:

Public Classand Imp lements Condition {//Implementation Condition interface P rivate L ist <condition > conditions;//Encapsulate condition columns for single or compound condition expressions   Table public and () {conditions = new ArrayList <condition > ();}   Public and Add (Condition Condition) {conditions. Add (Condition); Add any single or compound conditional expression to the list of conditions public void GenerateSQL (StringBuffer sbsql, L ist values) {sbsql. Append ("("); The WHERE clause in the conditional list generation (⋯and⋯) format is for (int index = 0; index < conditions. Size (); index + +) {conditions. GE T (index).      GenerateSQL (Sbsql, values); if (Index < conditions. Size ()-1) {Sbsql. Append ("and"); else{sbsql. Append (")");}}}

2.3 result set Sort class order
The order class encapsulates the collation of the query result set, supports the combination ordering of the multiple attribute ascending and descending order, and invokes the GenerateSQL generation
The SQL sort clause in the order By⋯ format.

Public Classorder {P Rivate class Entry {public Entry (String fieldName, Boolean isasc) {this. fieldName = Fieldnam E This. ISASC = ISASC;  } String FieldName; Boolean ISASC;   P rivate L ist < Entry > orders;   Public order () {orders = new ArrayList ();}   Public order Addasc (String fieldName) {orders. Add (New Entry (FieldName, true);   Public order Adddesc (String fieldName) {orders. Add (New Entry (FieldName, false);     public void GenerateSQL (StringBuffer sbsql, L ist values) {sbsql. Append ("ORDER by");       for (int index = 0; index < orders. Size (), index + +) {Entry Entry = orders. Get (index); Sbsql.       Append (entry. fieldName); if (entry. isasc) {sbsql. Append ("ASC");       else {sbsql. Append ("desc");} if (Index < orders. Size ()-1) {Sbsql. Append (",");}}}

2.4 Query Container class cond Itionholder
Conditionholder itself is only a query container, the specific query criteria to be added through the Setcondition method to
Conditionholder the instance, and uses the Setcondition method to specify the result set collation. Call GenerateSQL generate where and order
By clause and append the query value to the parameter list values after the passed in parameter (SQL statement) Sbsql.

public class Conditionholder {p rivate Condition Condition;//Specific query condition p rivate order;//result set collation public void Gener Atesql (StringBuffer sbsql, L ist values) {if (condition! = null) {sbsql. Append ("where"); Condition. GenerateSQL (Sbsql, values);   } if (order! = null) {GenerateSQL (sbsql, values); public void Setcondition (Condition Condition) {this. Condition = Condition; public void Setorder (order) {this. order = Order;}}

3 General Query Method implementation
Generates the corresponding where and ORDER BY clause by parsing the query conditions encapsulated in the Conditionholder object. Final Execution class
A SQL statement like "SELECT 3 From⋯where⋯order By⋯", after which the result set is obtained by reading the result set metadata (Metadata of
ResultSet) to automatically generate Java bean processes in reverse, resulting in a list of eligible Java Bean objects. To avoid generating
The implementation complexity of assigning statements to different types of fields, by storing field values in queries
Group values, use the SetObject method of the PreparedStatement interface object (automatic type conversion) to assign values to each parameter. Because the word

The Segment property is P rivate (externally inaccessible), and the Setaccessible (ture) method should be called to set the field property before it can be visited
Q. [4, 5] This article assumes that the Java Bean's properties have the same name as their Encapsulated database table fields.

Public L ist query (Class < > clazz, Conditionholder condition) {⋯stringbuffer sbsql = new StringBuffer (); Store Select SQL statement List values = new ArrayList (); Used to store query value Sbsql.   Append ("Select 3 from" + Gettablename (clazz)); Condition. GenerateSQL (Sbsql, values); Generates a WHERE clause into the sbsql, and the query value is stored in the values array preparedstatement statement = connection.   P Reparestatement (sbsql. toString ()); for (int index = 0; index < values. Size (); index + +) {statement. SetObject (index + 1, values. Get (Index) ) ; Assign values to all placeholder parameters through values} ResultSet rs = statement. ExecuteQuery ();   L ist list = new Arrayl ist (); while (Rs. Next ()) {//Generate a list of Java Bean objects based on the returned dataset ResultSetMetaData meta = Rs. getmetadata ();//Get result set metadata int col Umncount = Meta. getColumnCount (); Object instance = Clazz. Newinstance (); Generates the Java Bean instance for the Clazz class for (int index = 1; Index < = ColumnCount Index + +) {String currentfieldname = meta. getColumnName (Index); The corresponding property of the Java Bean is obtained based on the field name of the result set field Currentfield = Clazz.     Getdeclaredfield (Currentfieldname); Currentfield. Setaccessible (TRUE); //Set property to accessible Currentfield. Set (instance, Rs. getObject (index)); Sets the property value} list based on the field values in the result set. Add (instance);    Add a new object to the Java Bean List} return list; ⋯//Error Handling}

4 Application Examples
As an example of the database table T_book shown in table 1, the corresponding Java bean definition is as follows:
Table 1 table structure design of T_book
Field name segment Type primary key
Book Id VarChar (Y)
Title VarChar (50)
Amount Numeric (6, 0)
P Rice Numeric (6, 2)
...
Import Id; //reference the class package containing the id_annotation definition
Import Table; //reference the class package containing the table_annotation definition
@ Id ({"Book Id"})//Callout database table's primary key field name
@Table ({"T_book"})//Callout database table name

public class Bookbean imp lements serializable{p rivate string book Id; p rivate string title; P rivate Integer amount;   P rivate float P rice; ⋯public Boolean validate Insert (); Legality validation of new data operations ⋯//omit the getters and setters of the property field and other methods}

public class Persistertest {static Connection Connection; static Persister persister;     public static void Main (string[] args) throws excep Tion{⋯persister = new Persister (connection);     Conditionholder holder = new Conditionholder (); Condition C1 = new GreaterThan ("title", "H"); The condition 1 is the title field greater than "h" Condition c2 = new LessThan ("Amount", 10); The Condition 2 is Amount field is less than ten Condition C3 = New and (). Add (C1). Add (C2); Conditions 3 for conditions 1 and Conditions 2 holder. Setcondition (C3); //Set Condition 3 to holder the query condition. Setorder (New Order (). Adddesc ("book Id"); Sets the L ist queryresult = Persister in descending order by book ID field.     Query (Bookbean. class, Holder); Bookbean the corresponding database table according to the condition query, L ist contains the instance object ⋯} of the Eligible Bookbean class

Through the object-oriented encapsulation of query conditions, users do not have to splice the SQL query string, but use the set query condition to
Like to define query conditions, the query operation becomes more natural and convenient. Hibernate, top link and other open source frameworks provide similar work
Can, but are more complex and need external configuration file, so this article's query method is more suitable for small and medium project development.

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.