Javaweb jdbc& Custom Frame/dbutil (15)

Source: Internet
Author: User

Brief introduction

Regarding the code aspect, may in the future blog rarely writes, because I try to reflect the code as the thought out. So that you can review the idea of writing code later. In fact, the code into a post may not have the mind to look down, as the idea came true

Custom Framework 1. Simplify data access layer operations by writing simple custom frameworks
1. Prepare the Environment 1.1 jar package c3p0-0.9.1.2.jar/mysql-connector-java-5.0.8-bin.jar1.2 need to get the data source (used here c3p0 get) c3p0util.java/ The corresponding configuration file C3P0-CONFIG.XML2. Develop a simple framework to simplify DAO operations Dbassist class 1>. The dependency is reduced, where the data source gets passed in by the external, and the member property is received by the construct to assign the private static DataSource ds;public dbassist (DataSource ds) {this.ds = ds;} 3. Because the cud operation is the same, the only difference is the number of parameters, so here you can define a method to Cud operation definition method void update (String sql, object...params) 3.1 Get database connection through data source 3.2 Gets the Execute SQL statement object 3.3 obtains the parameter metadata information through the object Parametermetadata RSMD = Stmt.getparametermetadata (); Gets the number of arguments int count = Rsmd.getparametercount (); 3.4 Determine whether the number of parameters is the same as the OBJS corresponding to the parameter value 1). First, determine if the number of parameters (count) is greater than 02. Determines whether the received parameter is empty or less than 0/again determines whether the received parameter and the number of parameters is equal to 3). Otherwise the match condition is traversed, the parameters are iterated, each parameter is assigned (the value is the received parameter) 3.5 executes the statement stmt.executeupdate (), 3.6 frees the resource c3p0util.release (NULL, STMT, conn), 4. Query result set Definition Method Object query (String sql,resultsethandler rsh, object...params) repeats 3.1-3.4 step 4.5 execution result set stmt.executequery (); 4.6 Turns the result set to object returns 5. Continuation 4.6 Steps to convert the result set to object returns 5.1 to establish the interface Resultsethandler, the result processor this pattern is the policy design pattern, the abstract policy public interface Resultsethandler {Object Handler (ResultSet RS);} 5.2 Establish the corresponding JavaBean class 5.3 for the database to build the beanThe handler class, for cases where the result set has only one record, if the result set has multiple records, returns only the first target type to be encapsulated, needs to be returned by the caller, and the JavaBean field names are consistent and correspond to the database column names. And JavaBean has a default constructor that uses decorations to receive the class to be injected into the private class Clazz;public Beanhandler (class clazz) {This.clazz = Clazz;} 5.4 Methods for converting result sets to Objects Object Handler (ResultSet RS) 1). First create an instance of the class to inject obj = Clazz.newinstance (); 2). Get the meta information of the result set, get the number resultsetmetadata RSMD = Rs.getmetadata () by meta information, int count = Rsmd.getcolumncount (); 3). Traverse each parameter to get the column name and column value string columnName = Rsmd.getcolumnname (i+1); Object columnvalue = Rs.getobject (i+1); The column values are set by reflection into the properties of the injected class field field = Clazz.getdeclaredfield (ColumnName); field.setaccessible (true); Field.set (obj, Columnvalue); 6. Querying all result sets Beanlisthandler and querying a single result set is only different from the need to define a collection of 6.1 definition collections to use as storage for each result set 6.2 difference 1, to modify if to while, which means to traverse each row of data 6.3 Add the result set of each row to the list collection

ORM (Object relational mapping) 1. What is ORM?
ORM (Object/relation Mapping) is the object-relational mapping, the object is the Java object-oriented language, the relationship is a relational database, in fact, it is to map an object into a row of table records, and then map a row of the table records into a Java object. This is the purpose of ORM!
2. What is ORM?
1. Apache Commons dbutils: Very simple JDBC framework, a lot of companies are using it because it is simple and convenient; 2. Hibernate (fully automatic): SSH in the H is it, its hql claims to be object-oriented query language; 3. Ibatis (semi-automatic): simple, Convenient! Many people use "fully automatic" to describe hibernate, then the Ibatis is "semi-automatic". Hibernate encapsulates the relationship-oriented stuff, and even you may not know much about SQL to manipulate the database through hibernate! However, there is a need for us to do some special operations through the relationship-oriented (open encapsulation), then the "semi-automatic" ibatis comes in handy; 4. SPRING-JDBC (Basic and Dbutils are a level, very simple package): The JDBC framework in spring is similar to Dbutils! But spring's IOC has a strong backing for SPRING-JDBC, and Spring's handling of declarative transactions through AOP can be comparable, so the spring JDBC Framework is useful; 5. EJB (Entity Bean) (old): The entity Bean in Java EE, because it is a heavyweight component, is now rarely used.
DBUTILS1 Dbutils Introduction
Dbutils is a member of the Apache Commons component, open source free! Dbutils is a simple package for JDBC, but it is still used by many companies! Dbutils jar Package: Dbutils.jar
2 Dbutils Introduction
Dbutils: Are static methods, a series of Close () methods, Queryrunner: Provide update (), query (), batch () method, Queryrunner query () Method also requires Resultsethandler to map result set 1.  Batch use: public void Testbatch () {object[][] params = new object[10][];for (int i=0; i<params.length; i++) {Params[i] = new Object[]{i, "Web" +i,1000.00f};} try {qr.batch ("insert into T3 values (?,?,?)", params),} catch (SQLException e) {e.printstacktrace ();}} 2. Query commonly used three kinds of use: 2.1 public void Testbeanhandler () {Account A = new account (); a = Qr.query ("select * from T4 where id=?", NE W Beanhandler (A.getclass ()), 1); System.out.println (a);} 2.2 public void Testbeanlisthandler () {list<account> accounts = new arraylist<account> (); accounts = Qr.query ("SELECT * from T4", New Beanlisthandler<account> (Account.class)); SYSTEM.OUT.PRINTLN (accounts);} 2.3 public void TestScalarHandler2 () {int totalrecordes = ((Long) qr.query ("SELECT count (*) from T3", New Scalarhandler () ). Intvalue (); System.out.println (totalrecordes);//Get total number of bars, use} when paging
3 Dbutils and transaction processing
Con.setautocommit (FALSE); --Start con.commit (); --successfully concluded Con.rollback (); --Failure to end the transaction with Dbutil simple use, the following example to deepen understanding, here only for a simple understanding of private queryrunner QR = new Queryrunner (C3p0util.getdatasource ());p ublic void transfor (int sourceacc, int targetacc, float money) {Connection conn = null;try {conn = C3p0util.getconnection (); conn . Setautocommit (false); Qr.update ("Update account set money=money-? Where id=? ", MONEY,SOURCEACC); int i = 1/0;qr.update (" Update account set money=money+? "). Where id=? ", MONEY,TARGETACC); Conn.commit ();} catch (Exception e) {if (conn! = null) {try {conn.rollback ();} catch (SQLException E1) {e1.printstacktrace ();}}}}
4 transaction processing in DAO and service (Implementation of user transfer)
1. Development Prelude 1.1 Guide Package/Get data Source Tool class, interface, no longer repeat 1.2 steps JavaBean class-->accountdaoimpl-->businnesserviceimpl<-->beanfactory <-->transactionmanager2. Establish the Account and Database Account table field information into the mapping relationship private int id;private String name;private float money;3. The data access layer focuses on the implementation class in operational data AccountDaoImpl3.1 use Dbutil to achieve account acquisition and update account functionality 1). Private Queryrunner QR = new Queryrunner (); 2). Account Getaccountbyid (Int. ID)/void Updateaccount (Account ACC) 3). Specify the connection at the time of the query or update to ensure that it is a database connection (you need to use the method in transaction management) 4. The business logic layer focuses on business operations BUSINNESSERVICEIMPL1. Gets the DAO layer object to data manipulation 2. Get the account you want to transfer by name (source and destination account) 3. Operation of the account balance 4. Write to Table Updateaccout () 5. The implementation class of the Proxy business logic layer, realizes the business layer to concentrate on the operation business part, other functions by the proxy object proxy, when uses the business logic class, directly uses the proxy object to be 1. Defines the proxy object 2. Proxy Class 1 is created by Newproxyinstance (ClassLoader, Interfaces, Invocationhandler) in the proxy class in the dynamic proxy. Adopt the appropriate strategy for the business method if ("Transfor". Equals (Method.getname ())) {try {//cut across the transaction to be added Transactionmanager.starttransaction ();// Also known as the pre-notification//To ensure that the original method can execute object retVal = Method.invoke (service, args);//post-notification transactionmanager.starttransaction ();// Finally, do not forget to return the agent's object} catch (Exception e) {e.printstacktrace (); Transactionmanager.rolLback ();//exception Notification}//finally final notification}6. The TransactionManager class, the transaction that was mentioned in the previous step, should be encapsulated into a transaction management class that focuses on the thread local variables deposited by the current thread of the transaction only when the threads fetch value other threads are not fetching 1. Defines a thread local variable that is used to place the connection private static threadlocal<connection> TL = new threadlocal<connection> (); 2. Gets the connection method that sets the connection to the thread local variable 3. StartTransaction ()/rollback ()/commit () Gets the connection first, performing the appropriate operation

Javaweb jdbc& Custom Frame/dbutil (15)

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.