In-depth Persistence Layer

zhaozj2021-02-16  58

In-depth Persistence Layer

In-depth light-out Persistence Layer (1) from martin blog: http://www.matrix.org.cn/blog/martin/ Scott W. Ambler has written a detailed design papers about ORM PERSISISTENCE LAYER in 1998. According to this design idea, Artem Rudoy developed an open source ORM implementation - PL (Persistence Layer) open source project. I don't know if AMBLER is the pioneer of Orm, but it is certain that Ambler's Object thinks greatly affects the development of ORM tools. The PersistenceBroker design of Apache ObjectRelationalbridge (OJB) is in the same way with Ambler's papers. Today, ORM (Object Relation Mapping) products can be described as a hundred flowers, which are famous: Hibernate, OJB, Torque, Toplink, Castor, and countless lightweight ORM products. Although ORM is so dazzling, it is similar to the principle of low-level, design ideas, all like the same martial art. Hibernate Chinese website long Robbin is said: "No matter what JDO is good, Hibernate is good, COCOBASE is also CASTOR, or what Torque, OJB, software usage and configuration method can be different, but essentially ORM is a lasting layer package for JDBC, so it does not leave its Zong. Let's take a look at the implementation of open source project PL, come to understand the design of Master Ambler, I believe this is a wonderful journey. I. Overview 2. Deepen three. Shallow 1. Overview The following figure shows the persistent layer design summary of AMBLER (AMBLER, 1998B). This design attractive place is that application developers only need to know their objects to persist in their object: PersistentObject, PersistentCriteria class, PersistentTransAction, and Cursor. Other classes are not directly accessed by the application code, but they need to develop and maintain them to support these "public" classes. Class Description: ClassMap mapping classes, encapsulates behaviors that map classes to relational databases, including classes - data tables, class properties - table fields. CURSOR This class encapsulates the concept of the cursor in the database. PersistenceBroker maintains a connection such as a database or text file, and handles communication between the object application and the persistent mechanism. PersistentCriteria This class level encapsulates the behavior required for obtaining, updating, deleting, etc. according to specified conditions. PersistenceMechanism is a class level that encapsulates access methods such as text files, relational databases, object databases. For relational databases, this tree encapsulates complex class libraries, such as Microsoft's ODBC or Java JDBC, which protects your organization from being displaced by these class library. PersistentObject This class encapsulates a single instance persistent behavior, and all business objects that require persistence are derived from here. PersistentTransaction This class encapsulates the simplicity of support for persistent mechanisms and the behavior required for nested transactions. SqlStatement This class level knows how to construct INSERT, UPDATE, DELETE, and SELECT statements based on Classmap objects. The above class represents a concept of consolidation, in other words, each class is only one thing, and it is done very well. This is a good design basis. The PersistentObject encapsulates a single object persistent behavior, while the PersistentCriteria class level packages the behavior that needs to work with a set of lastuing objects.

More resources: Participation Forum Discussion: http://www.mtrix.org.cn/forum.asp More Technical Articles: http://www.matrix.org.cn/Article.aspmatrix Java Portal: http://www.matrix.org.cn Original Address: http://www.matrix.org.cn/Article/851.html Any License Reprinted this article, you must indicate the original address of Matrix in a significant location. And make links to future text, view detailed copyright instructions

In-depth light-out Persistence Layer (2) from martin blog: http://www.matrix.org.cn/blog/martin/ Mainstream Persistence Layer has its own profile, used to store mapping information for the object class and the database. Persistence Layer automatically generates the desired SQL statement and executes the required SQL statement and execute it when performing Save, Delete, Update, Retrieve. This core process is the soul of Persistence Layer, ORM, JDO, and EJBs have no exceptions. In-depth article describe the mapping of PL -> loading -> Generate SQL full process. I. Preparation of two. Map 3. Loading four. Generate one. Prepare 1. Download the PL project to download the open source project PL of Artem Rudoy, ​​which is an ORM implemented according to Scott W. Ambler. Unzip into a path. 2. Install the database to install the MySQL database, it is recommended to use the V3.23 version. Download MySQL JDBC Driver at the same time. Add it to the ClassPath. 3. Creating a test database Create a PLTEST database in the MySQL database, performs test / mysqltest.sql under decompression path, and creates a test data sheet. 4. Modify the database connection attribute to open the test / mysqltest.xml under the decompression path, modify user and password, others constant. II. Map the test / schema.xml under the path to the path is the mapping file of the PL. The following is a fragment of the mapping file: the top layer is the MAP node, and the MAP node contains the Class and Association subtitches. The Class node represents a class, the Class node contains Class-Name, Table-Name, Database-Name, and Attribute sub-nodes. The Association node represents an associated relationship. (Treatment of related information is not deep in-depth, disclose the other text. Loading PL.Test.test is one of the test classes provided by PL, this test class is small but there is a lot of test content, including: 1) Single object and transaction test 2) Test 3) Test of single inheritance 3) Test 4) Test 5) Test 5) Optimacy Lock Test 6) Agent object, agent object condition test ... PL Small, but it is full of five! 1. The read file PL load mapping information is done through the persistencebroker.loadConfig () method. The following is the PL.Test.Test class code public void performtest () {Try {persistenceBroker.getInstance (). Setdebug (true); persistencebroker.getInstance (). Init (); string dir = "D: // Workspace // PersisterLayer // Test // "; // Load Database Information PersistenceBroker.GetInstance (). LoadConfig (New XmlConfigLoader (Dir " MySqltest.xml "); // Load Class - Data Table Map Information PersistenceBroker.getInstance (). LoadingConfig (NEW XMLCONFIGLOADER (Dir "Schema.xml"); Tracking the persistencebroker.loadConfig () method, discovers that it calls the configLoader.loadConfig () method, and configLoader is an interface, and ConxmlConfigLoader is implemented.

Accordingly See XMLConfigLoader.loadConfig Method: public void loadConfig (PersistenceBroker broker) throws PlException {this.broker = broker; try {DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance (); dbf.setValidating (false); DocumentBuilder db = dbf.newDocumentBuilder (); Document document = db.parse (in); Element root = getFirstNamedChildElement (document, "map"); if (root == null) throw new PlException ( "Invalid XML document No map definition found."); Element child = null; // database connection information child = getFirstNamedChildElement (root, "database"); while (! child = null) {pl.sql.RelationalDatabase pm = getRelationalDatabase (child); broker.addRelationalDatabase (pm); child = getNextNamedSiblingElement (child, "database");} // class mapping information acquired child = getFirstNamedChildElement (root, "class"); while (child = null) {ClassMap cm = getClassMap (child);! broker.addClassMap (cm); child = getNextNamedSiblingElement ( Child, "Class"); Base (PM) saves the RelationAlDatabase object in the PersistenceBroker class. The mapping information of the class is similar, first constructed by GetClassMap (Child), then call Broker.AddClassMap (cm) to save the ClassMap object in the PersistenceBroker class. 2. Mapping information in memory View the getClassMap method of XMLConfigLoader, you can see how PL is constructed in memory. The following figure is a diagram of the map: 1) Creating a DatabaseMap for each Database; 2) for each A Table creates a TableMap; TableMap stores associations for DatabaseMap; 3) Creating a columnMap for each table field (Column); COLUMNMAP stores association 4) Creating a classmap for each class; ArrayList AttributeMaps Array Properties List 5) Create an AttributeMap for each class (Attribute); AttributeMap stores associations for ColumnMap. IV. Generating the PL generation SQL statement is completed in two phases, respectively. The first stage is to read mapping information from the mapping file schema.xml from the mapping file, which is generated at this stage.

The second phase is the running phase, acquires actual values ​​(such as query conditions, updated field values, etc.) to generate real running SQL statements from program calls. 1. See PersistenceBroker.addClassMap initialization phase method, as follows, public void addClassMap (ClassMap classMap) throws PlException {classMap.init (); classMaps.put (classMap.getName (), classMap);} It first performs classMap.init () Method, then store ClassMap into the private object of the PersistenceBroker, ClassMaps is a TreeMap. Classmap.init is a very important way, only one ClassMap class only executes. This method initializes the SQL statement for all of this ClassMap. (You can construct all SQL statements to be operated when you read the configuration file? Just like playing magic! Volume? Please think!) We know the operation of a data table with SELECT, INSERT, DELETE, UPDATE four operations, each One operation saves its SQL statement in the PL using the SQLStatement class. A private SQLSTATEMENT object is defined in the ClassMap class. As defined ClassMap class: public class ClassMap {private String name = null; private SqlStatement selectStatement = null; private SqlStatement selectProxyStatement = null; private SqlStatement selectTimestampStatement = null; private SqlStatement insertStatement = null; private SqlStatement deleteStatement = null; private SqlStatement updateStatement = NULL; ClassMap has 6 SQLStatement objects, in addition to crud4 operations, as well as SelectProxyStatement, SELECTTIMESTAMPSTATEMENT (used to implement the last modified record). The init method is used to initialize these SQLStatement objects, which initializes these SQLStateMent objects, and has the basic SQL statement. The following is the init method ClassMap public synchronized void init () throws pl.PlException {// We do not have to init class map twiceif (isInited) return; // Init all statements //// Init SELECT statement // selectStatement = getSelectSql (); // Add 'FROM' and 'WHERE' clauses to the select statementselectStatement.addSqlClause ( ""); selectStatement.addSqlStatement (getFromAndWhereSql ()); now we look at how to get SqlStatement SQL statement. From the above code, you can see that the SQL statement of the SQL statement of SelectStatement has two: getSelectSQL and GetFromandwhereSQL.

The above code is executed to print selectStatement, you can see SQL: select person.id, person.name from person where person.id =? 1. Take the SELECT section below is GetSelectSQL code: public sqlState getselectsql () throws plexception {/ / Create new statementSqlStatement statement = new SqlStatement (); // Add 'SELECT' clause to the select statement statement.addSqlClause ".; // Add clauses for all attributes Do not add (getRelationalDatabase () getClauseStringSelect () ".) " "Before the first attributeboolean isfirst = true; classmap classmap = this; do {for (int i = 0; i 0 || inheritanceassociations.Length ()> 0) {statement.addsqlclause (");"

转载请注明原文地址:https://www.9cbs.com/read-17547.html

New Post(0)