Advanced Database Persistence for Java

Examples & Reference Manual

 

Example 9 - Retrieving Sequence Values

This example shows how to retrieve database sequence values. Even though most of the time sequences are used behind the scenes to insert table rows, the need to use them for other purposes may arise, such as for creating files, indentiying network communication and others.

Example Source Code

package examples;

import java.sql.SQLException;

import daos.ClientDAO;
import daos.DailyReportDAO;

/**
 * Example 09 - Retrieving Sequence Values
 * 
 * @author Vladimir Alarcon
 * 
 */
public class Example09 {

  public static void main(String[] args) throws SQLException {

    System.out.println("=== Running Example 09 - Retrieving Sequence Values ===");
    System.out.println(" ");

    // 1. Retrieve Sequence Value
    // Example: Retrieve a value from the sequence CLIENT_SEQ

    long value = ClientDAO.selectSequenceClientSeq();
    System.out.println("1. Retrieve Sequence Value - Retrieved CLIENT_SEQ value=" + value);

    // 2. Retrieve Sequence Value - Custom Method Name
    // Example: Retrieve a value from the sequence PDF_REPORT_FILE_SEQ

    long pdfSeq = DailyReportDAO.retrieveFileReportSequence();
    System.out.println("2. Retrieve Sequence Value - Custom Method Name - PDF_REPORT_FILE_SEQ value=" + pdfSeq);

    System.out.println(" ");
    System.out.println("=== Example 09 Complete ===");

  }

}

How to Run this example

The Example 09 is included in the download package. To run this example please refer to the section How to Run the Examples above.

Case #1: Retrieve a sequence value

This is demonstrated using the sequence CLIENT_SEQ . In order to do this the following extra tag is added to the CLIENT table definition:

    <sequence name="client_seq" />

This tag produces the new DAO method selectSequenceClientSeq() on the ClientDAO class.

Case #2: Retrieve a sequence value using custom method name

This is demonstrated using the sequence PDF_REPORT_FILE_SEQ . In order to do this the following extra tag is added to the DAILY_REPORT table definition:

    <sequence name="pdf_report_file_seq"
          java-method-name="retrieveFileReportSequence" />

This tag produces the new DAO method retrieveFileReportSequence() on the DailyReportDAO class.