Java Bean Persistence and JDBC Database Access

XML-Based Bean Persistence

Long-term persistence enables Java beans to be saved in XML format. The XMLEncoder and XMLDecoder classes facilitate this process by writing and reading bean representations in XML documents.

Encoding and Decoding Objects

The XMLEncoder class generates XML representations of serializable objects:

XMLEncoder xmlWriter = new XMLEncoder(
    new BufferedOutputStream(
    new FileOutputStream("BeanData.xml")));

xmlWriter.writeObject(beanInstance);
xmlWriter.close();

The XMLDecoder class reconstructs objects from XML documents:

XMLDecoder xmlReader = new XMLDecoder(
    new BufferedInputStream(
    new FileInputStream("BeanData.xml")));

Object restoredObject = xmlReader.readObject();
xmlReader.close();

XML Structure for Bean Archives

Bean XML archives use specific tags to represent object elements:

  • XML declaration specifying version and encoding
  • <java> root element containing all objects
  • <object> tags representing method calls needed for object reconstruction

Example object representation:

<object class="javax.swing.JButton" method="new">
    <string>Confirm</string>
</object>

Primitive type tags include:

  • <boolean>
  • <int>
  • <double>
  • Other basic type tags

Bean Customization

Customization allows modifying bean appearance and behavior in application builders. Two primary customization approaches are available:

Property Editors

Property editors customize specific property types. They must implement the PropertyEditor interface. The support class PropertyEditorSupport provides default implementations.

Example property editor implementation:

public void paintValue(Graphics g, Rectangle bounds) {
    Color original = g.getColor();
    g.setColor(Color.BLACK);
    g.drawRect(bounds.x, bounds.y, bounds.width-3, bounds.height-3);
    g.setColor(currentColor);
    g.fillRect(bounds.x+1, bounds.y+1, bounds.width-4, bounds.height-4);
    g.setColor(original);
}

Customizers

Customizers provide complete GUI control over bean configuration. All customizers must:

  • Extend java.awt.Component or its subclasses
  • Implement the Customizer interface
  • Provide a default constructor
  • Be associated with their target class via BeanInfo.getBeanDescriptor

JDBC Database Access

The JDBC API provides Java applications with access to relational databases. A typical JDBC workflow involves:

public void queryDatabase(String user, String pass) {
    Connection conn = DriverManager.getConnection(
        "jdbc:driver:database", user, pass);
    
    Statement st = conn.createStatement();
    ResultSet results = st.executeQuery("SELECT col1, col2 FROM Table");
    
    while (results.next()) {
        int value1 = results.getInt("col1");
        String value2 = results.getString("col2");
    }
}

JDBC Architecture Components

JDBC consists of four main components:

  • JDBC API - Provides programmatic access to relational data
  • Driver Manager - Manages connections between applications and JDBC drivers
  • Test Suite - Validtaes JDBC driver functionality
  • JDBC-ODBC Bridge - Provides JDBC access via ODBC drivers

Database Connection Methods

Applications can connect using either DriverManager or DataSource objects. DataSource is preferred as it offers connection pooling and distributed transaction support.

Example database connection setup:

// Using DriverManager
Connection conn = DriverManager.getConnection(url, username, password);

// Using DataSource
Context context = new InitialContext();
DataSource source = (DataSource)context.lookup("jdbc/database");
Connection pooledConn = source.getConnection(username, password);

Working with Result Sets

Result sets provide access to query results through a cursor mechanism:

Statement statement = connection.createStatement();
ResultSet data = statement.executeQuery("SELECT * FROM Products");

while (data.next()) {
    String productName = data.getString("PRODUCT_NAME");
    double price = data.getDouble("PRICE");
    // Process data
}

Transaction Management

Transactions maintain data consistency during concurrent database access. JDBC supports both local and distributed transactions.

connection.setAutoCommit(false);
try {
    // Execute multiple statements
    statement.executeUpdate("UPDATE Accounts SET balance = balance - 100");
    statement.executeUpdate("UPDATE Accounts SET balance = balance + 100");
    connection.commit();
} catch (SQLException e) {
    connection.rollback();
}

Data base Table Setup

Example table creation for a coffee shop database:

CREATE TABLE COFFEE_PRODUCTS (
    PRODUCT_NAME VARCHAR(32) NOT NULL,
    SUPPLIER_ID INTEGER NOT NULL,
    PRICE DECIMAL(10,2) NOT NULL,
    SALES_COUNT INTEGER NOT NULL,
    TOTAL_SALES INTEGER NOT NULL,
    PRIMARY KEY (PRODUCT_NAME),
    FOREIGN KEY (SUPPLIER_ID) REFERENCES SUPPLIERS(SUPPLIER_ID)
);

Exception Handling

JDBC operations throw SQLException when database errors occur. Proper expection handling includes:

try {
    // JDBC operations
} catch (SQLException error) {
    System.err.println("SQL State: " + error.getSQLState());
    System.err.println("Error Code: " + error.getErrorCode());
    System.err.println("Message: " + error.getMessage());
    
    Throwable cause = error.getCause();
    while (cause != null) {
        System.out.println("Cause: " + cause);
        cause = cause.getCause();
    }
}

Tags: JavaBeans XMLEncoder XMLDecoder JDBC DataSource

Posted on Mon, 18 May 2026 02:21:47 +0000 by wiley