教程:散集和列集数据:实施
讨论此教程。 可打印版本 (PDF)。
这是目录页。 无上一页。 到上一级。 转至下一页。

实施


JAXB 保险配置文件系统 (JAXBIPS) 示例应用程序实施了几个在 Oracle JAXB 规范中定义的特性,包括:

  • JAXB 类生成器的使用
  • Marshaller 和 Unmarshaller 类的使用
  • 从文件和 StreamSource 进行列集和散集
  • 联合使用 JAXB 和 XMLType
  • 绑定 XML 模式和复杂类型
  • 在模式定义(多项声明信息)中使用集合类型
  • 散集 — 时间的验证

本教程主要讲解 JAXB 最重要的特性之一 — 散集和列集数据。在这一部分中,我们将通过查看相关的代码段,了解如何在应用程序中实施 JAXBIPS 的设计决策。在编写代码之前,我们需要在 Oracle JAXB 编译程序(oracle.xml.jaxb 程序包的一部分)的帮助下生成支持类。为了使用这一程序,我们需要在 CLASSPATH 中包含 xmlparserv2.jar:

在命令/解释程序提示符处执行以下命令:

$java oracle.xml.jaxb.orajaxb -schema profile.xsd -targetPkg oracle.otnsamples.orajaxb -outputDir ../src

要描述 XML 文档结构,我们需要有模式定义文件。我们使用 profile.xsd 来构建那些允许我们根据模式定义文件列集、散集和验证 XML 文档实例的类。我们示例中的模式定义文件是 profile.xsd

列集和散集 — 文件系统

现在我们来查看将 Java 实例列集到文件系统中的代码:


public void saveRecord(Record rec) {
try {
//Create a JAXBContext instance
JAXBContext jc = JAXBContext.newInstance(
"jaxbderived.profile"
                );
String filename = null;
if ( !dirPath.endsWith(".xml"))    
filename = dirPath + "/" + currentRecord.getCustomerID() +".xml";
else filename = dirPath;  

textArea.append(" Saving file  " + filename + "\n");

File f = new File(filename);

f.delete();

//Create a marshaler object
Marshaller m = jc.createMarshaller();
StringWriter swriter = new StringWriter();

//Marshal the record object
m.marshal(rec, swriter);

//Store the marshaled object in the String
String s = swriter.toString();

//Output this String to a file
FileOutputStream fout = new FileOutputStream(filename);
PrintWriter pw = new PrintWriter(fout);

pw.write(s);

//Flush and close file and printWriter
pw.flush();

if (pw != null) {
pw.close();
            }

if (fout != null) {
fout.close();
            }

textArea.append("Record saved...\n");
} catch (Exception e) {
e.printStackTrace();
        }
    }

以下是将文档实例从文件系统散集的代码:

public void loadSingleRecord() {
textArea.append("This may take some time.Please wait...\n");

try {
//Create a JAXBContext instance
JAXBContext jc = JAXBContext.newInstance(
"jaxbderived.profile"
                );

//Create an unmarshaller instance
Unmarshaller u = jc.createUnmarshaller();
u.setValidating(true);
textArea.append("\nReading file " + dirPath + "\n");

//Unmarshal the Record object from FileInputStream
Record rec = (Record) u.unmarshal(fileToURL(dirPath));

//Store the object in the list
list.add(rec);
textArea.append("One record loaded.\n Size of the list is " +
list.size() + " \n"
            );
} catch (Exception ex) {
textArea.append("There was an error while parsing \n" + dirPath +
"\nThis file will be ignored.\n"
            );
textArea.append(
"Please note that this error is thrown when the source XML does not "
            );
textArea.append(
"confirm to the Profile Record \nSchema definition.The error is given below \n"
            );
textArea.append(ex.toString() +"\n\n");
} finally {
        }
    }


列集和散集 — 数据库

以下是将记录列集并保存到数据库中的代码:

public void saveRecord(Record rec) {
Statement st = null;
JAXBContext jc = null;
Marshaller m = null;
OraclePreparedStatement stmt = null;

try {
st = con.createStatement();
textArea.append("Saving record with customer id " +
rec.getCustomerID() + " \n"
            );

//Delete previous record if any
st.execute(
"DELETE profile_tab pt WHERE  pt.c1.extract('//Record/@CustomerID').getStringVal() ='" +
rec.getCustomerID() + "'"
            );

if (st != null) {
st.close();
            }

//Insert updated record
stmt = (OraclePreparedStatement) con.prepareStatement(
"INSERT INTO profile_tab VALUES 
(XMLType.CreateXML(?).CreateSchemaBasedXML('http://jaxbderived.profile/profile.xsd'))" ); //Create JAXBContext instance jc = JAXBContext.newInstance("jaxbderived.profile"); //Create Marshaller instance m = jc.createMarshaller(); StringWriter swriter = new StringWriter(); //Marshal record object to a StringWriter m.marshal(rec, swriter); //Set the parameter stmt.setString(1, swriter.toString()); //Execute the insert statement stmt.execute(); con.commit(); textArea.append("One record has been added / updated \n"); } catch (Exception e) { textArea.append( "There was problem while adding / updating profile record in the database\n" ); textArea.append("Error message is \n"); textArea.append(e.toString() + "\n"); } finally { try { if (st != null) { st.close(); } } catch (Exception e1) { } } }

以下是将文档实例从数据库散集的代码:

private void createListFromDatabase() {
// Create a list instance
list = Collections.synchronizedList(new ArrayList());

Statement st = null;
ResultSet rs = null;
Unmarshaller u = null;
JAXBContext jc = null;

try {
//Create a JAXBContext instance
jc = JAXBContext.newInstance("jaxbderived.profile");

//Create unmarshaller object
u = jc.createUnmarshaller();
u.setValidating(false);
textArea.append("Reading records from the database \n");
st = con.createStatement();

//Select all records from profile_tab
rs = st.executeQuery(
"SELECT pt.c1.getStringVal() FROM profile_tab pt"
                );

int i = 0;

while (rs.next()) {
//Retrieve the XMLType object as a String
String s = rs.getString(1);

//Get byte array from the String object
byte[] bytes = s.getBytes();

//Create ByteArrayInputStream object
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);

try {
//Unmarshal the record
Record rec = (Record) u.unmarshal(new StreamSource(bais));
//Add the record to the list
list.add(rec);
} catch (Exception e1) {
textArea.append("There was an error while parsing " + i +
" th record from the result set \n" +
" This record has been skipped"
                    );
                }

i++;
            }

textArea.append("Number of records retrieved from the database :  " +
list.size() + "\n"
            );
listiterator = list.listIterator(0);

try {
listiterator.next();
} catch (Exception ex) {
            }

if (st != null) {
st.close();
            }
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (st != null) {
st.close();
                }
} catch (Exception ex1) {
            }
        }
    }


讨论此教程。 可打印版本 (PDF)。
这是目录页。 无上一页。 到上一级。 转至下一页。
寄送此页面
Printer View 打印机视图