Objects | Data in this article, we will discuss the Sun's Java data Object (JDO) standards in detail. JDO allows us to use Java objects to support transactions and multiuser. Unlike ODBC, it eliminates the need to consider SQL and other things related to the database. It is also different from serialization because it supports multiple users and transactions. JDO allows Java developers to use their data models as data models without having to spend a lot of time transferring between "data-side" and "Object-side".
The JDO standard is achievable for a variety of products, including Cocobase, Webgain TopLink and Castor jdo. Since there is a standard approach, we can only learn one of them, as with ODBC, we can use any database that provides a driver.
In this article, we will use the Prism technology company's openfusion JDO. Readers will later find that only a small part of the code uses the Prismtech API, and the other parts use the standard JDO standard.
Create a Person object
We will first create a person object that follows the JavaBean convention and can perform get and set operations on its properties. It should be noted that although we are creating this class, it is nothing special and it does not inherit or implement any of the basic classes. The requirements for a sustainable class are:
1. All domains must be able to be accessed by the JDO class (public or Set* method)
2. The data type of the domain must conform to the JDO specification.
3, can not support some types of fields (such as thread, File, socket, etc. can not be serialized fields).
Below are the Person.java that meet the above requirements:
public class Person {
private String name;
Private String address;
Private String SSN;
Private String Email;
Private String HomePhone;
Private String Workphone;
Allows us to create a person object using the constructor
Public person (string name, string address, string ssn,
string email, string homephone, String workphone) {
THIS.name = name;
this.address = address;
THIS.SSN = SSN;
This.email = email;
This.homephone = HomePhone;
This.workphone = Workphone;
}
Method
Public String GetName () {return name;}
Public String getaddress () {return address;}
Public String getssn () {return ssn;}
Public String Getemail () {return email;}
Public String Gethomephone () {return homephone;}
Public String Getworkphone () {return workphone;}
public void SetName (String name) {this.name = name;}
public void setaddress (String address) {
this.address = address;
}
public void Setssn (String ssn) {this.ssn = ssn;}
public void Setemail (String email) {this.email = email;}
public void Sethomephone (String homephone) {
This.homephone = HomePhone;
}
public void Setworkphone (String workphone) {
This.workphone = Workphone;
}
}
Creating Personpersist Object Management Retention
Now that you have a person object, we need to create some code to manage this retention. Here we'll discuss the code in detail and learn how to:
1. Initialize JDO to maintain the manager.
2, to the database to enter three people's data.
3, from the database display of human data.
4. Modify the name of one of the persons.
5. Delete A person's data from the database.
6, in the main () method for related processing.
Step One: Initialize the JDO persistence Manager
We have imported standard JDO classes and managedconnectionfactory from the openfusion implementation, and of course we can abstract them into a separate class. The constructor uses the Javax.jdo.PersistenceManagerFactoryClass property to set the connection agent, which is similar to the property setting the database driver in JDBC.
Package addressbook;
public class Personpersist
{
Private final static int SIZE = 3;
Private persistencemanagerfactory PMF = null;
Private PersistenceManager PM = null;
Private Transaction Transaction = null;
An array of people who need to keep
Private person[] people;
Vector of existing object identifiers
Private vector id = new vector (SIZE);
Public Personpersist () {
try {
Properties Props = new properties ();
Props.setproperty ("Javax.jdo.PersistenceManagerFactoryClass",
"Com.prismt.j2ee.jdo.PersistenceManagerFactoryImpl");
PMF = jdohelper.getpersistencemanagerfactory (props);
Pmf.setconnectionfactory (Createconnectionfactory ());
catch (Exception ex) {
Ex.printstacktrace ();
System.exit (1);
}
}
The connection agent is created in a static method named Createconnectionfactory () that requires a JDBC URL, JDBC driver, user name, and password.
public static Object Createconnectionfactory () {
Managedconnectionfactoryimpl MCFI = new
Managedconnectionfactoryimpl ();
Object connectionfactory = null;
Step Two: Enter data for three people in the database
Persistpeople () uses the constructor in the Person.java file to create 3-person data. The first thing we're going to do is pass
Getpersistencemanager () Gets a retention manager and then creates a transaction that performs our task. To keep this graph of objects, we simply call the Makepersistentall (object[]) method. The for () loop at the bottom of the code gets the unique ID of each persisted object and is saved for later use.
public void Persistpeople () {
Create an array of people's data
People = new Person[size];
Create 3-person information
People[0] = new Person ("Gary Segal", "123 Foobar Lane",
"123-123-1234", "gary@segal.com",
"(608) 294-0192", "(608) 029-4059");
PEOPLE[1] = new Person ("Michael Owen",
"222 Bazza Lane, Liverpool, MN",
"111-222-3333", "michael@owen.com",
"(720) 111-2222", "(303) 222-3333");
PEOPLE[2] = new Person ("Roy Keane",
"222 Trafford Ave, Manchester, MN",
"234-235-3830", "roy@keane.com",
"(720) 940-9049", "(303) 309-7599)");
Keep the information of these 3 people.
PM = Pmf.getpersistencemanager ();
Transaction = Pm.currenttransaction ();
Pm.makepersistentall (people);
Transaction.commit ();
Gets the object ID of the persisted object
for (int i = 0; i < people.length; i++) {
Id.add (Pm.getobjectid (people[i));
}
Closes the existing retention manager to ensure that the object is read from the database rather than from the retention manager's cache
Pm.close ();
}
Here are some other ways you can focus on the persistence Manager:
Make the instance sustainable: Get a temporary object and keep it.
Delete to persist instances: Delete information from the data repository.
To make an instance temporary: Detach the instance from the retention manager without deleting the information in the data repository.
Keep an instance in a holding state delete a persisted instance leave the instance in a temporary state
Makepersistent (Object o) deletepersistent (object o) maketransient (object o)
Makepersistentall (object[] os) deletepersistentall (object[] os) maketransientall (object[) OS)
Makepersistentall (Collection os) deletepersistentall (Collection os) maketransientall (Collection OS)
(Here is a 4x3 form, refer to the English form in the manuscript)
Step Three: Display information about people in the database
Displays the information code to get the retention manager to begin. We use the object ID saved by the Persistpeople () method in the above code to get the object, and the method of calling the object ━━ in this case is gets to get the information we entered. We can find that to keep our objects, there is no need to write a lot of code.
public void display (int end) {
Person of person;
int max = end <= SIZE? End:size;
To get a new retention manager
PM = Pmf.getpersistencemanager ();
Get the object from the database and display it
for (int i = 0; i < max; i++) {
person = (person) Pm.getobjectbyid (Id.elementat (i),
FALSE);
System.out.println ("Name:" + person.getname ());
SYSTEM.OUT.PRINTLN ("Address:" +
Person.getaddress ());
System.out.println ("SSN:" + person.getssn ());
System.out.println ("Email:" + person.getemail ());
System.out.println ("Home Phone:" +
Person.gethomephone ());
System.out.println ("Work Phone:" +
Person.getworkphone ());
}
Pm.close ();
}
Step Fourth: Change the name of one of the people
The code to change the information of a person stored in a database is also very simple, and it is very similar to the code that displays the information about people in the database. Here, we need to create a transaction (because we want to modify the records in it), use the defined SetName () method to modify a person's name, eventually commit the transaction, and save the changes. The real difference between this operation and the handling of temporary objects is that we consider the transaction.
public void Change () {
Person of person;
Getting objects from the data repository
PM = Pmf.getpersistencemanager ();
Transaction = Pm.currenttransaction ();
Modify the second datastring field that holds records
person = (person) Pm.getobjectbyid (Id.elementat (1),
FALSE);
Person.setname ("Steve Gerrard");
Commit the transaction and close the retention manager
Transaction.commit ();
Pm.close ();
}
Fifth step: Delete a person's information
Can you imagine the code that deletes the second person from the database? Because we already know all the knowledge needed to write this code. A closer look at the code below will show that we use the Deletepersistent () method mentioned in the second step of the persistence Manager method.
public void Delete () {
Getting objects from the database
PM = Pmf.getpersistencemanager ();
Transaction = Pm.currenttransaction ();
Deletes the second person's information from the database and deletes its ID from the ID vector
Pm.deletepersistent (Pm.getobjectbyid (Id.remove (1),
false));
Commit the transaction and close the retention manager
Transaction.commit ();
Pm.close ();
}
Step Sixth: Run the above code in the main () method
Finally, the entire code needs to have a main () string, enter the person's information in the database, change the name of one of the people, and then delete the person's data. If you run this program, you will see the Address Book when the program runs to each step.
public static void Main (string[] args) {
System.out.println ("Create personpersist");
Personpersist personpersist = new Personpersist ();
System.out.println ("Setup and persist a group of people");
Personpersist.persistpeople ();
System.out.println ("Display The Persisted people");
Personpersist.display (SIZE);
System.out.println ("Change a name");
Personpersist.change ();
Personpersist.display (SIZE);
System.out.println ("Delete a Person");
Personpersist.delete ();
Personpersist.display (SIZE-1);
}
Jdoenhancer: Create the JDO descriptor for the Jdoenhancer
Now that we have written the source code for the entire application, the next step is to create a jdoenhancer that will be used
The JDO descriptor. The reader will certainly ask, what is Jdoenhancer? The JDO architecture is based on the idea that a JDO implementation can get the byte code of the class, process them, and add some necessary functionality. For example, Jdoenhancer will make the class implement the Persistancecapable interface (so we don't have to programmatically implement this interface), and we can implement some of the methods in that interface. So after compiling the code we'll find that we have to run jdoenhancer to do the proper processing of bytecode. We need to create a descriptor file that gives us information about the class that we need to keep, as shown in the following document:
<?xml version= "1.0" encoding= "UTF-8"?>
<! DOCTYPE JDO SYSTEM
"File:/d:/apps/openfusionjdo/xml/schema/jdo.dtd" >
<jdo>
<package name= "AddressBook" >
<class name= "Person" identity-type= "Datastore" >
</class>
</package>
</jdo>
This is only a basic document, but it can meet our requirements. Of course, there are many more complex mappings. The following is a slightly more complex mapping in the openfusion example:
<class name= "Department" identity-type= "Datastore" >
<field name= "Name"/>
<field name= "Employees" >
<collection element-
Type= "Com.prismt.j2ee.jdo.examples.appKeyDepartment.Employee" >
</collection>
</field>
<field name= "Manager"/>
</class>
</package>
</jdo>
Now that we've written the code and the JDO descriptor files, we'll consolidate them and discuss how to build the entire system. To build the whole system, we just need a few simple steps to work:
1, compile the code.
2, run Jdoenhancer.
3, the use of jdoenhancer output to establish a database.
4, run the application.
The first step: compiling the Code
I think the broad masses of readers must already know how to run the Javac. Before running Javac, we just have to make sure that classpath is set properly. The following is an example of running Javac on a Windows platform:
% Set Openfusion_dir=d:\apps\openfusionjdo
% Set
Classpath=%openfusion_dir%\lib\connector.jar;%o penfusion_dir%\
Lib\jndi.jar;%o Penfusion_dir%\lib\log4j.jar;%o Penfusion_dir%\l
Ib\xerces.jar;%o Penfusion_dir%\lib\classes12.zip;%o Penfusion_d
Ir%\lib\jdo.jar;%o penfusion_dir%\lib\jta-
Spec1_0_1.jar;%o Penfusion_dir%\lib\ofjdo.jar;.
% Javac? d. Person*.java
Step Two: Run Jdoenhancer
Jdoenhancer needs to use the bytecode from the previous compilation and the JDO descriptor file we established earlier. Here is the complete syntax for openfusion jdoenhancer:
Java com.prismt.j2ee.jdo.enhancer.JDOEnhancer
Command options:
-CP begins searching for the basic path of the class that needs to be hardened, unlike classpath, which is the directory where the compiled retention class resides
-OC Storage-Hardened class directory
-PD JDO Descriptor File
Available options:
-DB Specify target database [Oracle, Sybase, etc]
-od a directory that generates SQL scripts
Here's an example of running jdoenhancer to build our application:
% Java Com.prismt.j2ee.jdo.enhancer.jdoenhancer-oc. -pd
Person.jdo-db Oracle-od DB-CP.
Step three: Build a database using Jdoenhancer output
, Jdoenhancer is able to create database scripts that build the database, provided that you use the DB and-od options. It can create many scripts, but one of them is named Load_all.sql, open the file and load it into a SQL prompt. (for example, Sqlplus for Oracle)
CREATE SEQUENCE instid_seq INCREMENT by 1
;
CREATE TABLE Jdo_addressbook_person_sco
(
inst_id INTEGER not NULL,
Class INTEGER not NULL,
Jdo_address VARCHAR2 (255),
Jdo_email VARCHAR2 (255),
Jdo_homephone VARCHAR2 (255),
Jdo_name VARCHAR2 (255),
JDO_SSN VARCHAR2 (255),
Jdo_workphone VARCHAR2 (255)
)
;
CREATE TABLE Jdo_addressbook_person
(
inst_id INTEGER not NULL,
Class INTEGER not NULL,
Jdo_address VARCHAR2 (255),
Jdo_email VARCHAR2 (255),
Jdo_homephone VARCHAR2 (255),
Jdo_name VARCHAR2 (255),
JDO_SSN VARCHAR2 (255),
Jdo_workphone VARCHAR2 (255)
)
;
CREATE TABLE Prismjdoprop
(
Name VARCHAR2 (255) PRIMARY KEY,
Value VARCHAR2 (255)
)
;
CREATE TABLE prismjdoextents
(
class_id number (38,0) PRIMARY KEY,
Class_name VARCHAR2 (255) UNIQUE,
App_key VARCHAR2 (255)
)
;
ALTER TABLE Jdo_addressbook_person_sco ADD PRIMARY KEY
(INST_ID, Class)
;
ALTER TABLE Jdo_addressbook_person ADD PRIMARY KEY (inst_id,
Class
;
INSERT into Prismjdoextents VALUES (0, ' addressbook. Person ',
' Com.prismt.j2ee.jdo.spi.DBKey ')
;
COMMIT WORK
;
INSERT into Prismjdoprop VALUES (' use. Rdbms. Triggers ', ' true ')
;
COMMIT WORK
;
Step Fourth: Run the application
Now that the database has been established, we can run the application. How to share the fruits of your labor!
% Java addressbook. Personpersist
Conclusion
We have discussed how to use the Openfusion JDO implementation to handle the JDO standards. This is a whole new area where developers can focus on business needs and objects without being proficient in SQL.
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.