What are the help of JDO to development - an example analysis

zhaozj2021-02-17  41

What are the help of JDO to development - an example analysis

(The copyright of this article is author himself, welcome to reprint, but must indicate the source and original authorities) 1 Interpretation: the business development group and the database management team, the development team is logically divided into two: business development Group and Database Management Groups. The two have characteristics, each is responsible, but the boundaries between each other are very clear, there will be no entanglement. The following table shows the difference between the two: Personnel constitute a business development group system analyst, programmer. Database management group DBA, run maintenance personnel. Generally, one to two can, and can design data class diagrams across multiple project work content business development groups, design business logic interfaces and use code implementation (generally in the similar sessionBean class) Database management group through data class map mapping data Table, generally simply adjust the desired knowledge and tool business development group UML, Java, JSP, Ant on the table structure automatically generated by JDO. Tools can be any IDE. Database Management Group JDO Principle, class diagram in UML, connection pool configuration. Tools include PowerDesigner, Database Access tools, some of the specific Details of the JDO products, are responsible for each other. LT; BR> business development group submits the UML entity class diagram of the data section, and some details (if a property is A long string). After the other party is configured, the PersistenceManagerFactory connection pool is called in the code. The database management group establishes the corresponding database based on the UML class diagram and the business development group to configure the corresponding JDO PersistenceManagerFactory on the server (a J2EE Connector, just like configuring the database connection pool) The business development group is related to the business, because the main code amount is not large in the business logic database management group, but may need some effort when importing data from the old database, but it is a one-time job involving data structure change. When the function change is required, the work business development group is adjusted to the database development group. On the other hand, the business logic code database management group is adjusted according to the new UML physical class map according to the new UML entity class diagram. (Some JDO products can be completed automatically). The server is configured unchanged. Since the work content for the database management group is relatively simple, just the problem, the following introduction does not involve the work of the database management group, and only for the business development group. 2 UML Entity Class Map UML Entity class diagram is part of the project involved in data, which does not lose as the program is subject to sustainable (persistent), and data in all databases can be sustainable. When we are designing, we should analyze which entity classes (ie, sustainable data classes) should be analyzed, thereby drawing entity class diagrams. On this initial class map, it may not contain any properties, but must include the relationship between the entity class, so that the system's approximate contour can be seen. Below is a simple model entity class diagram, a relationship diagram of major entities in a forum. Simply put, the project can be said to be a control class with the interrelated entity class plus the processing business logic, and the boundary of the input / output data, which may additionally add some interfaces or special services, such as SMS / mail or facing Third-party data access interface, etc. With this picture above, DBA is more clear about what kind of data table will have in the database, how to associate between tables. However, the tables in the database are not one by one. For example, a lot of correspondences in the physical class diagram, there must be an additional table in the database, some of some of some of the entities may be placed in another additional table to enhance performance.

The next step is to add an attribute to the physical class based on this picture, then add an access device to each attribute (Accessors, getxxx () / isxxxx (), and setxxx (), etc.), and some must-have methods (such as getage (), Aged by the current date and birthday). In this way, it becomes a complete entity class diagram. The following figure is a physical class diagram added to add ordinary properties. Next, join the accessor method for normal attributes, may add a member.getage () method, this entity class is completed. These processes are relatively simple, and there are many tools that can be done automatically. One thing to focus on, for the entity class, just give this picture, then use the tool to generate the corresponding Java class code, these class code is completed, and will not write code in it later. 3 Transparent storage For developers, main work is concentrated in business logic, which requires some control classes to implement these logic. These control classes can generally name the XXXSession to indicate the control class for a class, such as the MemberSession, complete some of the functions after the member is logged in; Adminssis is used to complete some of the functions after the administrator login. In one of these control classes, you only need to obtain access to the previous entity through the JDO specification interface class (javax.jdo. *) To complete the business function. A typical method is as follows: Method MemberSession keynote posted: public Topic postTopic (String title, String content, String forumId) {// business logic process begins javax.jdo.PersistenceManager pm = getPersistenceManagerFactory () getPersistenceManager (); pm. .currentTransaction (). begin (); // Mr. is a topic, setting basic attribute topic Topic = new Topic (); Topic.SetTitle (Title); Topic.SetContent (Content); Topic.SetPostTime (new date ()) ; // Get the related forum and the current login member // The following this.logonmemberid is the membership ID that must be provided when generated by this MEMBERSESSION object. // This MEMBERSESSION object is usually generated when logging in.

Forum forum = (Forum) pm.getObjectById (pm.newObjectIdInstance (Forum.class, forumId)); Member author = (Member) pm.getObjectById (pm.newObjectIdInstance (Member.class, this.logonMemberId)); // Set the Theme forum and author Topic.Setforum (forum); Topic.Setauthor (Author); // Marking is required to store PM.MakePersistent (Topic); // By the way, change forum and authors forum.Settopiccount (Forum.gettopiccount) () 1); Author.SetPost () 1); // Business logic process complete PM.CurrentTransAction (). Commit (); pm.close ();} This method is over. We can see that as long as the code related to the physical class is placed in the start and submission of PM.CurrentTransaction (). The only middle need to deal with JDO is to call PM.makePersistent (), but in many cases, as long as the object taken out from the PM points to this object (such as: Author.getPosttopics) ) .add (Topic)) If this statement does not need this statement (of course, it is right), because PM will directly or indirectly point to the object that is currently in the database according to the principle of reachability. The newly generated objects are stored. The above code illustrates that we don't have to call the update function for each changeable object, as the JDO PM will automatically track these changes and will synchronize the object that does change to the database. This is "transparent storage." 4 Flexible query: JDOQL vs SQLJDOQL is the query language used in JDO. It is an object-style query language. It is very like OQL, it is also very like EJBQL, but there is no EJBQL that can only static shortcomings. There are many articles in the advantages of object inquiry languages, and there is no longer explained here. Just illustrate: JDOQL is completely based on the UML physical class, does not necessarily pay anything in the specific database. Some examples will be given below to illustrate this flexibility. 4.1: Find all forums in a post, we give the parameters. We give only the author's name, I hope that all him published the subject or reply to the topic forum. We need this JDOQL condition: first query target is fororm class, then JDOQL filter string this == _topic.forum && (_topic.author.name == "<> || _topic.contains (_Repi) && _Reply.author.name == "") Then, the variable used by the declaration: Topic _topic; reply _reply; then execute SQL.

The general JDO product translates this query as: select a. From Forum A, Topic B, Reply C, Member Dwhere A.forum_ID = B. Forum_ID AND (B .MeMber_id = d. MEMBER_ID and D.NAME = '' or b.topic_id = c. Topic_id and c.member_id = D.MEMBER_ID AND D.NAME = '') from above, we can It is seen that JDOQL is far better than SQL in readability or maintainability. We can also use the author's name as a binding parameters, which will be simpler. If you direct SQL directly, you will be very troublesome. On the one hand, pay attention to the properties name in the entity class. On the one hand, pay attention to the corresponding field in the database, because in most cases, the spelling of the two is due to various factors (such as database Keyword conflicts, etc.) will be different. Open from this example, we can further: 4.2 cases: Find all forums in a post, the total number of the total number is greater than 100 and the forums that are incorporated by the author's favorites are very simple, and the filter string is written : This == _topic.forum& (_topic.author == _author || _topic.contains (_reply) && _reply.author ==_author) & _author.name == ' && postcount> 100 &&_author. FavoriteForums.Contains (this) This time you use a variable used: MEMBER _AUTHOR. Its underlying SQL can go to analog yourself. 5 Long strings We often encounter a piece of information that users entered beyond the size of the specified data field, which leads to a troublesome processing, especially some strings that are not necessary to limit the length, such as the content of a topic article. It is possible to take tens of thousand words, which forces us to divide them a lot of sub-records, and record a part of each. All of this makes our code amount, and the maintenance amount is increased. Now has JDO, our code is simple, we may try to use the transparent storage function provided by JDO, through some simple tool classes: principle is to split it into a string string.

package jdo_util; import java.util *;. public class StringHelper {public static List setLongString (String value) {if (value == null) return null; int len ​​= value.length (); int count = (len partSize- 1) / Partsize; list = new arraylist (count); for (int i = 0; i ) and Possible query results are not quite accurate (such as just spanning two substr serial parts). Fortunately, general this query requirement for a long string field is not too much. It should be noted that the use of conventional SQL also requires additional queries on the split string and has the same disadvantage. In addition, this feature requires an optional options in the JDO product support specification: javax.jdo.option.list, the main sever JDO products are supported. For example, Kodojdo and JDogenie.

6 Resources Recycling: PM.Close () When we use traditional SQL write code, the most dangerous is the resource release problem, which is especially important in Web-based applications. Because the resources associated with JDBC are not allocated in the Java virtual machine, the Java garbage collection mechanism is long, causing the system memory to crash slowly. Resources that require proactive releases in JDBC include: Connection, Statement, PreparedState, ResultSet, must release the previous resource when each variable for these types is assigned. It is undoubtedly a cumbersome and easily ignored things. In JDO, things become simpler, all resources are automatically released during PM.Close () (unless JDO products add some Cache for PreparedStatement and ResultSet, this is the requirements for JDO specifications. Therefore, as long as we remember that PM.Close () is called when the physical class is processed. For example, the following code: PersistenceManager PM = NullTry {PM = getPersistenceManagerFactory (). GetPersistenceManager (); // Do some data class processing} Finally {PM.Close ();} Some people may not like to call it, I feel annoying Because every time you have to use a PM, it is turned off when you run out. If the JDO product does not have a PM connection pool, performance may be affected.

Thus, we can use the following succession of tools java.lang.ThreadLocal This is done: public class PersistenceManagerRetriever extends ThreadLocal {/ ** * according to a configuration information acquisition PersistenceManager initializer * @param p * / public PersistenceManagerRetriever (java.util .Properties p) {pmf = JDOHelper.getPersistenceManagerFactory (p);} / ** * Get a related PersistenceManagerFactory * @return PersistenceManagerFactory objects * / public PersistenceManagerFactory pmf () {return pmf;} / ** * Get the current thread and a PersistenceManager * @return objects related to a PersistenceManager * / public PersistenceManager pm () {return (PersistenceManager) get ();} / ** * associated with this release all resources JDO thread * / public void cleanup () {PersistenceManager pm = PM (); if (pm == null) return; try {if (! pm.isclosed ()) {Transaction TS = PM.CurrentTransAction (); if (ts.isactive ()) {log.warn ("Found one Unfinished Transaction [" PMF.GetConnectionURL () "]! " TS); Ts.rollback ();} pm.close ();}} catch (exception ex) {log.error ("Unlike JDO resources:" EX, EX);} finally {set (null);}} public Object get () {PersistenceManager PM = (persistenceManager) super.get (); if (pm == null || pm.isclosed ()) {pm = pmf.getPersistenceManager (); set (pm); if (log.Indebugebled) ()) log.debug ("Retrieved New PM: PM);} Return PM;} public static final logger log = logger.getlogger (PersistenceManagerRever.Class);

Private persistenceManagerFactory PMF;} This, only in all threads (such as a page request), only directly call PersistenceManagerRetriever.pm (); and, only after the last use Calls PersistenceManagerRetriever.cleanup () to close it.

This persistenceManagerRetriever initialization code may be added to a system class: PersistenceManagerRetriever persistenceManagerRetriever = new PersistenceManagerRetriever (properties); Closes the current thread is a PM associated statement (persistenceManagerRetriever.cleanup ()) may be configured to complete a JspFilter it, for example: public static class JspFilter implements javax.servlet.Filter {public void doFilter (javax.servlet.ServletRequest request, javax.servlet.ServletResponse response, javax.servlet.FilterChain chain) throws javax.servlet.ServletException, java.io.IOException {try { chain.doFilter (request, response);} finally {if (! pmRetriever = null) pmRetriever.cleanup ();}} public void init (javax.servlet.FilterConfig filterConfig) throws javax.servlet.ServletException {} public javax.servlet .Filterconfig getfilterconfig () {return null;} public void setfilterconfig (javax.servlet.filterconfig fc) {} public void destroy () {}} then we will It is configured in a descriptor in WebApp: jdo_jspfilter ... xxx.jdo_util.jspfilter jdo_jspfilter *. jsp The code we are in JSP is simpler: ... persistenceManagerRever.pm (). CurrentTransAction (). begin (); // calls some xxxsession.somethodtHatusesSpm () methods of handling business logic, which uses PersistenceManagerRetriever.pm () in these methods to get PM (). PersistenceManagerRetriever.pm (). CurrentTransAction (). Commit (); No processing exception, JSPFilter belongs to handle. 7 ID and object model object identification fields, actually just a field of a database, and actually do not need these attributes in the object model.

That is, in the Java application, an identification of an object is the address in memory, not the properties of this object itself, as this object can be uniquely determined based on this memory address. For example, a Java program that edits vector maps, after reading each map element (object) from the file, these objects have a unique memory address, so it is not necessary to add a similar "ID" to each object. And write to the file. JDO also uses this concept, ID is independent of the object, does not belong to a part of the object. We can see in front of the forum entity class diagram, and there is no attribute similar to "ID" in each class. So how do JDO controls the correspondence with the primary key in the database? This is two commonly used tool-based methods: Object persistenceManager.getObjectId (Object obj) Object personistenceManager.getObjectByid (Object Obj, Boolean Validate) This allows you to get an identical ID of an entity object, or find one ID at any time This object is out. The first method can also be replaced with javax.jdo.jdohelper.getObjectId (). In the JDO specification, these IDs are automatically generated by JDO products. In project applications, only when the reference is required, such as between the two pages. Also, these ID classes can be transpleated with String, which is convenient for JSP delivery. This ID is called DataStore Identity, which is typically "JDO_ID" in the field name in the data table. If you really want yourself to control the ID in the database, JDO also provides user-defined IDs. At this time, the ID is existed as an attribute of the object, which can be any type, int, date, string, or other customized Compound types (such as two properties together as ID). This type of ID is called Application Identity. In a person concern, I recommend using Datastore Idity in the new project, so you can save a lot of time. In entity class can write some alternative way to maintain compatibility with the application identity, such as: public class SomePersistentClass {... public String getId () {return JDOHelper.getObjectById (this) .toString ();} public static SomePersistentClass GetId (String ID) {PersistenceManager PM = persistenceManagerRetriever.pm (); Return PM.GetObjectById (SomePersistentClass.class, ID));}} This method is valid for both types of IDs. Note that this class itself has these two methods, but there is no ID attribute. 8 Buffer and Optimistic Transaction Buffer is a highlight in JDO. Although the JDO specification does not strictly requires a JDO product to achieve what kind of buffer, almost every JDO product, especially commercial products, have a relatively perfect buffer system, this system is the focus of different JDO products. One. The main JDO products include the following buffers: 1. PM connection pool.

Buffering the PersistenceManager, similar to the JDBC connection pool, does not close it when calling PM.Close (), but waiting for the next call or timeout. 2. PreparedStatement buffer. If the JDO underlying finds that a JDOQL statement is the same as the previously used sentence, no new PREPAREDSTATEMENT is generated, but an existing statement in the buffer pool. The buffering of PreparedStatement is also a feature in the JDBC3.0 specification. The JDO underfielding finds that the driver buffer is used when configured in accordance with the Drive of the JDBC3.0 specification, otherwise you can use your own buffer. 3. ResultSet buffer. This kind of buffer implementation is not much JDO product, which is currently like only Kodojdo 2.5.0 Beta implementation. Its mechanism is if the second request performs the same JDOQL statement, the same parameter query, the JDO underlayer removes the collection from the previous execution result, directly returns, greatly enhanced performance. However, the resource is consumed because it is implemented in JDBC2.0. Generally, when updating the database, we lock the database, set different isolation levels, can complete different levels of lock, such as lock records, lock fields, locks, locks, and more. The JDO can be set in the Vendor Extension marker of the specific JDO product. In addition, the JDO specification also provides a way to completely locked the database: javax.jdo.option.optimisticTransaction, it is an optional option, that is, it is not to force the JDO manufacturer to achieve it, but the main one Vendor's JDO products have realized this feature. The mechanism principle of OptimisticTransaction is to add a transaction control field in the database record of each object, and then all object changes are completed in the Memory of the Java virtual machine. When submitted, check each changed object from Whether it is changed by other external programs after being removed in the database, which is done through this control field. Generally, this field is implemented: 1. Store the last time, the field name is more than "JDO_LAST_UPDATE_TIME" 2. The number of times the history is changed, the field name is more "jdo_version" in OptimisticTransaction In Transaction, the JDO bottom layer does not lock the database, which guarantees that the TRANSACTION for time span does not affect the execution of other threads (requests), just if the update operation is more, the access amount is relatively large, Transaction Submit The chance of failing will also become larger. 9 JDBC2.0 and JDBC3.0JDO are just an object-level packaging, which is based on JDBC, both of which cannot be replaced with each other. In fact, JDBC's norms range from 1.0 to 2.0, and then 3.0 has been doing functional and performance improvements. Of course, JDO products will not let these, a general JDO product, which detects which specification is in line with the JDBC driver of the underlying configuration, and will try to use the function of the drive itself to achieve a specific operation. For code developers, we can only master JDBC1.0 operations, and a small amount of 2.0 operation, only some of the master's master's advanced features in JDBC3.0. Therefore, JDO can also help us improve performance and efficiency without understanding the JDBC3.0 specification.

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

New Post(0)