《The Object-Oriented Thought Process》讀書筆記8

12 Persistent Objects: Serialization and RelationalDatabases

Persistent Objects Basics

The concept ofsaving the state of an object so that it can be used later is called persistence.

Figure 12.2 Object life cycle with persistence.

 

Saving the Object to a Flat File

Java has abuilt-in mechanism for object persistence. Like other C-based languages, Javalargely uses the concept of a stream to deal with I/O.To write to a Stream, objects must implement either the Serializable or Externalizable interface.

Serializing a File

class Person implements Serializable{

 

    …

    publicSavePerson(){

    …

    }

}

Implementation and Interface Revisited

Person person = (Person )ois.readObject();

What About the Methods?

the methods themselves are notnecessarily kept in the data store.

Using XML in the Serialization Process

XML is thestandard for defining data, so we can create an XML model of our serializationexample that can, at least theoretically, be used across various platforms andlanguages.

Let’s first lookat the C# code.

[XmlAttribute(“name”)]

public String Name

{

get

{

return this.strName;

}

set

{

if (value == null) return;

this.strName = value;

}

}

 

public void Serialize()

{

Person[]myPeople = new Person[3];

myPeople[0] =new Person(“John Q. Public”, 32, 95);

myPeople[1] =new Person(“Jacob M. Smith”, 35, 67);

myPeople[2] =new Person(“Joe L. Jones”, 65, 77);

XmlSerializermySerializer = new XmlSerializer(typeof(Person[]));

TextWritermyWriter = new StreamWriter(“person.xml”);

mySerializer.Serialize(myWriter,myPeople);

myWriter.Close();

}

the fileproduced is in XML.

 

<?xml version=”1.0” encoding=”utf-8”?>

<ArrayOfPerson xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”

xmlns:xsd=”http://www.w3.org/2001/XMLSchema”>

<Person name=”John Q.Public”>

<age>32</age>

</Person>

<Person name=”Jacob M.Smith”>

<age>35</age>

</Person>

<Person name=”Joe L.Jones”>

<age>65</age>

</Person>

</ArrayOfPerson>

To restore theobject,we use the following code:

public void DeSerialize()

{

Person[]myRestoredPeople;

XmlSerializermySerializer = new XmlSerializer(typeof(Person[]));

TextReadermyReader = new StreamReader(“person.xml”);

myRestoredPeople= (Person[])mySerializer.Deserialize(myReader);

Console.WriteLine(“My People restored:”);

foreach (PersonlistPerson in myRestoredPeople)

{

Console WriteLine(listPerson.Name + “ is “ +

listPerson.Age + “ years old.”);

}

Console.WriteLine(“Press any key to continue...”);

Console.ReadKey();

}

As we havenoted, one of the major advantages of this approach is that the XML file isaccessible by any and all languages and platforms that implement the XMLinterface, including Java.

Writing to a Relational Database

    Accessing aRelational Database

JDBC Java Database Connectivity                               

Open Database Connectivity (ODBC)

Figure 12.7 Database client server model using ODBC/JDBC.

Loading the Driver

Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

    Making theConnection

Connection con = DriverManager.getConnection(“jdbc:odbc:myDriver”, “id”, “pwd”);

The SQL Statements

String sqlQuery= “SELECTPRODUCT FFROM SUPPLIERTABLE WHERE PRODUCT = ‘Bolts’”;

ResultSet rs = statement.executeQuery(sqlQuery);

The complete code for this exampleis as follows:

 

public void findVendor(String vendorId)throws SQLException{

       StringreturnString = null;

       StringdbUserid = “userid”; // Your Database user id

       StringdbPassword = “password” ; // Your Database password

       Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

       Connectionconnection =

       DriverManager.getConnection(“jdbc:odbc:myDriver”,dbUserid ,dbPassword);

       Statementstatement = connection .createStatement();

       StringsqlQuery=

              “selectPRODUCT from SUPPLIERTABLE where PRODUCT = ‘Bolts’”;

              ResultSetrs = statement.executeQuery(sqlQuery);

       if(rs.next())

       {

              System.out.println(“rs.getString(“SUPPLIERID”));

       }

       statement.close();

       connection.close();

}

Conclusion

In this chapter,we covered theconcept of object persistence.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章