Persistence technology worth paying attention: hibernate
How do you persistent data? EJB (CMP)? JDO? JDBC SQL?
Here I want to recommend another object that is worthy of attention - the relationship mapping frame Hibernate, which is a sub-project for SourceForge.net.
This article is intended to give a probably contour (very time), please refer to its own excellent document.
Reference: A group of cattle discussions about JDO and EJB: Java Object Models Debated also mentioned this open source project.
Brief description of the first intimate contact: a simple example of complex relationships
1. Brief description:
If you take a new technology to take time, it will not pay back the time after using it:
We can use keywords: "JDO EJB CMP Hibernate" to find a comment article on Google, as long as used
People who have hibernate are very advocated to it (I also).
Our object model can be used very well by Hibernate, and the Persistent Object in the figure below is a simple business entity object.
(Objects to be persisted). The transparent persistence through Hibernate into the database. The following example will explain everything.
2. A simple example
We develop a Person class:
It can be imagined that the data table is below:
Table Person
ID (PRIMARY Key) NameAddress00000000 Chen Peng Xi'an ...
To implement it through Hibernate, it is necessary to pass through the following steps:
Mainly, the simple business entity class is written according to the object model (simple bean specification, that is, the GET, SET method class, can be generated with JAC),
Use the XML mapping file to describe the way it maps the database (very easy), and finally you can last through the small Hibernate API write test class.
operating.
2.1 Write the PersonTent Object, it is different from the ordinary class, but pay attention to it should comply with the specification of the bean, provide GET, SET method for each property:
H.Person // Warning: this file Has Been Automatic Or generated by jac // do not modify unless, public, {string name; / ** * sets the value of field name. * * @Param name * value of field name * / public void setname (string value) {this.name = value;} / ** * gets the value of field name. * * @Return value of infen * / public string getName () {return name;} String address;. / ** * Sets the value of field address * * @param address * value of field address * / public void setAddress (String value) {this.address = value;} / ** * Gets the value of field address. * * @Return value of field address * / public string getaddress () {Return address;} string id; / ** * sets the value of field id. * * @Param ID * Value of Field ID * / Public void setid (string value) {this.id = value;} / ** * gets the value of field ID. * * @return value of field id * / public string getId () {return ID;}} 2.2 Fill in the object - Relationship mapping XML file, don't worry about its complexity, we can copy:
Write this mapping file like all O-R mapping tools.
Person.hbm.xml is recommended to name: "Class name" "hbm.xml" and place it in the same package directory in the Person class
XML Version = "1.0" encoding = "gb2312"?>
H. TestPerson Package H; Import Net.sf.hibernate.Session; import net.sf.hibernate.Transaction; import net.sf.hibernate.SessionFactory; import net.sf.hibernate.cfg.configuration; import net.sf.hibernate .tool.hbm2ddl.SchemaExport; class TestPerson {private static SessionFactory sessions; public static void main (String [] args) throws Exception {// configuration environment, analyzing the mapping xml file configuration conf = new configuration () .addClass (Person.class ); // Generate and output SQL to file (current directory) and database schemaexport dbexport = new schemaExport (conf); dbexport.setputPutfile ("build / sql.txt"); dbexport.create (true, true); sessions = confe .BUILDSessionFactory (); // The above is a fixed format environment configuration // start ... session s = sessions.openSession () (); transaction t = s.begintransaction (); // 1. Use ordinary use Way to build an object, fill data in Person P1 = new person (); p1.setname ("Chen Peng"); P1.Setaddress ("Xi'an East, Huangling"); // 2. Holding S. Save (P1); / / At this point P1 can already find T.Commit (); s.close ();}}
2.4 In order to run the database: I take the mysql database as an example: (only use labor 1 time)
Hibernate.properties You can find this file template in the root directory of the Hibernate source program, Copy to our root directory. That is: "../ h" ## mysql ## The first two lines are filled with you, only fill in the database connection and username, passwordHibernate.diaract net.sf.hibernate.diaract.MysqldiaalectHibernate.Connection.Driver_class org. gjt.mm.mysql.Driverhibernate.connection.url jdbc: mysql: // localhost / test useUnicode = true & characterEncoding = GBKhibernate.connection.username roothibernate.connection.password2.5 run TestPerson class, observing create a good table in mysql person? And data
OK! The whole process is mainly the first 3 steps: Write the Bean class (Persistent Object), write O-R mapping files, write to the test class.
3. Examples of complex relations
Let's change a slightly complicated example to see:
It can be imagined that the data table is below:
Table Person
ID (PRIMARY Key) company_idnameaddress0000000000000000002 Chen Peng Xi'an
Table Company
ID (Primary Key) Name000000002 East Soft ...
3.1 Person (already available) Class: Persistent Object
H.Company Package H; Public Class Company {String ID; Public Void SetId (String Value) {this.id = value;} public string getId () {return id;} String name; public void setname (string value) {THIS .name = value;} public string getname () {return name;} java.util.list Employees = new java.util.vector (); public void setemployees (java.util.list value) {this.employees = value; } public java.util.List getEmployees () {return employees;} public void addEmployee (h.Person value) {employees.add (value);} public void removeEmployee (h.Person value) {employees.remove (value); } Public void clearemployees () {Employees.clear ();}}
3.2 Fill in the object - the relationship map XML file, Person.hbm.xml is still
COMPANY.HBM.XML is also placed in the same directory in the H.Company class XML Version = "1.0" encoding = "gb2312"?>
h.TestCompanypackage h; import net.sf.hibernate.Session; import net.sf.hibernate.Transaction; import net.sf.hibernate.SessionFactory; import net.sf.hibernate.cfg.Configuration; import net.sf.hibernate. tool.hbm2ddl.SchemaExport; class TestCompany {private static SessionFactory sessions; public static void main (String [] args) throws Exception {// configuration environment, analyzing the mapping xml file configuration conf = new configuration () .addClass (Person.class) .addclass (company.class); // Generate and output SQL to file (current directory) and database schemaexport dbexport = new schemaexport (conf); dbexport.setputfile ("build / sql.txt"); dbexport.create (True, True); sessions = conf.buildsessionFactory (); // More than a fixed format environment configuration // start ... session s = sessions.opensession (); transaction t = s.begintransaction (); / / 1. Establish an object with ordinary way, fill data companies C = new company (); C.setname ("East Soft"); Person P1 = New Person (); p1.setname ("Chen Petrname); p1.setaddress "Xi'an East, Huangling"; Person P2 = New Person (); p2.setname "Sun Yapeng"); P2.Setaddress ("Nanjiao Electronic City"); C.ADDemPloyee (P1); C.AddemPloyee (P2); // 2. Holding S. Save (C); // At this time C, P1 P2 can already find T.Commit () in the database; S.Close ();}} 3.4 Do not configure the database.
3.5 Run the TestCompany class, observe the data of CREATE Table Person and Company in MySQL.
to sum up:
Here only shows the implementation of the two persistent examples, more 1: 1, 1: n, m: N, etc., see the documentation included with Hibernate,
The more complex models, the more you can reflect its power. Objects such as Hibernate, JDO, EJB - the benefits of the relationship map middleware are obvious,
Comrades who are still studying SQL JDBC should rest, I am hard enough! (You will not build such a middleware yourself, amazing!)
Example download:
Example of the Person class
Examples of Person-Company
Two examples require Hibernate's lib, please download Hibernate yourself.
Reference connection:
XPetStore 3.0 Applying a complete example of Hibernate.
Unusual active hibernate.
MySQL: http://www.mysql.com/mysql is a very easy to use graphical client: http://www.mysqlstudio.com/
Another introduction to JDO articles
About the Author:
Chen Peng, Dongping Xi'an Company. As a fanatic programmer hopes to grow progress every day, and hope to share happiness and knowledge with you. Please contact him in the following ways: email chen56@msn.com