Relationship mapping using Hibernate

zhaozj2021-02-12  145

Relationship mapping using Hibernate

Original connection: http://www.meagle.com: 8080 / hibernate.jsp

Hibernate is an industry-related ORM (O / R mapping). The current version is very stable and mature, and his document is also extremely rich. Http://www.jdon.com and http://www.chinaxp.com The two technical websites are also very fine to Hibernate. This article is an article that lets the scholars entry. It is interested in that English can skip directly to read the original text. - Translator

There are many methods in Java technology to persist in data, and the persistence layer is also one of the most important parts of the Java application. When today's relational database is still a mainstream database, I personally think that persistence technology is often not approved. In this article, several famous persistent frameworks achieved by Java technology will then be discussed to some of the latest persistence frames, such as: Hibernate, let us open from those famous frames to the extreme universal APIS. Trip.

1. Most Java developers are communicating with JDBC and databases, which can be improved and improved through the DAO (Data Access Object) mode, however, this way is maintained in large applications, "high consumption ". However, most developers are very familiar with JDBC's operation and their API, so I believe that it is still one of the most widely used data lasting technologies. (Don't worry "" Nightmare is going to end ", the translator's note)

2. EJB According to the survey EJB, it is usually a second choice for data persistent technology. It is a "Silver Bank" in the Java lasting framework through entry Beans. Silver bomb ??), I mean in a huge market (potential big cake?). However, it is not the case: First, you need to buy a reasonable EJB container - J2EE application server, free EJB container with open source projects is a good choice :), such as JBoss (forgiveness); It takes the Entity Bean to take a "large amount" time to understand the EJB specification. Before using EJB, you usually want to master its API; then, you need to know the deployment descriptor except EJB-JAR.XML except EJB-JAR.XML, and many commercial EJB containers performance and technical support I don't dare to compliment. For Java developers, JDBCs in EJB are also more complicated. EJB is the most concerned that may be stateless session bean (stateless-session beans) and message-driven beans (Messaging Driver Beans)

3. More lasting frames After a "swimming and 踌躇" in front of the previous norms, you may find that they are not perfect solutions. JDO's appearance seems to be changed, but JDO1.0 seems to be from the operation mode or its function seems to "day or gray", "and there is no good free product", JDO1.0 still does not have much change, people still stay in the stage of learning it, this situation is to be solved by JDO. (At present, Sun has joined JDOCENTORL.COM to start JDO2.0, and we only wait for the shirt.) So what should we do? If you leave the mainstream concept, you will find that you will have more choices (maybe it's better?), If so, you won't pay attention to the two names "hibernate" and "OJB "These two long-lasting frames are very different from the previously mentioned JDBC, EJB and JDO in some respects, they don't need any containers, provide easy to use and comply with ODMG3-Style Apis, and they are free, open source , Rich document and stable development background. Maybe what you have to do is choose? 4 "Harmony" hibernate let us start now, in these "fresh" persistent frames I chose Hibernate, and at the same time, I also included the OJB in my selection, but the last reason for choosing Hibernate will be done. In its rich document, I know that there are many other people to use OJB and have succeeded. No matter what, Hibernate and OJB allow you to completely manipulate your persistence. Please visit http://hibernate.blumers.net/4.html to get Hibernate's functional introduction. Below I want to say my running environment: Hibernate 2.0 RC1 (2.0 Beta 5) Tomcat 4.1.18 WebSphere Application Server 5.0.1 (please get the latest version, the translator's note), I The example can run normally in other containers, but I didn't perform this test. The Hibernate website is related to configuration information under JBoss, usually almost all application servers and databases can integrate hibernate.

4.1 Mapping RELATIONS with Hibernate Let's discuss how to use Hibernate to perform an object's relationship mapping. I will introduce how to use Hibernate to "one-to-one", "one-to-many", "multi-to-many" mapping. In the code I offer, just for testing without taking more "mode rules", etc., this is just a enlightenment here, let us learn Hibernate's API from the code, and how to develop, please Pay attention to the necessary patterns and coding specifications when you write.

Then we look at what objects in my example, let them model them, as shown below: The picture below shows the data table diagram:

4.2 Configuring Hibernate

Click here to get the instance code in this article so you can have a deeper understanding of this example. To run an instance, be sure that you have downloaded the latest release packages of Hibernate and Log4j, but also drive the database to the classpath. Download the example_schema.ddl file in the following compression package to generate a database table.

Next, the author tells us a hibernate.properties file, which is first in contact with Hibernate. It is initialized for us when the application starts (the translator Note: Hibernate.cfg.xml Hibernate.properties can have no, isn't it?) Hibernate.connection.driver_class = com.ibm.db2.jdbc.net.db2driver hibernate.connection.URL = JDBC: DB2: // Server1 / sample hibernate. connection.username = db2admin hibernate.connection.password = password hibernate.default_schema = db2admin hibernate.dialect = net.sf.hibernate.dialect.DB2Dialect hibernate.show_sql = true # The maximum number of active connections that can be allocated # from this pool at the same time, or zero for no limit. hibernate.dbcp.maxActive 100 # Action to take in case of an exhausted DBCP statement pool # (0 = fail, 1 = block, 2 = grow) hibernate.dbcp.whenExhaustedAction 1 hibernate .dbcp.maxWait 120000 # The maximum number of active connections that can remain # idle in the pool, without extra ones being released, or zero # for no limit. hibernate.dbcp.maxIdle 10 # The SQL query that will be used to validate # co nnections from this pool before returning them to the caller. # hibernate.dbcp.validationQuery = TODO ## prepared statement cache hibernate.dbcp.ps.maxActive 100 # Action to take in case of an exhausted DBCP statement #pool (0 = fail, 1 = block, 2 = grow) hibernate.dbcp.ps.whenExhaustedAction 1 # The maximum number of milliseconds that the pool will # wait (when there are no available connections) for a connection # to be returned before throwing an exception, or - 1 to # Wait Indefinitely. Hibernate.dbcp.ps.maxwait 120000 hibernate.dbcp.ps.maxidle 100

In the top of the code, first specify the attribute elements related to the data connection: Database Driver, JDBC URL, user account and password, Diagect ("Database" dialect, Tang, local, local words, etc., Diagect for each database we use Perform optimal optimization, you can get Diagect in each database in the Hibernate manual. Finally, hibernate.show_sql When set to "true", we can see HiBernate's debug information when it is executed SQL statement. The remaining attribute elements are used to configure the connection pool, which is used here to implement the connection pool with Jakarta DBCP (Details to Jakarta Official Website). The same Hibernate can also be implemented in other ways, such as: C3PO (I haven't heard of it, huh, ..). Details Enter the Hibernate document. 4.3 Creating a lasting object

After the Hibernate running environment, we started to create a persistent object or a mapping file to start our work. (Usually create an object and create a mapping file to do one, another can be done by doing a good time), here we start from the creation of a lasting object, the following is the completed code, the "persistent object" required by Hibernate is in line with The norms of the object we often write, they have no difference:

Package dbdemo; import java.util.date; import java.util.set; / ** * @ hibernate.class table = "users" * @Author meagle * * represents a user * / public class user {private string userid; private String userName; private String password; private String emailAddress; private Date lastLogon; private Set contacts; private Set books; private address address; / ** * @ hibernate.property column = "EmailAddress" type = "string" * @return String * / public String getEmailAddress () {return emailAddress;} / ** * @ hibernate.property column = "LastLogon" type = "date" * @return Date * / public Date getLastLogon () {return lastLogon;} / ** * @ hibernate.property column = "password" type = "string" * @return string * / public string getpassword () {return password;} / ** * @ hibernate.id generator-class = "assigned" type = "string" * column = "logonid" * @Return string * / public string getUserId () {return userid;} / ** * @ hibernate.property column = "Name" type = "string" * @return String * / public String getUserName () {return userName;} / ** * @param string * / public void setEmailAddress (String string) {emailAddress = string;

} / ** * @Param string * / public void setLastLogon (Date Date) {LastLogon = Date;} / ** * @Param string * / public void setpassword (string string) {password = string;} / ** * @ param string * / public void setUserID (String string) {userID = string;} / ** * @param string * / public void setUserName (String string) {userName = string;} / ** * @ hibernate.set role = " Contacts "Table =" Contacts "* cascade =" all "readonly =" true "* @ hibernate.collection-key color =" user_id "* @ hibernate.collection-one-to-man class =" dbdemo.contact "* @ Return java.util.set * / public set getcontacts () {return contacts;} / ** * @Param set * / public void setContacts (SET SET) {Contacts = set;} / ** * @ hibernate.set role = "books" table = "book_user_link" * cascade = "all" Eadonly = "true" * @ hibernate.collection-key column = "userid" * @Hibernate .COLLECTION-MANY-TO-MANY * Class = "DBDemo.book" Column = "Bookid" * @return java.util.set * / public set getBooks () {return books;} / ** * @

PARAM SET * / PUBLIC VOID SETBOOKS (SET SET) {Books = set;} / ** * @ hibernate.one-to-one class = "dbdemo.address" * @return dbdemo.address * / public address getaddress () { Return address;} / ** * @Param address * / public void setaddress (address address) {this.address = address;}} 4.4 Ant and xdoclet

If you look at the code on the upper side, you will find that it is a little "not too the same" before, and there are many specific javadoc in javadoc, yes, it is hibernatedoclet. It and xdoclet are "sisters", XDoclets are tools: it generates an application deployment descriptor with Apache Ant. Therefore, unless you are happy to write an XML mapping file, you will use xdoclet (but I still recommend beginners to handle **. HBm.xml). Go to view the details of Hibernatedoclet, let's take a look, here is if you use an object to generate mapping files, below, see build.xml:

False "Inverse =" true "cascade =" all "sort =" unsorted "> < Property name = "emailaddress" type = "string" column = "emailddress" not-null = "false" unique = "false" /> <

/ hibernate-maping> Once the mapped file is created (placed in the classpath, and the object is a "one-to-one" relationship), you can manipulate the system object through the interface and method of Hibernate. Finally, let's download the content in this article, each individual example has a main method to run: First example: hibernatedemo.java, add two users, and associated with Address ("One-to-one" Second Example: HibernateDemoonTomany.java, learning Hibernate for "a pair of" mappings; final, third example: hibernateDemanyTomany.java, learning "Multi-to-many" mapping with Hibernate. It is recommended that you run in order, if you don't use DB2 (E.G. Sequences). If you don't use DB2 (E.G. Sequences). If you can follow your database. There is also an example in the example package: HibernateDemoHQL uses the data generated by the previous example to explain how to manipulate data with HQL.

The author provides very simple in the examples, but for beginners is a very good opportunity (I hope that beginners will run attempt to the author's code, there are many things that this article does not say, but you can get answers through the author's code. ). I hope that you can get some help from here when you learn Hibernate.

You can contact the author through Mark Eagle (Meagle@meagle.com) and the author.

JPLATEAU 9/9/2003

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

New Post(0)