Chapter 4 MySQL Cluster Connector for Java

Table of Contents

4.1 MySQL Cluster Connector for Java: Overview
4.1.1 MySQL Cluster Connector for Java Architecture
4.1.2 Java and NDB Cluster
4.1.3 The ClusterJ API and Data Object Model
4.2 Using MySQL Cluster Connector for Java
4.2.1 Getting, Installing, and Setting Up MySQL Cluster Connector for Java
4.2.2 Using ClusterJ
4.2.3 Using JPA with NDB Cluster
4.2.4 Using Connector/J with NDB Cluster
4.3 ClusterJ API Reference
4.3.1 com.mysql.clusterj
4.3.2 com.mysql.clusterj.annotation
4.3.3 com.mysql.clusterj.query
4.3.4 Constant field values
4.4 MySQL Cluster Connector for Java: Limitations and Known Issues

This chapter discusses using NDB Cluster with MySQL Cluster Connector for Java, which includes ClusterJ and ClusterJPA, a plugin for use with OpenJPA.

ClusterJ is a high level database API that is similar in style and concept to object-relational mapping persistence frameworks such as Hibernate and JPA. Because ClusterJ does not use the MySQL Server to access data in NDB Cluster, it can perform some operations much more quickly than can be done using JDBC. ClusterJ supports primary key and unique key operations and single-table queries; it does not support multi-table operations, including joins.

ClusterJPA is an OpenJPA implementation for NDB Cluster that attempts to offer the best possible performance by leveraging the strengths of both ClusterJ and JDBC. ID lookups and other such operations are performed using ClusterJ, while more complex queries that can benefit from the MySQL query optimizer are sent through the MySQL Server, using JDBC.

4.1 MySQL Cluster Connector for Java: Overview

This section provides a conceptual and architectural overview of the APIs available using the MySQL Cluster Connector for Java.

4.1.1 MySQL Cluster Connector for Java Architecture

MySQL Cluster Connector for Java is a collection of Java APIs for writing applications against NDB Cluster, including JDBC, JPA, and ClusterJ. These provide a number of different access paths and styles of access to NDB Cluster data. Section 4.1.2, “Java and NDB Cluster”, describes each of these APIs in more detail.

MySQL Cluster Connector for Java is included with all NDB Cluster source and binary releases. Building MySQL Cluster Connector for Java from source can be done as part of building NDB Cluster; however, it can also be built with Maven.

4.1.2 Java and NDB Cluster

A NDB Cluster is defined as one or more MySQL Servers providing access to an NDBCLUSTER storage engine—that is, to a set of NDB Cluster data nodes (ndbd processes). There are four main access paths from Java to NDBCLUSTER, listed here:

  • JDBC and mysqld.  JDBC works by sending SQL statements to the MySQL Server and returning result sets. When using JDBC, you must write the SQL, manage the connection, and copy any data from the result set that you want to use in your program as objects. The JDBC implementation most often used with the MySQL Server is MySQL Connector/J.

  • Java Persistence API (JPA) and JDBC.  JPA uses JDBC to connect to the MySQL Server. Unlike JDBC, JPA provides an object view of the data in the database.

  • ClusterJ.  ClusterJ uses a JNI bridge to the NDB API for direct access to NDBCLUSTER. It employs a style of data access that is based on a domain object model, similar in many ways to that employed by JPA. ClusterJ does not depend on the MySQL Server for data access.

  • ClusterJPA.  ClusterJPA is an adapter for the OpenJPA implementation. It can use either of two different access paths—JDBC or ClusterJ—to NDB Cluster data, depending on the type of operation to be performed. This can significantly improve performance for some uses, bypassing SQL, JDBC, and the MySQL Server entirely when it is more efficient to do so.

These paths are shown in the following API stack diagram:

Java access paths to NDB

JDBC and mysqld.  Connector/J provides standard access through the MySQL JDBC driver. Using Connector/J, JDBC applications can be written to work with a MySQL server acting as an NDB Cluster SQL node in much the same way that other Connector/J applications work with any other MySQL Server instance.

For more information, see Section 4.2.4, “Using Connector/J with NDB Cluster”.

ClusterJ.  ClusterJ is a native Java Connector for NDBCLUSTER (or NDB), the storage engine for NDB Cluster, in the style of Hibernate, JPA, and JDO. Like other persistence frameworks, ClusterJ uses the Data Mapper pattern, in which data is represented as domain objects, separate from business logic, mapping Java classes to database tables stored in the NDBCLUSTER storage engine.

Note

The NDBCLUSTER storage engine is often referred to (in MySQL documentation and elsewhere) simply as NDB. The terms NDB and NDBCLUSTER are synonymous, and you can use either ENGINE=NDB or ENGINE=NDBCLUSTER in a CREATE TABLE statement to create a clustered table.

ClusterJ does not need to connect to a mysqld process, having direct access to NDBCLUSTER using a JNI bridge that is included in the dynamic library libnbdclient. However, unlike JDBC, ClusterJ does not support table creation and other data definition operations; these must be performed by some other means, such as JDBC or the mysql client.

OpenJPA (ClusterJPA).  ClusterJPA is an adapter for OpenJPA that can also bypass JDBC and MySQL Server, using ClusterJ for fast-track access to the cluster. However, for complex queries (not primary key lookups) ClusterJPA uses JDBC.

OpenJPA is an implementation of the JPA (Java Persistence API) specification, which provides an object-relational persistence framework with relationships, inheritance, and persistent classes. See openjpa.apache.org, for more information about OpenJPA.

ClusterJ is independent of ClusterJPA as well as JDBC. However, ClusterJ can be used together with these APIs. Because ClusterJ is limited to queries on single tables, and does not support relations or inheritance, you should use JPA if you need support for these features in your applications.

For more information, see Section 4.2.3, “Using JPA with NDB Cluster”.

Differences Between ClusterJPA and ClusterJ.  While ClusterJPA and ClusterJ are similar in many ways, there are importance differences between the two, highlighted in the following list.

  • ClusterJPA supports persistent classes, whereas ClusterJ only supports persistent interfaces.

  • ClusterJPA supports relationships between persistent classes (typically modeled as logical foreign keys), whereas ClusterJ only supports single-valued fields directly mapped to database columns.

  • ClusterJPA makes it possible for you to formulate queries that contain joins based on relationships in the domain object model, while ClusterJ does not support either relationships or joins.

    However, once you retrieve instances using a JPA query, you can update or delete these using the fast path of ClusterJ.

  • ClusterJPA makes it possible to use the JPA API to declare some fields as lazily loaded, meaning that the data is only brought into memory when your program actually references it. ClusterJ, however, reads all mapped columns from the table whenever you access a row.

4.1.3 The ClusterJ API and Data Object Model

This section discusses the ClusterJ API and the object model used to represent the data handled by the application.

Application Programming Interface.  The ClusterJ API depends on 4 main interfaces: Session, SessionFactory, Transaction, and QueryBuilder.

Session interface.  All access to NDB Cluster data is done in the context of a session. The Session interface represents a user's or application's individual connection to an NDB Cluster. It contains methods for the following operations:

SessionFactory interface.  Sessions are obtained from a SessionFactory, of which there is typically a single instance for each NDB Cluster that you want to access from the Java VM. SessionFactory stores configuration information about the cluster, such as the hostname and port number of the NDB Cluster management server. It also stores parameters regarding how to connect to the cluster, including connection delays and timeouts. For more information about SessionFactory and its use in a ClusterJ application, see Getting the SessionFactory and getting a Session.

Transaction interface.  Transactions are not managed by the Session interface; like other modern application frameworks, ClusterJ separates transaction management from other persistence methods. Transaction demarcation might be done automatically by a container or in a web server servlet filter. Removing transaction completion methods from Session facilitates this separation of concerns.

The Transaction interface supports the standard begin, commit, and rollback behaviors required by a transactional database. In addition, it enables the user to mark a transaction as being rollback-only, which makes it possible for a component that is not responsible for completing a transaction to indicate that—due to an application or database error—the transaction must not be permitted to complete normally.

QueryBuilder interface.  The QueryBuilder interface makes it possible to construct criteria queries dynamically, using domain object model properties as query modeling elements. Comparisons between parameters and database column values can be specified, including equal, greater and less than, between, and in operations. These comparisons can be combined using methods corresponding to the Boolean operators AND, OR, and NOT. Comparison of values to NULL is also supported.

Data model.  ClusterJ provides access to data in NDB Cluster using domain objects, similar in many ways to the way that JPA models data.

In ClusterJ, the domain object mapping has the following characteristics:

  • All tables map to persistent interfaces. For every NDB table in the cluster, ClusterJ uses one or more interfaces. In many cases, a single interface is used; but for cases where different columns are needed by different parts of the application, multiple interfaces can be mapped to the same table.

    However, the classes themselves are not persistent.

  • Users map a subset of columns to persistent properties in interfaces. Thus, all properties map to columns; however, not all columns necessarily map to properties.

    All ClusterJ property names default to column names. The interface provides getter and setter methods for each property, with predictable corresponding method names.

  • Annotations on interfaces define mappings.

The user view of the application environment and domain objects is illustrated in the following diagram, which shows the logical relationships among the modeling elements of the ClusterJ interfaces:

ClusterJ user view of application and environment

The SessionFactory is configured by a properties object that might have been loaded from a file or constructed dynamically by the application using some other means (see Section 4.2.2.1, “Executing ClusterJ Applications and Sessions”).

The application obtains Session instances from the SessionFactory, with at most one thread working with a Session at a time. A thread can manage multiple Session instances if there is some application requirement for multiple connections to the database.

Each session has its own collection of domain objects, each of which represents the data from one row in the database. The domain objects can represent data in any of the following states:

  • New; not yet stored in the database

  • Retrieved from the database; available to the application

  • Updated; to be stored back in the database

  • To be deleted from the database

4.2 Using MySQL Cluster Connector for Java

This section provides basic information about building and running Java applications using MySQL Cluster Connector for Java.

4.2.1 Getting, Installing, and Setting Up MySQL Cluster Connector for Java

This section discusses how to obtain MySQL Cluster Connector for Java sources, binaries, compiling, installing, getting started.

Obtaining MySQL Cluster Connector for Java.  You can obtain the most recent NDB Cluster release incorporating MySQL Cluster Connector for Java from downloads.mysql.com.

Building and installing MySQL Cluster Connector for Java from source.  You can build and install ClusterJ, ClusterJPA, or both as part of building and installing NDB Cluster, which always requires you to configure the build using a --with-plugins option that causes NDB support to be included, such as --with-plugins=ndbcluster or --with-plugins=max. Other relevant plugin names that can be used with this option include the following:

  • clusterj: Required for building NDB Cluster with ClusterJ support.

  • openjpa: Required for building NDB Cluster with ClusterJPA support.

In addition, you should use the following two configure options when configuring a build to include ClusterJ, ClusterJPA, or both:

  • --with-classpath=path: Required for building NDB Cluster with ClusterJPA support. path must include the path or paths to the OpenJPA libraries and OpenJPA dependencies on your system.

  • --with-extra-charsets: ClusterJ uses the ucs2 character set for internal storage, and ClusterJ cannot be built without it. The simplest way to ensure that this character set is available is to configure using --with-extra-charsets=all. This is what we recommend that you use, unless you have some reason for not wanting to include all character sets, in which case you should make sure that ucs2 is specified in the character set list passed to this option.

A typical configuration step in building NDB Cluster with support for both ClusterJ and ClusterJPA might look like this:

shell> ./configure --with-plugins=ndbcluster,clusterj,openjpa \
  --with-extra-charsets=all  \
  --with-classpath=path/to/openjpa/libs \
  --prefix=path/to/install/directory

path/to/openjpa/libs must include the following:

  • openjpa-2.2.2.jar

  • driver-5.1.10.jar (This is the MySQL JDBC driver)

  • geronimo-jta_1.1_spec-1.1.jar

  • geronimo-jpa_3.0_spec-1.0.jar

  • serp-1.13.1.jar

  • commons-lang-2.1.jar

  • commons-collections-3.2.jar

Note

Not all available options for configuring an NDB Cluster build are shown in this section. For information about other options that can be used, see Installing MySQL Using a Development Source Tree, or consult the output of configure --help.

After configuring the build, run make and make install as you normally would to compile and install the NDB Cluster software. Following installation, the MySQL Cluster Connector for Java jar files can be found in share/mysql/java under the MySQL installation directory (by default, this is /usr/local/mysql/share/mysql/java).

You can also use the included file storage/ndb/clusterj/pom.xml for building ClusterJ with Maven. Setting up your build environment to use Maven requires that you run mvn install in the clusterj directory. Assuming that you are already in the root directory of the NDB Cluster source tree, you can accomplish this by performing in your shell the steps shown here:

cd storage/ndb/clusterj
mvn install
        

This causes ClusterJ—including the clusterj-jpa plugin—to be built, with the resulting .jar files installed in the local repository.

MySQL Cluster Connector for Java jar files.  After building and installing NDB Cluster with MySQL Cluster Connector for Java, you should find the following JAR files that are needed for using ClusterJ and ClusterJPA in share/mysql/java/ under the NDB Cluster installation directory:

  • clusterj-api.jar: This is the compile-time jar file, required for compiling ClusterJ application code.

  • clusterj.jar: This is the runtime library required for executing ClusterJ applications.

  • clusterjpa.jar: This is the runtime library required for executing ClusterJPA applications. This jar file must be in your classpath when running OpenJPA with ClusterJPA.

4.2.2 Using ClusterJ

This section provides basic information for writing, compiling, and executing applications that use ClusterJ. For the API documentation for ClusterJ, see Section 4.3, “ClusterJ API Reference”.

Requirements.  ClusterJ requires Java 1.5 or 1.6. NDB Cluster must be compiled with ClusterJ support; NDB Cluster binaries supplied by Oracle include ClusterJ support. If you are building NDB Cluster from source, see Building and installing MySQL Cluster Connector for Java from source, for information on configuring the build to enable ClusterJ support.

To compile applications that use ClusterJ, you need the clusterj-api jar file in your classpath. To run applications that use ClusterJ, you need the clusterj runtime jar file; in addition, libndbclient must be in the directory specified by java.library.path. Section 4.2.2.1, “Executing ClusterJ Applications and Sessions”, provides more information about these requirements.

4.2.2.1 Executing ClusterJ Applications and Sessions

In this section, we discuss how to start ClusterJ applications and the ClusterJ application environment.

Executing a ClusterJ application.  All of the ClusterJ jar files are normally found in share/mysql/java/ in the MySQL installation directory. When executing a ClusterJ application, you must set the classpath to point to these files. In addition, you must set java.library.path variable to point to the directory containing the Cluster ndbclient library, normally found in lib/mysql (also in the MySQL installation directory). Thus you might execute a ClusterJ program MyClusterJApp in a manner similar to what is shown here:

shell> java -classpath /usr/local/mysql/share/mysql/java/clusterj.jar \
              -Djava.library.path=/usr/local/mysql/lib MyClusterJApp
Note

The precise locations of the ClusterJ jar files and of libndbclient depend on how the NDB Cluster software was installed. See Installation Layouts, for more information.

ClusterJ encourages you to use different jar files at compile time and runtime. This is to remove the ability of applications to access implementation artifacts accidentally. ClusterJ is intended to be independent of the NDB Cluster software version, whereas the ndbclient layer is version-specific. This makes it possible to maintain a stable API, so that applications written against it using a given NDB Cluster version continue to run following an upgrade of the cluster to a new version.

Getting the SessionFactory and getting a Session.  SessionFactory is the source of all ClusterJ sessions that use a given NDB Cluster. Usually, there is only a single SessionFactory per NDB Cluster, per Java Virtual Machine.

SessionFactory can be configured by setting one or more properties. The preferred way to do this is by putting these in a properties file, like this:

com.mysql.clusterj.connectstring=localhost:1186
com.mysql.clusterj.database=mydb

The name of the properties file is arbitrary; howver, by convention, such files are named with a .properties extension. For ClusterJ applications, it is customary to name the file clusterj.properties.

After editing and saving the file, you can load the its contents into an instance of Properties, as shown here:

    
File propsFile = new File("clusterj.properties");
InputStream inStream = new FileInputStream(propsFile);
Properties props = new Properties();
props.load(inStream);

It is also possible to set these properties directly, without the use of a properties file:

Properties props = new Properties();

props.put("com.mysql.clusterj.connectstring", "localhost:1186");
props.put("com.mysql.clusterj.database", "mydb");

Once the properties have been set and loaded (using either of the techniques just shown), you can obtain a SessionFactory, and then from that a Session instance. For this, you use the SessionFactory's getSession() method, as shown here:

SessionFactory factory = ClusterJHelper.getSessionFactory(props);

Session session = factory.getSession();

It is usually sufficient to set and load the com.mysql.clusterj.connectstring and com.mysql.clusterj.database properties (and these properties, along with com.mysql.clusterj.max.transactions, cannot be changed after starting the SessionFactory). For a complete list of available SessionFactory properties and usual values, see com.mysql.clusterj.Constants.

Note

Session instances must not be shared among threads. Each thread in your application should use its own instance of Session.

For com.mysql.clusterj.connectstring, we use the default NDB Cluster connection string localhost:1186 (see NDB Cluster Connection Strings, for more information). For the value of com.mysql.clusterj.database, we use mydb in this example, but this value can be the name of any database containing NDB tables. For a listing of all SessionFactory properties that can be set in this manner, see com.mysql.clusterj.Constants.

Reconnecting to an NDB Cluster.  ClusterJ does not attempt to reconnect to an NDB Cluster once the connection is lost (error 4009) due to, for example, a network outage or the cluster going down. This, together with other errors, should be handled by the application with a common error handler. The handler needs to be able to detect and distinguish among three types of errors, and handle them accordingly:

  • Normal errors: These are errors at the application level (for example, those to deal with duplicate key, foreign key constraint, or timeout). They should be handled in application-specific ways, and, if resolved, the application can continue with the transaction.

  • Unexpected errors: These are failures to work with the cluster that cannot be accounted for by the conditions of the application, but are nonfatal. The application should close the ClusterJ session and reopen a new one.

  • Fatal errors: These are fatal errors like, for example, error 4009, Cluster Failure, which indicates a network outage or the cluster going down. The application should close the session and notify the rest of the application to shut down and then restart the SessionFactory.

    The restarting of the SessionFactory can be an automatic application function or a manual intervention. In either case, the code should wait until all sessions have been closed (that is, the public method getConnectionPoolSessionCounts() in the SessionFactory interface returns zeros for all pooled connections). Then the SessionFactory can be closed and reopened, and applications can start to get sessions again.

Logging.  ClusterJ uses Java logging. Here are some default settings for the ClusterJ logging, which are specified in the logging.properties file and can be modified there:

  • Logging level is set at INFO for all classes.

  • Using java.util.logging.FileHandler as the handler.

  • Default level for java.util.logging.FileHandler is set at FINEST

  • Using java.util.logging.SimpleFormatter as the formatter for the handler.

  • Log files are put inside the target directory under the current working directory, and file names are, generally, in the pattern of logNum, where Num is a unique number for resolving file name conflicts (see the Java documentation for java.util.logging.FileHandler for details).

The logging.properties file is located by default in the current working directory, but the location can be changed by specifying the system property java.util.logging.config.file when you start Java.

4.2.2.2 Creating tables

ClusterJ's main purpose is to read, write, and update row data in an existing database, rather than to perform DDL. You can create the employee table that matches this interface, using the following CREATE TABLE statement, in a MySQL client application such as mysql.

CREATE TABLE employee (
    id INT NOT NULL PRIMARY KEY,
    first VARCHAR(64) DEFAULT NULL,
    last VARCHAR(64) DEFAULT NULL,
    municipality VARCHAR(64) DEFAULT NULL,
    started DATE DEFAULT NULL,
    ended DATE DEFAULT NULL,
    department INT NOT NULL DEFAULT 1,
    UNIQUE KEY idx_u_hash (last,first USING HASH,
    KEY idx_municipality (municipality)
) ENGINE=NDBCLUSTER;

Now that the table has been created in NDB Cluster, you can map a ClusterJ interface to it using annotations. We show you how to do this in the next section.

4.2.2.3 Annotations

In ClusterJ (as in JPA), annotations are used to describe how the interface is mapped to tables in a database. An annotated interface looks like this:

@PersistenceCapable(table="employee")
@Index(name="idx_uhash")
public interface Employee {

    @PrimaryKey
    int getId();
    void setId(int id);

    String getFirst();
    void setFirst(String first);
    String getLast();
    void setLast(String last);
  
    @Column(name="municipality")  
    @Index(name="idx_municipality")
    String getCity();
    void setCity(String city);
  
    Date getStarted();
    void setStarted(Date date);
  
    Date getEnded();
    void setEnded(Date date);

    Integer getDepartment();
    void setDepartment(Integer department);
}

This interface maps seven columns: id, first, last, municipality started, ended, and department. The annotation @PersistenceCapable(table="employee") is used to let ClusterJ know which database table to map the Employee to (in this case, the employee table). The @Column annotation is used because the city property name implied by the getCity() and setCity() methods is different from the mapped column name municipality. The annotations @PrimaryKey and @Index inform ClusterJ about indexes in the database table.

The implementation of this interface is created dynamically by ClusterJ at runtime. When the newInstance() method is called, ClusterJ creates an implementation class for the Employee interface; this class stores the values in an internal object array.

ClusterJ does not require an annotation for every attribute. ClusterJ automatically detects the primary keys of tables; while there is an annotation in ClusterJ to permit the user to describe the primary keys of a table (see previous example), when specified, it is currently ignored. (The intended use of this annotation is for the generation of schemas from the domain object model interfaces, but this is not yet supported.)

The annotations themselves must be imported from the ClusterJ API. They can be found in package com.mysql.clusterj.annotation, and can be imported like this:

import com.mysql.clusterj.annotation.Column;
import com.mysql.clusterj.annotation.Index;
import com.mysql.clusterj.annotation.PersistenceCapable;
import com.mysql.clusterj.annotation.PrimaryKey;

4.2.2.4 ClusterJ Basic Operations

In this section, we describe how to perform operations basic to ClusterJ applications, including the following:

  • Creating new instances, setting their properties, and saving them to the database

  • Performing primary key lookups (reads)

  • Updating existing rows and saving the changes to the database

  • Deleting rows from the database

  • Constructing and executing queries to fetch a set of rows meeting certain criteria from the database

Creating new rows.  To insert a new row into the table, first create a new instance of Employee. This can be accomplished by calling the Session method newInstance(), as shown here:

Employee newEmployee = session.newInstance(Employee.class);

Set the Employee instance properties corresponding with the desired employee table columns. For example, the following sets the id, firstName, lastName, and started properties.

emp.setId(988);

newEmployee.setFirstName("John");
newEmployee.setLastName("Jones");

newEmployee.setStarted(new Date());

Once you are satisfied with the changes, you can persist the Employee instance, causing a new row containing the desired values to be inserted into the employee table, like this:

session.persist(newEmployee);

If autocommit is on, and a row with the same id as this instance of Employee already exists in the database, the persist() method fails. If autocommit is off and a row with the same id as this Employee instance already exists in the database, the persist() method succeeds but a subsequent commit() fails.

If you want the data to be saved even though the row already exists, use the savePersistent() method instead of the persist() method. The savePersistent() method updates an existing instance or creates a new instance as needed, without throwing an exception.

Values that you have not specified are stored with their Java default values (0 for integral types, 0.0 for numeric types, and null for reference types).

Primary key lookups.  You can find an existing row in an NDB table using the Session's find() method, like this:

Employee theEmployee = session.find(Employee.class, 988);

This is equivalent to the primary key lookup query SELECT * FROM employee WHERE id = 988.

ClusterJ also supports compound primary keys. The find() method can take an object array as a key, where the components of the object array are used to represent the primary key columns in the order they were declared. In addition, queries are optimized to detect whether columns of the primary key are specified as part of the query criteria, and if so, a primary key lookup or scan is executed as a strategy to implement the query.

Note

ClusterJ also supports multiple column ordered btree and unique hash indexes. As with primary keys, if a query specifies values for ordered or unique index fields, ClusterJ optimizes the query to use the index for scanning the table.

NDB Cluster automatically spreads table data across multiple data nodes. For some operations—find, insert, delete, and update—it is more efficient to tell the cluster on which data node the data is physically located, and to have the transaction execute on that data node. ClusterJ automatically detects the partition key; if the operation can be optimized for a specific data node, ClusterJ automatically starts the transaction on that node.

Update and save a row.  To update the value of a given column in the row that we just obtained as theEmployee, use the set*() method whose name corresponds to the name of that column. For example, to update the started date for this Employee, use the Employee's setStarted() method, as shown here:

theEmployee.setStarted(new Date(getMillisFor(2010, 01, 04)));
Note

For convenience, we use in this example a method getMillisFor(), which is defined as shown here, in the file AbstractClusterJModelTest.java (found in the storage/ndb/clusterj/clusterj-test/src/main/java/testsuite/clusterj directory of the NDB Cluster source tree):

      
/** Convert year, month, day into milliseconds after the Epoch, UTC.
* Set hours, minutes, seconds, and milliseconds to zero.
* @param year the year
* @param month the month (0 for January)
* @param day the day of the month
* @return
*/

protected static long getMillisFor(int year, int month, int day) {
  Calendar calendar = Calendar.getInstance();
  calendar.clear();
  calendar.set(Calendar.YEAR, year);
  calendar.set(Calendar.MONTH, month);
  calendar.set(Calendar.DATE, day);
  calendar.set(Calendar.HOUR, 0);
  calendar.set(Calendar.MINUTE, 0);
  calendar.set(Calendar.SECOND, 0);
  calendar.set(Calendar.MILLISECOND, 0);
  long result = calendar.getTimeInMillis();
  return result;
}

See the indicated file for further information.

You can update additional columns by invoking other Employee setter methods, like this:

theEmployee.setDepartment(3);

To save the changed row back to the NDB Cluster database, use the Session's updatePersistent() method, like this:

session.updatePersistent(theEmployee);

Deleting rows.  You can delete a single row easily using the deletePersistent() method of Session. In this example, we find the employee whose ID is 13, then delete this row from the employee table:

Employee exEmployee = session.find(Employee.class, 13);

session.deletePersistent(exEmployee);'

System.out.println("Deleted employee named " + exEmployee.getFirst()
                 + " " + exEmployee.getLast() + ".");

There also exists a method for deleting multiple rows, which provides two options:

  1. Delete all rows from a table.

  2. Delete an arbitrary collection of rows.

Both kinds of multi-row delete can be performed using the deletePersistentAll() method. The first variant of this method acts on a Class. For example, the following statement deletes all rows from the employee table and returns the number of rows deleted, as shown here:

int numberDeleted = session.deletePersistentAll(Employee);

System.out.println("There used to be "  + numberDeleted + " employees, but now there are none.");

The call to deletePersistentAll() just shown is equivalent to issuing the SQL statement DELETE FROM employee in the mysql client.

deletePersistentAll() can also be used to delete a collection of rows, as shown in this example:

//  Assemble the collection of rows to be deleted...

List<Employee> redundancies = new ArrayList<Employee>();

for (int i = 1000; i < 2000; i += 100) {
  Employee redundant = session.newInstance(Employee.class);
  redundant.setId(i);
  redundancies.add(redundant);
}

numberDeleted = session.deletePersistentAll(redundancies);

System.out.println("Deleted " + numberDeleted + " rows.");

It is not necessary to find the instances in the database before deleting them.

Writing queries.  The ClusterJ QueryBuilder interface is used to instantiate queries. The process begins with obtaining an instance of QueryBuilder, which is supplied by the current Session; we can then obtain a QueryDefinition, as shown here:

QueryBuilder builder = session.getQueryBuilder();

QueryDomainType<Employee> domain = builder.createQueryDefinition(Employee.class);

This is then used to set a column for comparison by the query. Here, we show how to prepare a query that compares the value of the employee table's department column with the constant value 8.

domain.where( domain.get("department").equal(domain.param("department") );

Query<Employee> query = session.createQuery(domain);

query.setParameter("department", 8);

To obtain the results from the query, invoke the Query's getResultList() method, as shown here;

List<Employee> results = query.getResultList();

The return value is a List that you can iterate over to retrieve and process the rows in the usual manner.

Transactions.  The Transaction interface can optionally be used to bound transactions, via the following methods:

It is also possible using Transaction to check whether the transaction is active (via the isActive() method, and to get and set a rollback-only flag (using getRollbackOnly() and setRollbackOnly(), respectively).

If you do not use the Transaction interface, methods in Session that affect the database—such as persist(), deletePersistent(), updatePersistent(), and so on—are automatically enclosed in a database transaction.

4.2.2.5 ClusterJ Mappings Between MySQL and Java Data Types

ClusterJ provides mappings for all of the common MySQL database types to Java types. Java object wrappers of primitive types should be mapped to nullable database columns.

Note

Since Java does not have native unsigned data types, UNSIGNED columns should be avoided in table schemas if possible.

Compatibility with JDBC mappings.  ClusterJ is implemented so as to be bug-compatible with the JDBC driver in terms of mapping from Java types to the database. That is, if you use ClusterJ to store or retrieve data, you obtain the same value as if you used the JDBC driver directly or through JPA.

The following tables show the mappings used by ClusterJ between common Java data types and MySQL column types. Separate tables are provided for numeric, floating-point, and variable-width types.

Numeric types.  This table shows the ClusterJ mappings between Java numeric data types and MySQL column types:

Date and time types.  The following table shows the ClusterJ mappings between Java date and time data types and MySQL column types:

Note

ClusterJ maps the MySQL YEAR type to a Java short (or java.lang.Short), as shown in the first table in this section.

java.util.Date represents date and time similar to the way in which Unix does so, but with more precision and a larger range. Where Unix represents a point in time as a 32-bit signed number of seconds since the Unix Epoch (01 January 1970), Java uses a 64-bit signed number of milliseconds since the Epoch.

Variable-width types.  The following table shows the ClusterJ mappings between Java data types and MySQL variable-width column types:

Java Data TypeMySQL Column Type
StringCHAR, VARCHAR, TEXT
byte[]BINARY, VARBINARY, BLOB
Note

No translation binary data is performed when mapping from MySQL BINARY, VARBINARY, or BLOB column values to Java byte arrays. Data is presented to the application exactly as it is stored.

4.2.3 Using JPA with NDB Cluster

ClusterJPA is implemented as a plugin for OpenJPA. The best way to use ClusterJPA is to start with the standard configuration of OpenJPA with JDBC and MySQL Server. Once you know that this configuration works for your application, you can switch to the ClusterJ code path.

Compiling applications for ClusterJPA is the same as compiling them for OpenJPA. To do this, you must have the following jar files in your classpath:

  • openjpa-2.2.2.jar

  • driver-5.1.10.jar (This is the MySQL JDBC driver)

  • geronimo-jta_1.1_spec-1.1.jar

  • geronimo-jpa_3.0_spec-1.0.jar

  • serp-1.13.1.jar

  • commons-lang-2.1.jar

  • commons-collections-3.2.jar

You must also have the OpenJPA jar files to run OpenJPA applications. To run them using ClusterJPA, you also need the clusterj.jar jar file in your classpath, as well as the MySQL Server JDBC connector jar file mysql-connector-j.jar (see Connector/J Installation), and your java.library.path must include the directory where libndbclient can be found.

You must also update the persistence.xml file, which selects the JPA implementation to be used by the application. The contents of a sample persistence.xml file are shown here (with the relevant portions shown in emphasized text):

<persistence-unit name="personnel" transaction-type="RESOURCE_LOCAL">
  <provider>
    org.apache.openjpa.persistence.PersistenceProviderImpl
  </provider>
  <class>com.mysql.clusterj.jpatest.model.Employee</class>
  <properties>
    <property name="openjpa.BrokerFactory" value="ndb"/>
    <property name="openjpa.ndb.connectString" value="localhost:1186"/>
    <property name="openjpa.ConnectionURL" value="jdbc:mysql://localhost:3306/test"/>
    <property name="openjpa.ConnectionDriverName" value="com.mysql.jdbc.Driver"/>
    <property name="openjpa.ConnectionRetainMode" value="transaction"/>
  </properties>
</persistence-unit>

To activate ClusterJPA, the property named openjpa.BrokerFactory must have the value ndb.

The name of the persistence unit is arbitrary; for this example, we have chosen personnel.

4.2.4 Using Connector/J with NDB Cluster

JDBC clients of an NDB Cluster data source, and using Connector/J 5.0.6 (or later), accept jdbc:mysql:loadbalance:// URLs (see Driver/Datasource Class Names, URL Syntax and Configuration Properties for Connector/J), with which you can take advantage of the ability to connect with multiple MySQL servers to achieve load balancing and failover.

However, while Connector/J does not depend on the MySQL client libraries, it does require a connection to a MySQL Server, which ClusterJ does not. JDBC also does not provide any object mappings for database objects, properties, or operations, or any way to persist objects.

See MySQL Connector/J 5.1 Developer Guide, for general information about using Connector/J.

4.3 ClusterJ API Reference

The following sections contain specifications for ClusterJ packages, interfaces, classes, and methods.

4.3.1 com.mysql.clusterj

Provides classes and interfaces for using NDB Cluster directly from Java.

  • A class for bootstrapping

  • Interfaces for use in application programs

  • Classes to define exceptions

This package contains three main groups of classes and interfaces:

4.3.1.1 Major Interfaces

ClusterJ provides these major interfaces for use by application programs: com.mysql.clusterj.SessionFactory, com.mysql.clusterj.Session, com.mysql.clusterj.Transaction, com.mysql.clusterj.query.QueryBuilder, and com.mysql.clusterj.Query. Bootstrapping The helper class com.mysql.clusterj.ClusterJHelper contains methods for creating the com.mysql.clusterj.SessionFactory. Bootstrapping is the process of identifying an NDB Cluster and obtaining the SessionFactory for use with the cluster. There is one SessionFactory per cluster per Java VM.

4.3.1.1.1 SessionFactory

The com.mysql.clusterj.SessionFactory is configured via properties, which identify the NDB Cluster that the application connects to:

  • com.mysql.clusterj.connectstring identifies the ndb_mgmd host name and port

  • com.mysql.clusterj.connect.retries is the number of retries when connecting

  • com.mysql.clusterj.connect.delay is the delay in seconds between connection retries

  • com.mysql.clusterj.connect.verbose tells whether to display a message to System.out while connecting

  • com.mysql.clusterj.connect.timeout.before is the number of seconds to wait until the first node responds to a connect request

  • com.mysql.clusterj.connect.timeout.after is the number of seconds to wait until the last node responds to a connect request

  • com.mysql.clusterj.connect.database is the name of the database to use

    File propsFile = new File("clusterj.properties");
    InputStream inStream = new FileInputStream(propsFile);
    Properties props = new Properties();
    props.load(inStream);
    SessionFactory sessionFactory = ClusterJHelper.getSessionFactory(props);

Session The com.mysql.clusterj.Session represents the user's individual connection to the cluster. It contains methods for:

  • finding persistent instances by primary key

  • persistent instance factory (newInstance)

  • persistent instance life cycle management (persist, remove)

  • getting the QueryBuilder

  • getting the Transaction (currentTransaction)

    Session session = sessionFactory.getSession();
    Employee existing = session.find(Employee.class, 1);
    if (existing != null) {
        session.remove(existing);
    }
    Employee newemp = session.newInstance(Employee.class);
    newemp.initialize(2, "Craig", 15, 146000.00);
    session.persist(newemp);

Transaction The com.mysql.clusterj.Transaction allows users to combine multiple operations into a single database transaction. It contains methods to:

  • begin a unit of work

  • commit changes from a unit of work

  • roll back all changes made since the unit of work was begun

  • mark a unit of work for rollback only

  • get the rollback status of the current unit of work

    Transaction tx = session.currentTransaction();
    tx.begin();
    Employee existing = session.find(Employee.class, 1);
    Employee newemp = session.newInstance(Employee.class);
    newemp.initialize(2, "Craig", 146000.00);
    session.persist(newemp);
    tx.commit();

QueryBuilder The com.mysql.clusterj.query.QueryBuilder allows users to build queries. It contains methods to:

  • define the Domain Object Model to query

  • compare properties with parameters using:

    • equal

    • lessThan

    • greaterThan

    • lessEqual

    • greaterEqual

    • between

    • in

  • combine comparisons using "and", "or", and "not" operators

    QueryBuilder builder = session.getQueryBuilder();
    QueryDomainType<Employee> qemp = builder.createQueryDefinition(Employee.class);
    Predicate service = qemp.get("yearsOfService").greaterThan(qemp.param("service"));
    Predicate salary = qemp.get("salary").lessEqual(qemp.param("salaryCap"));
    qemp.where(service.and(salary));
    Query<Employee> query = session.createQuery(qemp);
    query.setParameter("service", 10);
    query.setParameter("salaryCap", 180000.00);
    List<Employee> results = query.getResultList();

4.3.1.2 ClusterJDatastoreException

ClusterJUserException represents a database error. The underlying cause of the exception is contained in the "cause".

4.3.1.2.1 Synopsis
 public class ClusterJDatastoreException extends, ClusterJException {
// Public Constructors  public ClusterJDatastoreException(String message);
  public ClusterJDatastoreException(String msg,
                                    int code,
                                    int mysqlCode,
                                    int status,
                                    int classification);

  public ClusterJDatastoreException(String message,
                                    Throwable t);

  public ClusterJDatastoreException(Throwable t);
// Public Methods  public int getClassification();
  public int getCode();
  public int getMysqlCode();
  public int getStatus();
}

Methods inherited from com.mysql.clusterj.ClusterJException: printStackTrace

Methods inherited from java.lang.Throwable: addSuppressed , fillInStackTrace , getCause , getLocalizedMessage , getMessage , getStackTrace , getSuppressed , initCause , setStackTrace , toString

Methods inherited from java.lang.Object: equals , getClass , hashCode , notify , notifyAll , wait

Figure 4.1 ClusterJDatastoreException Class

ClusterJDatastoreException Class

4.3.1.2.2 getClassification()
public int getClassification();

Get the classification

4.3.1.2.3 getCode()
public int getCode();

Get the code

Since

7.3.15, 7.4.13, 7.5.4

4.3.1.2.4 getMysqlCode()
public int getMysqlCode();

Get the mysql code

Since

7.3.15, 7.4.13, 7.5.4

4.3.1.2.5 getStatus()
public int getStatus();

Get the status

4.3.1.3 ClusterJDatastoreException.Classification

Helper class for getClassification(). import com.mysql.clusterj.ClusterJDatastoreException.Classification; Classification c = Classification.lookup(datastoreException.getClassification()); System.out.println("exceptionClassification " + c + " with value " + c.value);

4.3.1.3.1 Synopsis
 public static final class ClusterJDatastoreException.Classification extends, Enum<Classification> {
// Public Static Fields  public static final Classification ApplicationError ;
  public static final Classification ConstraintViolation ;
  public static final Classification FunctionNotImplemented ;
  public static final Classification InsufficientSpace ;
  public static final Classification InternalError ;
  public static final Classification InternalTemporary ;
  public static final Classification NoDataFound ;
  public static final Classification NoError ;
  public static final Classification NodeRecoveryError ;
  public static final Classification NodeShutdown ;
  public static final Classification OverloadError ;
  public static final Classification SchemaError ;
  public static final Classification SchemaObjectExists ;
  public static final Classification TemporaryResourceError ;
  public static final Classification TimeoutExpired ;
  public static final Classification UnknownErrorCode ;
  public static final Classification UnknownResultError ;
  public static final Classification UserDefinedError ;
// Public Static Methods  public static Classification lookup(int value);
  public static Classification valueOf(String name);
  public static Classification[] values();
}

Methods inherited from java.lang.Enum: compareTo , equals , getDeclaringClass , hashCode , name , ordinal , toString , valueOf

Methods inherited from java.lang.Object: getClass , notify , notifyAll , wait

Since

7.3.15, 7.4.13, 7.5.4

Figure 4.2 ClusterJDatastoreException.Classification Class

ClusterJDatastoreException.Classification Class

4.3.1.3.2 lookup(int)
public static Classification lookup(int value);

Get the Classification enum for a value returned by ClusterJDatastoreException.getClassification().

Parameters

value

the classification returned by getClassification()

return

the Classification for the error

4.3.1.4 ClusterJException

ClusterJException is the base for all ClusterJ exceptions. Applications can catch ClusterJException to be notified of all ClusterJ reported issues.

  • User exceptions are caused by user error, for example providing a connect string that refers to an unavailable host or port.

  • Datastore exceptions report conditions that result from datastore operations after bootstrapping. For example, duplicate keys on insert, or record does not exist on delete. com.mysql.clusterj.ClusterJDatastoreException

  • Internal exceptions report conditions that are caused by errors in implementation. These exceptions should be reported as bugs. com.mysql.clusterj.ClusterJFatalInternalException

Exceptions are in three general categories: User exceptions, Datastore exceptions, and Internal exceptions.

4.3.1.4.1 Synopsis
 public class ClusterJException extends, RuntimeException {
// Public Constructors  public ClusterJException(String message);
  public ClusterJException(String message,
                           Throwable t);

  public ClusterJException(Throwable t);
// Public Methods  public synchronized void printStackTrace(PrintStream s);
}

Direct known subclasses: com.mysql.clusterj.ClusterJDatastoreException , com.mysql.clusterj.ClusterJFatalException , com.mysql.clusterj.ClusterJUserException

Methods inherited from java.lang.Throwable: addSuppressed , fillInStackTrace , getCause , getLocalizedMessage , getMessage , getStackTrace , getSuppressed , initCause , printStackTrace , setStackTrace , toString

Methods inherited from java.lang.Object: equals , getClass , hashCode , notify , notifyAll , wait

Figure 4.3 ClusterJException Class

ClusterJException Class

4.3.1.5 ClusterJFatalException

ClusterJFatalException represents an exception that is not recoverable.

4.3.1.5.1 Synopsis
 public class ClusterJFatalException extends, ClusterJException {
// Public Constructors  public ClusterJFatalException(String string);
  public ClusterJFatalException(String string,
                                Throwable t);

  public ClusterJFatalException(Throwable t);
}

Direct known subclasses: com.mysql.clusterj.ClusterJFatalInternalException , com.mysql.clusterj.ClusterJFatalUserException

Methods inherited from com.mysql.clusterj.ClusterJException: printStackTrace

Methods inherited from java.lang.Throwable: addSuppressed , fillInStackTrace , getCause , getLocalizedMessage , getMessage , getStackTrace , getSuppressed , initCause , setStackTrace , toString

Methods inherited from java.lang.Object: equals , getClass , hashCode , notify , notifyAll , wait

Figure 4.4 ClusterJFatalException Class

ClusterJFatalException Class

4.3.1.6 ClusterJFatalInternalException

ClusterJFatalInternalException represents an implementation error that the user cannot recover from.

4.3.1.6.1 Synopsis
 public class ClusterJFatalInternalException extends, ClusterJFatalException {
// Public Constructors  public ClusterJFatalInternalException(String string);
  public ClusterJFatalInternalException(String string,
                                        Throwable t);

  public ClusterJFatalInternalException(Throwable t);
}

Methods inherited from com.mysql.clusterj.ClusterJException: printStackTrace

Methods inherited from java.lang.Throwable: addSuppressed , fillInStackTrace , getCause , getLocalizedMessage , getMessage , getStackTrace , getSuppressed , initCause , setStackTrace , toString

Methods inherited from java.lang.Object: equals , getClass , hashCode , notify , notifyAll , wait

Figure 4.5 ClusterJFatalInternalException Class

ClusterJFatalInternalException Class

4.3.1.7 ClusterJFatalUserException

ClusterJFatalUserException represents a user error that is unrecoverable, such as programming errors in persistent classes or missing resources in the execution environment.

4.3.1.7.1 Synopsis
 public class ClusterJFatalUserException extends, ClusterJFatalException {
// Public Constructors  public ClusterJFatalUserException(String string);
  public ClusterJFatalUserException(String string,
                                    Throwable t);

  public ClusterJFatalUserException(Throwable t);
}

Methods inherited from com.mysql.clusterj.ClusterJException: printStackTrace

Methods inherited from java.lang.Throwable: addSuppressed , fillInStackTrace , getCause , getLocalizedMessage , getMessage , getStackTrace , getSuppressed , initCause , setStackTrace , toString

Methods inherited from java.lang.Object: equals , getClass , hashCode , notify , notifyAll , wait

Figure 4.6 ClusterJFatalUserException Class

ClusterJFatalUserException Class

4.3.1.8 ClusterJHelper

ClusterJHelper provides helper methods to bridge between the API and the implementation.

4.3.1.8.1 Synopsis
 public class ClusterJHelper {
// Public Constructors  public ClusterJHelper();
// Public Static Methods  public static boolean getBooleanProperty(String propertyName,
                                           String def);

  public static getServiceInstance(Class<T> cls);
  public static getServiceInstance(Class<T> cls,
                                     ClassLoader loader);

  public static getServiceInstance(Class<T> cls,
                                     String implementationClassName);

  public static getServiceInstance(Class<T> cls,
                                     String implementationClassName,
                                     ClassLoader loader);

  public static List<T> getServiceInstances(Class<T> cls,
                                            ClassLoader loader,
                                            StringBuffer errorMessages);

  public static SessionFactory getSessionFactory(Map props);
  public static SessionFactory getSessionFactory(Map props,
                                                 ClassLoader loader);

  public static String getStringProperty(String propertyName,
                                         String def);

  public static Dbug newDbug();
}

Methods inherited from java.lang.Object: equals , getClass , hashCode , notify , notifyAll , toString , wait

Figure 4.7 ClusterJHelper Class

ClusterJHelper Class

4.3.1.8.2 getBooleanProperty(String, String)
public static boolean getBooleanProperty(String propertyName,
                                         String def);

Get the named boolean property from either the environment or system properties. If the property is not 'true' then return false.

Parameters

propertyName

the name of the property

def

the default if the property is not set

return

the system property if it is set via -D or the system environment

4.3.1.8.3 getServiceInstance(Class<T>)
public static getServiceInstance(Class<T> cls);

Locate a service implementation by services lookup of the context class loader.

Parameters

cls

the class of the factory

return

the service instance

4.3.1.8.4 getServiceInstance(Class<T>, ClassLoader)
public static getServiceInstance(Class<T> cls,
                                   ClassLoader loader);

Locate a service implementation for a service by services lookup of a specific class loader. The first service instance found is returned.

Parameters

cls

the class of the factory

loader

the class loader for the factory implementation

return

the service instance

4.3.1.8.5 getServiceInstance(Class<T>, String)
public static getServiceInstance(Class<T> cls,
                                   String implementationClassName);

Locate a service implementation for a service. If the implementation name is not null, use it instead of looking up. If the implementation class is not loadable or does not implement the interface, throw an exception. Use the ClusterJHelper class loader to find the service.

Parameters

cls

implementationClassName

return

the implementation instance for a service

4.3.1.8.6 getServiceInstance(Class<T>, String, ClassLoader)
public static getServiceInstance(Class<T> cls,
                                   String implementationClassName,
                                   ClassLoader loader);

Locate a service implementation for a service. If the implementation name is not null, use it instead of looking up. If the implementation class is not loadable or does not implement the interface, throw an exception.

Parameters

cls

implementationClassName

name of implementation class to load

loader

the ClassLoader to use to find the service

return

the implementation instance for a service

4.3.1.8.7 getServiceInstances(Class<T>, ClassLoader, StringBuffer)
public static List<T> getServiceInstances(Class<T> cls,
                                          ClassLoader loader,
                                          StringBuffer errorMessages);

Locate all service implementations by services lookup of a specific class loader. Implementations in the services file are instantiated and returned. Failed instantiations are remembered in the errorMessages buffer.

Parameters

cls

the class of the factory

loader

the class loader for the factory implementation

errorMessages

a buffer used to hold the error messages

return

the service instance

4.3.1.8.8 getSessionFactory(Map)
public static SessionFactory getSessionFactory(Map props);

Locate a SessionFactory implementation by services lookup. The class loader used is the thread's context class loader.

Parameters

props

properties of the session factory

return

the session factory

Exceptions

ClusterFatalUserException

if the connection to the cluster cannot be made

4.3.1.8.9 getSessionFactory(Map, ClassLoader)
public static SessionFactory getSessionFactory(Map props,
                                               ClassLoader loader);

Locate a SessionFactory implementation by services lookup of a specific class loader. The properties are a Map that might contain implementation-specific properties plus standard properties.

Parameters

props

the properties for the factory

loader

the class loader for the factory implementation

return

the session factory

Exceptions

ClusterFatalUserException

if the connection to the cluster cannot be made

4.3.1.8.10 getStringProperty(String, String)
public static String getStringProperty(String propertyName,
                                       String def);

Get the named String property from either the environment or system properties.

Parameters

propertyName

the name of the property

def

the default if the property is not set

return

the system property if it is set via -D or the system environment

4.3.1.8.11 newDbug()
public static Dbug newDbug();

Return a new Dbug instance.

Parameters

return

a new Dbug instance

4.3.1.9 ClusterJUserException

ClusterJUserException represents a user programming error.

4.3.1.9.1 Synopsis
 public class ClusterJUserException extends, ClusterJException {
// Public Constructors  public ClusterJUserException(String message);
  public ClusterJUserException(String message,
                               Throwable t);

  public ClusterJUserException(Throwable t);
}

Methods inherited from com.mysql.clusterj.ClusterJException: printStackTrace

Methods inherited from java.lang.Throwable: addSuppressed , fillInStackTrace , getCause , getLocalizedMessage , getMessage , getStackTrace , getSuppressed , initCause , setStackTrace , toString

Methods inherited from java.lang.Object: equals , getClass , hashCode , notify , notifyAll , wait

Figure 4.8 ClusterJUserException Class

ClusterJUserException Class

4.3.1.10 ColumnMetadata

 public interface ColumnMetadata {
// Public Methods  public abstract String charsetName();
  public abstract ColumnType columnType();
  public abstract boolean isPartitionKey();
  public abstract boolean isPrimaryKey();
  public abstract Class<?> javaType();
  public abstract int maximumLength();
  public abstract String name();
  public abstract boolean nullable();
  public abstract int number();
  public abstract int precision();
  public abstract int scale();
}

Figure 4.9 ColumnMetadata Class

ColumnMetadata Class

4.3.1.10.1 charsetName()
public abstract String charsetName();

Return the charset name.

Parameters

return

the charset name

4.3.1.10.2 columnType()
public abstract ColumnType columnType();

Return the type of the column.

Parameters

return

the type of the column

4.3.1.10.3 isPartitionKey()
public abstract boolean isPartitionKey();

Return whether this column is a partition key column.

Parameters

return

true if this column is a partition key column

4.3.1.10.4 isPrimaryKey()
public abstract boolean isPrimaryKey();

Return whether this column is a primary key column.

Parameters

return

true if this column is a primary key column

4.3.1.10.5 javaType()
public abstract Class<?> javaType();

Return the java type of the column.

Parameters

return

the java type of the column

4.3.1.10.6 maximumLength()
public abstract int maximumLength();

Return the maximum number of bytes that can be stored in the column after translating the characters using the character set.

Parameters

return

the maximum number of bytes that can be stored in the column

4.3.1.10.7 name()
public abstract String name();

Return the name of the column.

Parameters

return

the name of the column

4.3.1.10.8 nullable()
public abstract boolean nullable();

Return whether this column is nullable.

Parameters

return

whether this column is nullable

4.3.1.10.9 number()
public abstract int number();

Return the column number. This number is used as the first parameter in the get and set methods of DynamicColumn.

Parameters

return

the column number.

4.3.1.10.10 precision()
public abstract int precision();

Return the precision of the column.

Parameters

return

the precision of the column

4.3.1.10.11 scale()
public abstract int scale();

Return the scale of the column.

Parameters

return

the scale of the column

4.3.1.11 ColumnType

This class enumerates the column types for columns in ndb.

4.3.1.11.1 Synopsis
 public final class ColumnType extends, Enum<ColumnType> {
// Public Static Fields  public static final ColumnType Bigint ;
  public static final ColumnType Bigunsigned ;
  public static final ColumnType Binary ;
  public static final ColumnType Bit ;
  public static final ColumnType Blob ;
  public static final ColumnType Char ;
  public static final ColumnType Date ;
  public static final ColumnType Datetime ;
  public static final ColumnType Datetime2 ;
  public static final ColumnType Decimal ;
  public static final ColumnType Decimalunsigned ;
  public static final ColumnType Double ;
  public static final ColumnType Float ;
  public static final ColumnType Int ;
  public static final ColumnType Longvarbinary ;
  public static final ColumnType Longvarchar ;
  public static final ColumnType Mediumint ;
  public static final ColumnType Mediumunsigned ;
  public static final ColumnType Olddecimal ;
  public static final ColumnType Olddecimalunsigned ;
  public static final ColumnType Smallint ;
  public static final ColumnType Smallunsigned ;
  public static final ColumnType Text ;
  public static final ColumnType Time ;
  public static final ColumnType Time2 ;
  public static final ColumnType Timestamp ;
  public static final ColumnType Timestamp2 ;
  public static final ColumnType Tinyint ;
  public static final ColumnType Tinyunsigned ;
  public static final ColumnType Undefined ;
  public static final ColumnType Unsigned ;
  public static final ColumnType Varbinary ;
  public static final ColumnType Varchar ;
  public static final ColumnType Year ;
// Public Static Methods  public static ColumnType valueOf(String name);
  public static ColumnType[] values();
}

Methods inherited from java.lang.Enum: compareTo , equals , getDeclaringClass , hashCode , name , ordinal , toString , valueOf

Methods inherited from java.lang.Object: getClass , notify , notifyAll , wait

Figure 4.10 ColumnType Class

ColumnType Class

4.3.1.12 Constants

4.3.1.12.1 Synopsis
4.3.1.12.2 DEFAULT_PROPERTY_CLUSTER_BYTE_BUFFER_POOL_SIZES
4.3.1.12.3 DEFAULT_PROPERTY_CLUSTER_CONNECT_AUTO_INCREMENT_BATCH_SIZE
4.3.1.12.4 DEFAULT_PROPERTY_CLUSTER_CONNECT_AUTO_INCREMENT_START
4.3.1.12.5 DEFAULT_PROPERTY_CLUSTER_CONNECT_AUTO_INCREMENT_STEP
4.3.1.12.6 DEFAULT_PROPERTY_CLUSTER_CONNECT_DELAY
4.3.1.12.7 DEFAULT_PROPERTY_CLUSTER_CONNECT_RETRIES
4.3.1.12.8 DEFAULT_PROPERTY_CLUSTER_CONNECT_TIMEOUT_AFTER
4.3.1.12.9 DEFAULT_PROPERTY_CLUSTER_CONNECT_TIMEOUT_BEFORE
4.3.1.12.10 DEFAULT_PROPERTY_CLUSTER_CONNECT_TIMEOUT_MGM
4.3.1.12.11 DEFAULT_PROPERTY_CLUSTER_CONNECT_VERBOSE
4.3.1.12.12 DEFAULT_PROPERTY_CLUSTER_DATABASE
4.3.1.12.13 DEFAULT_PROPERTY_CLUSTER_MAX_TRANSACTIONS
4.3.1.12.14 DEFAULT_PROPERTY_CONNECTION_POOL_SIZE
4.3.1.12.15 ENV_CLUSTERJ_LOGGER_FACTORY_NAME
4.3.1.12.16 PROPERTY_CLUSTER_BYTE_BUFFER_POOL_SIZES
4.3.1.12.17 PROPERTY_CLUSTER_CONNECT_AUTO_INCREMENT_BATCH_SIZE
4.3.1.12.18 PROPERTY_CLUSTER_CONNECT_AUTO_INCREMENT_START
4.3.1.12.19 PROPERTY_CLUSTER_CONNECT_AUTO_INCREMENT_STEP
4.3.1.12.20 PROPERTY_CLUSTER_CONNECT_DELAY
4.3.1.12.21 PROPERTY_CLUSTER_CONNECT_RETRIES
4.3.1.12.22 PROPERTY_CLUSTER_CONNECT_TIMEOUT_AFTER
4.3.1.12.23 PROPERTY_CLUSTER_CONNECT_TIMEOUT_BEFORE
4.3.1.12.24 PROPERTY_CLUSTER_CONNECT_TIMEOUT_MGM
4.3.1.12.25 PROPERTY_CLUSTER_CONNECT_VERBOSE
4.3.1.12.26 PROPERTY_CLUSTER_CONNECTION_SERVICE
4.3.1.12.27 PROPERTY_CLUSTER_CONNECTSTRING
4.3.1.12.28 PROPERTY_CLUSTER_DATABASE
4.3.1.12.29 PROPERTY_CLUSTER_MAX_TRANSACTIONS
4.3.1.12.30 PROPERTY_CONNECTION_POOL_NODEIDS
4.3.1.12.31 PROPERTY_CONNECTION_POOL_SIZE
4.3.1.12.32 PROPERTY_DEFER_CHANGES
4.3.1.12.33 PROPERTY_JDBC_DRIVER_NAME
4.3.1.12.34 PROPERTY_JDBC_PASSWORD
4.3.1.12.35 PROPERTY_JDBC_URL
4.3.1.12.36 PROPERTY_JDBC_USERNAME
4.3.1.12.37 SESSION_FACTORY_SERVICE_CLASS_NAME
4.3.1.12.38 SESSION_FACTORY_SERVICE_FILE_NAME

Constants used in the ClusterJ project.

4.3.1.12.1 Synopsis
 public interface Constants {
// Public Static Fields  public static final String DEFAULT_PROPERTY_CLUSTER_BYTE_BUFFER_POOL_SIZES = "256, 10240, 102400, 1048576";
  public static final int DEFAULT_PROPERTY_CLUSTER_CONNECT_AUTO_INCREMENT_BATCH_SIZE = 10;
  public static final long DEFAULT_PROPERTY_CLUSTER_CONNECT_AUTO_INCREMENT_START = 1L;
  public static final long DEFAULT_PROPERTY_CLUSTER_CONNECT_AUTO_INCREMENT_STEP = 1L;
  public static final int DEFAULT_PROPERTY_CLUSTER_CONNECT_DELAY = 5;
  public static final int DEFAULT_PROPERTY_CLUSTER_CONNECT_RETRIES = 4;
  public static final int DEFAULT_PROPERTY_CLUSTER_CONNECT_TIMEOUT_AFTER = 20;
  public static final int DEFAULT_PROPERTY_CLUSTER_CONNECT_TIMEOUT_BEFORE = 30;
  public static final int DEFAULT_PROPERTY_CLUSTER_CONNECT_TIMEOUT_MGM = 30000;
  public static final int DEFAULT_PROPERTY_CLUSTER_CONNECT_VERBOSE = 0;
  public static final String DEFAULT_PROPERTY_CLUSTER_DATABASE = "test";
  public static final int DEFAULT_PROPERTY_CLUSTER_MAX_TRANSACTIONS = 4;
  public static final int DEFAULT_PROPERTY_CONNECTION_POOL_SIZE = 1;
  public static final String ENV_CLUSTERJ_LOGGER_FACTORY_NAME = "CLUSTERJ_LOGGER_FACTORY";
  public static final String PROPERTY_CLUSTER_BYTE_BUFFER_POOL_SIZES = "com.mysql.clusterj.byte.buffer.pool.sizes";
  public static final String PROPERTY_CLUSTER_CONNECTION_SERVICE = "com.mysql.clusterj.connection.service";
  public static final String PROPERTY_CLUSTER_CONNECTSTRING = "com.mysql.clusterj.connectstring";
  public static final String PROPERTY_CLUSTER_CONNECT_AUTO_INCREMENT_BATCH_SIZE = "com.mysql.clusterj.connect.autoincrement.batchsize";
  public static final String PROPERTY_CLUSTER_CONNECT_AUTO_INCREMENT_START = "com.mysql.clusterj.connect.autoincrement.offset";
  public static final String PROPERTY_CLUSTER_CONNECT_AUTO_INCREMENT_STEP = "com.mysql.clusterj.connect.autoincrement.increment";
  public static final String PROPERTY_CLUSTER_CONNECT_DELAY = "com.mysql.clusterj.connect.delay";
  public static final String PROPERTY_CLUSTER_CONNECT_RETRIES = "com.mysql.clusterj.connect.retries";
  public static final String PROPERTY_CLUSTER_CONNECT_TIMEOUT_AFTER = "com.mysql.clusterj.connect.timeout.after";
  public static final String PROPERTY_CLUSTER_CONNECT_TIMEOUT_BEFORE = "com.mysql.clusterj.connect.timeout.before";
  public static final String PROPERTY_CLUSTER_CONNECT_TIMEOUT_MGM = "com.mysql.clusterj.connect.timeout.mgm";
  public static final String PROPERTY_CLUSTER_CONNECT_VERBOSE = "com.mysql.clusterj.connect.verbose";
  public static final String PROPERTY_CLUSTER_DATABASE = "com.mysql.clusterj.database";
  public static final String PROPERTY_CLUSTER_MAX_TRANSACTIONS = "com.mysql.clusterj.max.transactions";
  public static final String PROPERTY_CONNECTION_POOL_NODEIDS = "com.mysql.clusterj.connection.pool.nodeids";
  public static final String PROPERTY_CONNECTION_POOL_SIZE = "com.mysql.clusterj.connection.pool.size";
  public static final String PROPERTY_DEFER_CHANGES = "com.mysql.clusterj.defer.changes";
  public static final String PROPERTY_JDBC_DRIVER_NAME = "com.mysql.clusterj.jdbc.driver";
  public static final String PROPERTY_JDBC_PASSWORD = "com.mysql.clusterj.jdbc.password";
  public static final String PROPERTY_JDBC_URL = "com.mysql.clusterj.jdbc.url";
  public static final String PROPERTY_JDBC_USERNAME = "com.mysql.clusterj.jdbc.username";
  public static final String SESSION_FACTORY_SERVICE_CLASS_NAME = "com.mysql.clusterj.SessionFactoryService";
  public static final String SESSION_FACTORY_SERVICE_FILE_NAME = "META-INF/services/com.mysql.clusterj.SessionFactoryService";
}

Figure 4.11 Constants Class

Constants Class

4.3.1.12.2 DEFAULT_PROPERTY_CLUSTER_BYTE_BUFFER_POOL_SIZES
public static final String DEFAULT_PROPERTY_CLUSTER_BYTE_BUFFER_POOL_SIZES = "256, 10240, 102400, 1048576";

The default value of the byte buffer pool sizes property: 256, 10K, 100K, 1M

4.3.1.12.3 DEFAULT_PROPERTY_CLUSTER_CONNECT_AUTO_INCREMENT_BATCH_SIZE
public static final int DEFAULT_PROPERTY_CLUSTER_CONNECT_AUTO_INCREMENT_BATCH_SIZE = 10;

The default value of the connection delay property

4.3.1.12.4 DEFAULT_PROPERTY_CLUSTER_CONNECT_AUTO_INCREMENT_START
public static final long DEFAULT_PROPERTY_CLUSTER_CONNECT_AUTO_INCREMENT_START = 1L;

The default value of the connection autoincrement offset property

4.3.1.12.5 DEFAULT_PROPERTY_CLUSTER_CONNECT_AUTO_INCREMENT_STEP
public static final long DEFAULT_PROPERTY_CLUSTER_CONNECT_AUTO_INCREMENT_STEP = 1L;

The default value of the connection delay property

4.3.1.12.6 DEFAULT_PROPERTY_CLUSTER_CONNECT_DELAY
public static final int DEFAULT_PROPERTY_CLUSTER_CONNECT_DELAY = 5;

The default value of the connection delay property

4.3.1.12.7 DEFAULT_PROPERTY_CLUSTER_CONNECT_RETRIES
public static final int DEFAULT_PROPERTY_CLUSTER_CONNECT_RETRIES = 4;

The default value of the connection retries property

4.3.1.12.8 DEFAULT_PROPERTY_CLUSTER_CONNECT_TIMEOUT_AFTER
public static final int DEFAULT_PROPERTY_CLUSTER_CONNECT_TIMEOUT_AFTER = 20;

The default value of the connection timeout after property

4.3.1.12.9 DEFAULT_PROPERTY_CLUSTER_CONNECT_TIMEOUT_BEFORE
public static final int DEFAULT_PROPERTY_CLUSTER_CONNECT_TIMEOUT_BEFORE = 30;

The default value of the connection timeout before property

4.3.1.12.10 DEFAULT_PROPERTY_CLUSTER_CONNECT_TIMEOUT_MGM
public static final int DEFAULT_PROPERTY_CLUSTER_CONNECT_TIMEOUT_MGM = 30000;

The default value of the connection timeout mgm property

4.3.1.12.11 DEFAULT_PROPERTY_CLUSTER_CONNECT_VERBOSE
public static final int DEFAULT_PROPERTY_CLUSTER_CONNECT_VERBOSE = 0;

The default value of the connection verbose property

4.3.1.12.12 DEFAULT_PROPERTY_CLUSTER_DATABASE
public static final String DEFAULT_PROPERTY_CLUSTER_DATABASE = "test";

The default value of the database property

4.3.1.12.13 DEFAULT_PROPERTY_CLUSTER_MAX_TRANSACTIONS
public static final int DEFAULT_PROPERTY_CLUSTER_MAX_TRANSACTIONS = 4;

The default value of the maximum number of transactions property

4.3.1.12.14 DEFAULT_PROPERTY_CONNECTION_POOL_SIZE
public static final int DEFAULT_PROPERTY_CONNECTION_POOL_SIZE = 1;

The default value of the connection pool size property

4.3.1.12.15 ENV_CLUSTERJ_LOGGER_FACTORY_NAME
public static final String ENV_CLUSTERJ_LOGGER_FACTORY_NAME = "CLUSTERJ_LOGGER_FACTORY";

The name of the environment variable to set the logger factory

4.3.1.12.16 PROPERTY_CLUSTER_BYTE_BUFFER_POOL_SIZES
public static final String PROPERTY_CLUSTER_BYTE_BUFFER_POOL_SIZES = "com.mysql.clusterj.byte.buffer.pool.sizes";

The name of the byte buffer pool sizes property. To disable buffer pooling for blob objects, set the value of this property to "1". With this setting, buffers will be allocated and freed (and cleaned if possible) immediately after being used for blob data transfer.

4.3.1.12.17 PROPERTY_CLUSTER_CONNECT_AUTO_INCREMENT_BATCH_SIZE
public static final String PROPERTY_CLUSTER_CONNECT_AUTO_INCREMENT_BATCH_SIZE = "com.mysql.clusterj.connect.autoincrement.batchsize";

The name of the connection autoincrement batch size property. For details, see Ndb_cluster_connection::connect()

4.3.1.12.18 PROPERTY_CLUSTER_CONNECT_AUTO_INCREMENT_START
public static final String PROPERTY_CLUSTER_CONNECT_AUTO_INCREMENT_START = "com.mysql.clusterj.connect.autoincrement.offset";

The name of the connection autoincrement offset property. For details, see Ndb_cluster_connection::connect()

4.3.1.12.19 PROPERTY_CLUSTER_CONNECT_AUTO_INCREMENT_STEP
public static final String PROPERTY_CLUSTER_CONNECT_AUTO_INCREMENT_STEP = "com.mysql.clusterj.connect.autoincrement.increment";

The name of the connection autoincrement increment property. For details, see Ndb_cluster_connection::connect()

4.3.1.12.20 PROPERTY_CLUSTER_CONNECT_DELAY
public static final String PROPERTY_CLUSTER_CONNECT_DELAY = "com.mysql.clusterj.connect.delay";

The name of the connection delay property. For details, see Ndb_cluster_connection::connect()

4.3.1.12.21 PROPERTY_CLUSTER_CONNECT_RETRIES
public static final String PROPERTY_CLUSTER_CONNECT_RETRIES = "com.mysql.clusterj.connect.retries";

The name of the connection retries property. For details, see Ndb_cluster_connection::connect()

4.3.1.12.22 PROPERTY_CLUSTER_CONNECT_TIMEOUT_AFTER
public static final String PROPERTY_CLUSTER_CONNECT_TIMEOUT_AFTER = "com.mysql.clusterj.connect.timeout.after";

The name of the connection timeout after property. For details, see Ndb_cluster_connection::wait_until_ready()

4.3.1.12.23 PROPERTY_CLUSTER_CONNECT_TIMEOUT_BEFORE
public static final String PROPERTY_CLUSTER_CONNECT_TIMEOUT_BEFORE = "com.mysql.clusterj.connect.timeout.before";

The name of the connection timeout before property. For details, see Ndb_cluster_connection::wait_until_ready()

4.3.1.12.24 PROPERTY_CLUSTER_CONNECT_TIMEOUT_MGM
public static final String PROPERTY_CLUSTER_CONNECT_TIMEOUT_MGM = "com.mysql.clusterj.connect.timeout.mgm";

The name of the initial timeout for cluster connection to connect to MGM before connecting to data nodes Ndb_cluster_connection::set_timeout()

4.3.1.12.25 PROPERTY_CLUSTER_CONNECT_VERBOSE
public static final String PROPERTY_CLUSTER_CONNECT_VERBOSE = "com.mysql.clusterj.connect.verbose";

The name of the connection verbose property. For details, see Ndb_cluster_connection::connect()

4.3.1.12.26 PROPERTY_CLUSTER_CONNECTION_SERVICE
public static final String PROPERTY_CLUSTER_CONNECTION_SERVICE = "com.mysql.clusterj.connection.service";

The name of the connection service property

4.3.1.12.27 PROPERTY_CLUSTER_CONNECTSTRING
public static final String PROPERTY_CLUSTER_CONNECTSTRING = "com.mysql.clusterj.connectstring";

The name of the connection string property. For details, see Ndb_cluster_connection constructor

4.3.1.12.28 PROPERTY_CLUSTER_DATABASE
public static final String PROPERTY_CLUSTER_DATABASE = "com.mysql.clusterj.database";

The name of the database property. For details, see the catalogName parameter in the Ndb constructor. Ndb constructor

4.3.1.12.29 PROPERTY_CLUSTER_MAX_TRANSACTIONS
public static final String PROPERTY_CLUSTER_MAX_TRANSACTIONS = "com.mysql.clusterj.max.transactions";

The name of the maximum number of transactions property. For details, see Ndb::init()

4.3.1.12.30 PROPERTY_CONNECTION_POOL_NODEIDS
public static final String PROPERTY_CONNECTION_POOL_NODEIDS = "com.mysql.clusterj.connection.pool.nodeids";

The name of the connection pool node ids property. There is no default. This is the list of node ids to force the connections to be assigned to specific node ids. If this property is specified and connection pool size is not the default, the number of node ids of the list must match the connection pool size, or the number of node ids must be 1 and node ids will be assigned to connections starting with the specified node id.

4.3.1.12.31 PROPERTY_CONNECTION_POOL_SIZE
public static final String PROPERTY_CONNECTION_POOL_SIZE = "com.mysql.clusterj.connection.pool.size";

The name of the connection pool size property. This is the number of connections to create in the connection pool. The default is 1 (all sessions share the same connection; all requests for a SessionFactory with the same connect string and database will share a single SessionFactory). A setting of 0 disables pooling; each request for a SessionFactory will receive its own unique SessionFactory.

4.3.1.12.32 PROPERTY_DEFER_CHANGES
public static final String PROPERTY_DEFER_CHANGES = "com.mysql.clusterj.defer.changes";

The flag for deferred inserts, deletes, and updates

4.3.1.12.33 PROPERTY_JDBC_DRIVER_NAME
public static final String PROPERTY_JDBC_DRIVER_NAME = "com.mysql.clusterj.jdbc.driver";

The name of the jdbc driver

4.3.1.12.34 PROPERTY_JDBC_PASSWORD
public static final String PROPERTY_JDBC_PASSWORD = "com.mysql.clusterj.jdbc.password";

The jdbc password

4.3.1.12.35 PROPERTY_JDBC_URL
public static final String PROPERTY_JDBC_URL = "com.mysql.clusterj.jdbc.url";

The jdbc url

4.3.1.12.36 PROPERTY_JDBC_USERNAME
public static final String PROPERTY_JDBC_USERNAME = "com.mysql.clusterj.jdbc.username";

The jdbc username

4.3.1.12.37 SESSION_FACTORY_SERVICE_CLASS_NAME
public static final String SESSION_FACTORY_SERVICE_CLASS_NAME = "com.mysql.clusterj.SessionFactoryService";

The name of the session factory service interface

4.3.1.12.38 SESSION_FACTORY_SERVICE_FILE_NAME
public static final String SESSION_FACTORY_SERVICE_FILE_NAME = "META-INF/services/com.mysql.clusterj.SessionFactoryService";

The name of the files with names of implementation classes for session factory service

4.3.1.13 Dbug

Dbug allows clusterj applications to enable the DBUG functionality in cluster ndbapi library. The dbug state is a control string that consists of flags separated by colons. Flags are:

  • d set the debug flag

  • a[,filename] append debug output to the file

  • A[,filename] like a[,filename] but flush the output after each operation

  • d[,keyword[,keyword...]] enable output from macros with specified keywords

  • D[,tenths] delay for specified tenths of a second after each operation

  • f[,function[,function...]] limit output to the specified list of functions

  • F mark each output with the file name of the source file

  • i mark each output with the process id of the current process

  • g[,function[,function...]] profile specified list of functions

  • L mark each output with the line number of the source file

  • n mark each output with the current function nesting depth

  • N mark each output with a sequential number

  • o[,filename] overwrite debug output to the file

  • O[,filename] like o[,filename] but flush the output after each operation

  • p[,pid[,pid...]] limit output to specified list of process ids

  • P mark each output with the process name

  • r reset the indentation level to zero

  • t[,depth] limit function nesting to the specified depth

  • T mark each output with the current timestamp

For example, the control string to trace calls and output debug information only for "jointx" and overwrite the contents of file "/tmp/dbug/jointx", use "t:d,jointx:o,/tmp/dbug/jointx". The above can be written as ClusterJHelper.newDbug().trace().debug("jointx").output("/tmp/dbug/jointx").set();

4.3.1.13.1 Synopsis
 public interface Dbug {
// Public Methods  public abstract Dbug append(String fileName);
  public abstract Dbug debug(String string);
  public abstract Dbug debug(String[] strings);
  public abstract Dbug flush();
  public abstract String get();
  public abstract Dbug output(String fileName);
  public abstract void pop();
  public abstract void print(String keyword,
                             String message);

  public abstract void push();
  public abstract void push(String state);
  public abstract void set();
  public abstract void set(String state);
  public abstract Dbug trace();
}

Figure 4.12 Dbug Class

Dbug Class

4.3.1.13.2 append(String)
public abstract Dbug append(String fileName);

Specify the file name for debug output (append).

Parameters

fileName

the name of the file

return

this

4.3.1.13.3 debug(String)
public abstract Dbug debug(String string);

Set the list of debug keywords.

Parameters

string

the comma separated debug keywords

return

this

4.3.1.13.4 debug(String[])
public abstract Dbug debug(String[] strings);

Set the list of debug keywords.

Parameters

strings

the debug keywords

return

this

4.3.1.13.5 flush()
public abstract Dbug flush();

Force flush after each output operation.

Parameters

return

this

4.3.1.13.6 get()
public abstract String get();

Return the current state.

Parameters

return

the current state

4.3.1.13.7 output(String)
public abstract Dbug output(String fileName);

Specify the file name for debug output (overwrite).

Parameters

fileName

the name of the file

return

this

4.3.1.13.8 pop()
public abstract void pop();

Pop the current state. The new state will be the previously pushed state.

4.3.1.13.9 print(String, String)
public abstract void print(String keyword,
                           String message);

Print debug message.

4.3.1.13.10 push()
public abstract void push();

Push the current state as defined by the methods.

4.3.1.13.11 push(String)
public abstract void push(String state);

Push the current state and set the parameter as the new state.

Parameters

state

the new state

4.3.1.13.12 set()
public abstract void set();

Set the current state as defined by the methods.

4.3.1.13.13 set(String)
public abstract void set(String state);

Set the current state from the parameter.

Parameters

state

the new state

4.3.1.13.14 trace()
public abstract Dbug trace();

Set the trace flag.

Parameters

return

this

4.3.1.14 DynamicObject

 public abstract class DynamicObject {
// Public Constructors  public DynamicObject();
// Public Methods  public final ColumnMetadata[] columnMetadata();
  public final DynamicObjectDelegate delegate();
  public final void delegate(DynamicObjectDelegate delegate);
  public Boolean found();
  public final Object get(int columnNumber);
  public final void set(int columnNumber,
                        Object value);

  public String table();
}

Methods inherited from java.lang.Object: equals , getClass , hashCode , notify , notifyAll , toString , wait

Figure 4.13 DynamicObject Class

DynamicObject Class

4.3.1.15 DynamicObjectDelegate

 public interface DynamicObjectDelegate {
// Public Methods  public abstract ColumnMetadata[] columnMetadata();
  public abstract Boolean found();
  public abstract void found(Boolean found);
  public abstract Object get(int columnNumber);
  public abstract void release();
  public abstract void set(int columnNumber,
                           Object value);

  public abstract boolean wasReleased();
}

Figure 4.14 DynamicObjectDelegate Class

DynamicObjectDelegate Class

4.3.1.16 LockMode

Lock modes for read operations.

  • SHARED: Set a shared lock on rows

  • EXCLUSIVE: Set an exclusive lock on rows

  • READ_COMMITTED: Set no locks but read the most recent committed values

4.3.1.16.1 Synopsis
 public final class LockMode extends, Enum<LockMode> {
// Public Static Fields  public static final LockMode EXCLUSIVE ;
  public static final LockMode READ_COMMITTED ;
  public static final LockMode SHARED ;
// Public Static Methods  public static LockMode valueOf(String name);
  public static LockMode[] values();
}

Methods inherited from java.lang.Enum: compareTo , equals , getDeclaringClass , hashCode , name , ordinal , toString , valueOf

Methods inherited from java.lang.Object: getClass , notify , notifyAll , wait

Figure 4.15 LockMode Class

LockMode Class

4.3.1.17 Query

A Query instance represents a specific query with bound parameters. The instance is created by the method com.mysql.clusterj.Session.<T>createQuery(com.mysql.clusterj.query.QueryDefinition<T>).

4.3.1.17.1 Synopsis
 public interface Query<E> {
// Public Static Fields  public static final String INDEX_USED = "IndexUsed";
  public static final String SCAN_TYPE = "ScanType";
  public static final String SCAN_TYPE_INDEX_SCAN = "INDEX_SCAN";
  public static final String SCAN_TYPE_PRIMARY_KEY = "PRIMARY_KEY";
  public static final String SCAN_TYPE_TABLE_SCAN = "TABLE_SCAN";
  public static final String SCAN_TYPE_UNIQUE_KEY = "UNIQUE_KEY";
// Public Methods  public abstract int deletePersistentAll();
  public abstract Results<E> execute(Object parameter);
  public abstract Results<E> execute(Object[] parameters);
  public abstract Results<E> execute(Map<String, ?> parameters);
  public abstract Map<String, Object> explain();
  public abstract List<E> getResultList();
  public abstract void setLimits(long skip,
                                 long limit);

  public abstract void setOrdering(Ordering ordering,
                                   String[] orderingFields);

  public abstract void setParameter(String parameterName,
                                    Object value);

}

Figure 4.16 Query Class

Query Class

4.3.1.17.2 INDEX_USED
public static final String INDEX_USED = "IndexUsed";

The query explain index used key

4.3.1.17.3 SCAN_TYPE
public static final String SCAN_TYPE = "ScanType";

The query explain scan type key

4.3.1.17.4 SCAN_TYPE_INDEX_SCAN
public static final String SCAN_TYPE_INDEX_SCAN = "INDEX_SCAN";

The query explain scan type value for index scan

4.3.1.17.5 SCAN_TYPE_PRIMARY_KEY
public static final String SCAN_TYPE_PRIMARY_KEY = "PRIMARY_KEY";

The query explain scan type value for primary key

4.3.1.17.6 SCAN_TYPE_TABLE_SCAN
public static final String SCAN_TYPE_TABLE_SCAN = "TABLE_SCAN";

The query explain scan type value for table scan

4.3.1.17.7 SCAN_TYPE_UNIQUE_KEY
public static final String SCAN_TYPE_UNIQUE_KEY = "UNIQUE_KEY";

The query explain scan type value for unique key

4.3.1.17.8 deletePersistentAll()
public abstract int deletePersistentAll();

Delete the instances that satisfy the query criteria.

Parameters

return

the number of instances deleted

4.3.1.17.9 execute(Map<String, ?>)
public abstract Results<E> execute(Map<String, ?> parameters);

Execute the query with one or more named parameters. Parameters are resolved by name.

Parameters

parameters

the parameters

return

the result

4.3.1.17.10 execute(Object...)
public abstract Results<E> execute(Object[] parameters);

Execute the query with one or more parameters. Parameters are resolved in the order they were declared in the query.

Parameters

parameters

the parameters

return

the result

4.3.1.17.11 execute(Object)
public abstract Results<E> execute(Object parameter);

Execute the query with exactly one parameter.

Parameters

parameter

the parameter

return

the result

4.3.1.17.12 explain()
public abstract Map<String, Object> explain();

Explain how this query will be or was executed. If called before binding all parameters, throws ClusterJUserException. Return a map of key:value pairs that explain how the query will be or was executed. Details can be obtained by calling toString on the value. The following keys are returned:

  • ScanType: the type of scan, with values:

    • PRIMARY_KEY: the query used key lookup with the primary key

    • UNIQUE_KEY: the query used key lookup with a unique key

    • INDEX_SCAN: the query used a range scan with a non-unique key

    • TABLE_SCAN: the query used a table scan

  • IndexUsed: the name of the index used, if any

Parameters

return

the data about the execution of this query

Exceptions

ClusterJUserException

if not all parameters are bound

4.3.1.17.13 getResultList()
public abstract List<E> getResultList();

Get the results as a list.

Parameters

return

the result

Exceptions

ClusterJUserException

if not all parameters are bound

ClusterJDatastoreException

if an exception is reported by the datastore

4.3.1.17.14 setLimits(long, long)
public abstract void setLimits(long skip,
                               long limit);

Set limits on results to return. The execution of the query is modified to return only a subset of results. If the filter would normally return 100 instances, skip is set to 50, and limit is set to 40, then the first 50 results that would have been returned are skipped, the next 40 results are returned and the remaining 10 results are ignored.

Skip must be greater than or equal to 0. Limit must be greater than or equal to 0. Limits may not be used with deletePersistentAll.

Parameters

skip

the number of results to skip

limit

the number of results to return after skipping; use Long.MAX_VALUE for no limit.

4.3.1.17.15 setOrdering(Query.Ordering, String...)
public abstract void setOrdering(Ordering ordering,
                                 String[] orderingFields);

Set ordering for the results of this query. The execution of the query is modified to use an index previously defined.

  • There must be an index defined on the columns mapped to the ordering fields, in the order of the ordering fields.

  • There must be no gaps in the ordering fields relative to the index.

  • All ordering fields must be in the index, but not all fields in the index need be in the ordering fields.

  • If an "in" predicate is used in the filter on a field in the ordering, it can only be used with the first field.

  • If any of these conditions is violated, ClusterJUserException is thrown when the query is executed.

If an "in" predicate is used, each element in the parameter defines a separate range, and ordering is performed within that range. There may be a better (more efficient) index based on the filter, but specifying the ordering will force the query to use an index that contains the ordering fields.

Parameters

ordering

either Ordering.ASCENDING or Ordering.DESCENDING

orderingFields

the fields to order by

4.3.1.17.16 setParameter(String, Object)
public abstract void setParameter(String parameterName,
                                  Object value);

Set the value of a parameter. If called multiple times for the same parameter, silently replace the value.

Parameters

parameterName

the name of the parameter

value

the value for the parameter

4.3.1.18 Query.Ordering

Ordering

4.3.1.18.1 Synopsis
 public static final class Query.Ordering extends, Enum<Ordering> {
// Public Static Fields  public static final Ordering ASCENDING ;
  public static final Ordering DESCENDING ;
// Public Static Methods  public static Ordering valueOf(String name);
  public static Ordering[] values();
}

Methods inherited from java.lang.Enum: compareTo , equals , getDeclaringClass , hashCode , name , ordinal , toString , valueOf

Methods inherited from java.lang.Object: getClass , notify , notifyAll , wait

Figure 4.17 Query.Ordering Class

Query.Ordering Class

4.3.1.19 Results

Results of a query.

4.3.1.19.1 Synopsis
 public interface Results<E> extends, Iterable<E> {
// Public Methods  public abstract Iterator<E> iterator();
}

Figure 4.18 Results Class

Results Class

4.3.1.19.2 iterator()
public abstract Iterator<E> iterator();

Specified by: Method iterator in interface Iterable

Get an iterator over the results of a query.

Parameters

return

the iterator

4.3.1.20 Session

Session is the primary user interface to the cluster.

4.3.1.20.1 Synopsis
 public interface Session {
// Public Methods  public abstract void close();
  public abstract Query<T> createQuery(QueryDefinition<T> qd);
  public abstract Transaction currentTransaction();
  public abstract void deletePersistent(Class<T> cls,
                                        Object key);

  public abstract void deletePersistent(Object instance);
  public abstract int deletePersistentAll(Class<T> cls);
  public abstract void deletePersistentAll(Iterable<?> instances);
  public abstract find(Class<T> cls,
                         Object key);

  public abstract void flush();
  public abstract Boolean found(Object instance);
  public abstract QueryBuilder getQueryBuilder();
  public abstract boolean isClosed();
  public abstract load(instance);
  public abstract makePersistent(instance);
  public abstract Iterable<?> makePersistentAll(Iterable<?> instances);
  public abstract void markModified(Object instance,
                                    String fieldName);

  public abstract newInstance(Class<T> cls);
  public abstract newInstance(Class<T> cls,
                                Object key);

  public abstract void persist(Object instance);
  public abstract release(obj);
  public abstract void remove(Object instance);
  public abstract savePersistent(instance);
  public abstract Iterable<?> savePersistentAll(Iterable<?> instances);
  public abstract void setLockMode(LockMode lockmode);
  public abstract void setPartitionKey(Class<?> cls,
                                       Object key);

  public abstract String unloadSchema(Class<?> cls);
  public abstract void updatePersistent(Object instance);
  public abstract void updatePersistentAll(Iterable<?> instances);
}

Figure 4.19 Session Class

Session Class

4.3.1.20.2 close()
public abstract void close();

Close this session.

4.3.1.20.3 createQuery(QueryDefinition<T>)
public abstract Query<T> createQuery(QueryDefinition<T> qd);

Create a Query from a QueryDefinition.

Parameters

qd

the query definition

return

the query instance

4.3.1.20.4 currentTransaction()
public abstract Transaction currentTransaction();

Get the current com.mysql.clusterj.Transaction.

Parameters

return

the transaction

4.3.1.20.5 deletePersistent(Class<T>, Object)
public abstract void deletePersistent(Class<T> cls,
                                      Object key);

Delete an instance of a class from the database given its primary key. For single-column keys, the key parameter is a wrapper (e.g. Integer). For multi-column keys, the key parameter is an Object[] in which elements correspond to the primary keys in order as defined in the schema.

Parameters

cls

the interface or dynamic class

key

the primary key

4.3.1.20.6 deletePersistent(Object)
public abstract void deletePersistent(Object instance);

Delete the instance from the database. Only the id field is used to determine which instance is to be deleted. If the instance does not exist in the database, an exception is thrown.

Parameters

instance

the instance to delete

4.3.1.20.7 deletePersistentAll(Class<T>)
public abstract int deletePersistentAll(Class<T> cls);

Delete all instances of this class from the database. No exception is thrown even if there are no instances in the database.

Parameters

cls

the interface or dynamic class

return

the number of instances deleted

4.3.1.20.8 deletePersistentAll(Iterable<?>)
public abstract void deletePersistentAll(Iterable<?> instances);

Delete all parameter instances from the database.

Parameters

instances

the instances to delete

4.3.1.20.9 find(Class<T>, Object)
public abstract find(Class<T> cls,
                       Object key);

Find a specific instance by its primary key. The key must be of the same type as the primary key defined by the table corresponding to the cls parameter. The key parameter is the wrapped version of the primitive type of the key, e.g. Integer for INT key types, Long for BIGINT key types, or String for char and varchar types. For multi-column primary keys, the key parameter is an Object[], each element of which is a component of the primary key. The elements must be in the order of declaration of the columns (not necessarily the order defined in the CONSTRAINT ... PRIMARY KEY clause) of the CREATE TABLE statement.

Parameters

cls

the interface or dynamic class to find an instance of

key

the key of the instance to find

return

the instance of the interface or dynamic class with the specified key

4.3.1.20.10 flush()
public abstract void flush();

Flush deferred changes to the back end. Inserts, deletes, loads, and updates are sent to the back end.

4.3.1.20.11 found(Object)
public abstract Boolean found(Object instance);

Was the row corresponding to this instance found in the database?

Parameters

instance

the instance corresponding to the row in the database

return

  • null if the instance is null or was created via newInstance and never loaded;

  • true if the instance was returned from a find or query or created via newInstance and successfully loaded;

  • false if the instance was created via newInstance and not found.

4.3.1.20.12 getQueryBuilder()
public abstract QueryBuilder getQueryBuilder();

Get a QueryBuilder.

Parameters

return

the query builder

4.3.1.20.13 isClosed()
public abstract boolean isClosed();

Is this session closed?

Parameters

return

true if the session is closed

4.3.1.20.14 load(T)
public abstract load(instance);

Load the instance from the database into memory. Loading is asynchronous and will be executed when an operation requiring database access is executed: find, flush, or query. The instance must have been returned from find or query; or created via session.newInstance and its primary key initialized.

Parameters

instance

the instance to load

return

the instance

4.3.1.20.15 makePersistent(T)
public abstract makePersistent(instance);

Insert the instance into the database. If the instance already exists in the database, an exception is thrown.

Parameters

instance

the instance to insert

return

the instance

4.3.1.20.16 makePersistentAll(Iterable<?>)
public abstract Iterable<?> makePersistentAll(Iterable<?> instances);

Insert the instances into the database.

Parameters

instances

the instances to insert.

return

the instances

4.3.1.20.17 markModified(Object, String)
public abstract void markModified(Object instance,
                                  String fieldName);

Mark the field in the object as modified so it is flushed.

Parameters

instance

the persistent instance

fieldName

the field to mark as modified

4.3.1.20.18 newInstance(Class<T>)
public abstract newInstance(Class<T> cls);

Create an instance of an interface or dynamic class that maps to a table.

Parameters

cls

the interface for which to create an instance

return

an instance that implements the interface

4.3.1.20.19 newInstance(Class<T>, Object)
public abstract newInstance(Class<T> cls,
                              Object key);

Create an instance of an interface or dynamic class that maps to a table and set the primary key of the new instance. The new instance can be used to create, delete, or update a record in the database.

Parameters

cls

the interface for which to create an instance

return

an instance that implements the interface

4.3.1.20.20 persist(Object)
public abstract void persist(Object instance);

Insert the instance into the database. This method has identical semantics to makePersistent.

Parameters

instance

the instance to insert

4.3.1.20.21 release(T)
public abstract release(obj);

Release resources associated with an instance. The instance must be a domain object obtained via session.newInstance(T.class), find(T.class), or query; or Iterable, or array T[]. Resources released can include direct buffers used to hold instance data. Released resources may be returned to a pool.

Parameters

obj

a domain object of type T, an Iterable, or array T[]

return

the input parameter

Exceptions

ClusterJUserException

if the instance is not a domain object T, Iterable, or array T[], or if the object is used after calling this method.

4.3.1.20.22 remove(Object)
public abstract void remove(Object instance);

Delete the instance from the database. This method has identical semantics to deletePersistent.

Parameters

instance

the instance to delete

4.3.1.20.23 savePersistent(T)
public abstract savePersistent(instance);

Save the instance in the database without checking for existence. The id field is used to determine which instance is to be saved. If the instance exists in the database it will be updated. If the instance does not exist, it will be created.

Parameters

instance

the instance to update

4.3.1.20.24 savePersistentAll(Iterable<?>)
public abstract Iterable<?> savePersistentAll(Iterable<?> instances);

Update all parameter instances in the database.

Parameters

instances

the instances to update

4.3.1.20.25 setLockMode(LockMode)
public abstract void setLockMode(LockMode lockmode);

Set the lock mode for read operations. This will take effect immediately and will remain in effect until this session is closed or this method is called again.

Parameters

lockmode

the LockMode

4.3.1.20.26 setPartitionKey(Class<?>, Object)
public abstract void setPartitionKey(Class<?> cls,
                                     Object key);

Set the partition key for the next transaction. The key must be of the same type as the primary key defined by the table corresponding to the cls parameter. The key parameter is the wrapped version of the primitive type of the key, e.g. Integer for INT key types, Long for BIGINT key types, or String for char and varchar types. For multi-column primary keys, the key parameter is an Object[], each element of which is a component of the primary key. The elements must be in the order of declaration of the columns (not necessarily the order defined in the CONSTRAINT ... PRIMARY KEY clause) of the CREATE TABLE statement.

Parameters

key

the primary key of the mapped table

Exceptions

ClusterJUserException

if a transaction is enlisted

ClusterJUserException

if a partition key is null

ClusterJUserException

if called twice in the same transaction

ClusterJUserException

if a partition key is the wrong type

4.3.1.20.27 unloadSchema(Class<?>)
public abstract String unloadSchema(Class<?> cls);

Unload the schema definition for a class. This must be done after the schema definition has changed in the database due to an alter table command. The next time the class is used the schema will be reloaded.

Parameters

cls

the class for which the schema is unloaded

return

the name of the schema that was unloaded

4.3.1.20.28 updatePersistent(Object)
public abstract void updatePersistent(Object instance);

Update the instance in the database without necessarily retrieving it. The id field is used to determine which instance is to be updated. If the instance does not exist in the database, an exception is thrown. This method cannot be used to change the primary key.

Parameters

instance

the instance to update

4.3.1.20.29 updatePersistentAll(Iterable<?>)
public abstract void updatePersistentAll(Iterable<?> instances);

Update all parameter instances in the database.

Parameters

instances

the instances to update

4.3.1.21 SessionFactory

SessionFactory represents a cluster.

4.3.1.21.1 Synopsis
 public interface SessionFactory {
// Public Methods  public abstract void close();
  public abstract List<Integer> getConnectionPoolSessionCounts();
  public abstract Session getSession();
  public abstract Session getSession(Map properties);
}

Figure 4.20 SessionFactory Class

SessionFactory Class

4.3.1.21.2 close()
public abstract void close();

Close this session factory. Release all resources.

4.3.1.21.3 getConnectionPoolSessionCounts()
public abstract List<Integer> getConnectionPoolSessionCounts();

Get a list containing the number of open sessions for each connection in the connection pool.

Since

7.3.14, 7.4.12, 7.5.2

4.3.1.21.4 getSession()
public abstract Session getSession();

Create a Session to use with the cluster, using all the properties of the SessionFactory.

Parameters

return

the session

4.3.1.21.5 getSession(Map)
public abstract Session getSession(Map properties);

Create a session to use with the cluster, overriding some properties. Properties PROPERTY_CLUSTER_CONNECTSTRING, PROPERTY_CLUSTER_DATABASE, and PROPERTY_CLUSTER_MAX_TRANSACTIONS may not be overridden.

Parameters

properties

overriding some properties for this session

return

the session

4.3.1.22 SessionFactoryService

This interface defines the service to create a SessionFactory from a Map<String, String> of properties.

4.3.1.22.1 Synopsis
 public interface SessionFactoryService {
// Public Methods  public abstract SessionFactory getSessionFactory(Map<String, String> props);
}

Figure 4.21 SessionFactoryService Class

SessionFactoryService Class

4.3.1.22.2 getSessionFactory(Map<String, String>)
public abstract SessionFactory getSessionFactory(Map<String, String> props);

Create or get a session factory. If a session factory with the same value for PROPERTY_CLUSTER_CONNECTSTRING has already been created in the VM, the existing factory is returned, regardless of whether other properties of the factory are the same as specified in the Map.

Parameters

props

the properties for the session factory, in which the keys are defined in Constants and the values describe the environment

return

the session factory

4.3.1.23 Transaction

Transaction represents a user transaction active in the cluster.

4.3.1.23.1 Synopsis
 public interface Transaction {
// Public Methods  public abstract void begin();
  public abstract void commit();
  public abstract boolean getRollbackOnly();
  public abstract boolean isActive();
  public abstract void rollback();
  public abstract void setRollbackOnly();
}

Figure 4.22 Transaction Class

Transaction Class

4.3.1.23.2 begin()
public abstract void begin();

Begin a transaction.

4.3.1.23.3 commit()
public abstract void commit();

Commit a transaction.

4.3.1.23.4 getRollbackOnly()
public abstract boolean getRollbackOnly();

Has this transaction been marked for rollback only?

Parameters

return

true if the transaction has been marked for rollback only

4.3.1.23.5 isActive()
public abstract boolean isActive();

Is there a transaction currently active?

Parameters

return

true if a transaction is active

4.3.1.23.6 rollback()
public abstract void rollback();

Roll back a transaction.

4.3.1.23.7 setRollbackOnly()
public abstract void setRollbackOnly();

Mark this transaction as rollback only. After this method is called, commit() will roll back the transaction and throw an exception; rollback() will roll back the transaction and not throw an exception.

4.3.2 com.mysql.clusterj.annotation

This package provides annotations for domain object model interfaces mapped to database tables.

4.3.2.1 Column

Annotation for a column in the database.

4.3.2.1.1 Synopsis
 @Target(value={java.lang.annotation.ElementType.FIELD, java.lang.annotation.ElementType.METHOD}) @Retention(value=java.lang.annotation.RetentionPolicy.RUNTIME) public @interface Column {
  public String name ;
  public String allowsNull ;
  public String defaultValue ;
}

Figure 4.23 Column Class

Column Class

4.3.2.1.2 allowsNull

Whether the column allows null values to be inserted. This overrides the database definition and requires that the application provide non-null values for the database column.

Parameters

return

whether the column allows null values to be inserted

4.3.2.1.3 defaultValue

Default value for this column.

Parameters

return

the default value for this column

4.3.2.1.4 name

Name of the column.

Parameters

return

the name of the column

4.3.2.2 Columns

Annotation for a group of columns. This annotation is used for multi-column structures such as indexes and keys.

4.3.2.2.1 Synopsis
 @Target(value={java.lang.annotation.ElementType.FIELD, java.lang.annotation.ElementType.METHOD, java.lang.annotation.ElementType.TYPE}) @Retention(value=java.lang.annotation.RetentionPolicy.RUNTIME) public @interface Columns {
  public Column[] value ;
}

Figure 4.24 Columns Class

Columns Class

4.3.2.2.2 value

The columns annotation information.

Parameters

return

the columns

4.3.2.3 Extension

Annotation for a non-standard extension.

4.3.2.3.1 Synopsis
 @Target(value={java.lang.annotation.ElementType.TYPE, java.lang.annotation.ElementType.FIELD, java.lang.annotation.ElementType.METHOD}) @Retention(value=java.lang.annotation.RetentionPolicy.RUNTIME) public @interface Extension {
  public String vendorName ;
  public String key ;
  public String value ;
}

Figure 4.25 Extension Class

Extension Class

4.3.2.3.2 key

The key for the extension (required).

Parameters

return

the key

4.3.2.3.3 value

The value for the extension (required).

Parameters

return

the value

4.3.2.3.4 vendorName

Vendor that the extension applies to (required to make the key unique).

Parameters

return

the vendor

4.3.2.4 Extensions

Annotation for a group of extensions.

4.3.2.4.1 Synopsis
 @Target(value={java.lang.annotation.ElementType.TYPE, java.lang.annotation.ElementType.FIELD, java.lang.annotation.ElementType.METHOD}) @Retention(value=java.lang.annotation.RetentionPolicy.RUNTIME) public @interface Extensions {
  public Extension[] value ;
}

Figure 4.26 Extensions Class

Extensions Class

4.3.2.4.2 value

The extensions.

Parameters

return

the extensions

4.3.2.5 Index

Annotation for a database index.

4.3.2.5.1 Synopsis
 @Target(value={java.lang.annotation.ElementType.TYPE, java.lang.annotation.ElementType.FIELD, java.lang.annotation.ElementType.METHOD}) @Retention(value=java.lang.annotation.RetentionPolicy.RUNTIME) public @interface Index {
  public String name ;
  public String unique ;
  public Column[] columns ;
}

Figure 4.27 Index Class

Index Class

4.3.2.5.2 columns

Columns that compose this index.

Parameters

return

columns that compose this index

4.3.2.5.3 name

Name of the index

Parameters

return

the name of the index

4.3.2.5.4 unique

Whether this index is unique

Parameters

return

whether this index is unique

4.3.2.6 Indices

Annotation for a group of indices. This is used on a class where there are multiple indices defined.

4.3.2.6.1 Synopsis
 @Target(value=java.lang.annotation.ElementType.TYPE) @Retention(value=java.lang.annotation.RetentionPolicy.RUNTIME) public @interface Indices {
  public Index[] value ;
}

Figure 4.28 Indices Class

Indices Class

4.3.2.6.2 value

The indices.

Parameters

return

The indices

4.3.2.7 Lob

Annotation for a Large Object (lob). This annotation can be used with byte[] and InputStream types for binary columns; and with String and InputStream types for character columns.

4.3.2.7.1 Synopsis
 @Target(value={java.lang.annotation.ElementType.FIELD, java.lang.annotation.ElementType.METHOD}) @Retention(value=java.lang.annotation.RetentionPolicy.RUNTIME) public @interface Lob {
}

Figure 4.29 Lob Class

Lob Class

4.3.2.8 NotPersistent

Annotation to specify that the member is not persistent. If used, this is the only annotation allowed on a member.

4.3.2.8.1 Synopsis
 @Target(value={java.lang.annotation.ElementType.FIELD, java.lang.annotation.ElementType.METHOD}) @Retention(value=java.lang.annotation.RetentionPolicy.RUNTIME) public @interface NotPersistent {
}

Figure 4.30 NotPersistent Class

NotPersistent Class

4.3.2.9 NullValue

Enumeration of the "null-value" behavior values. This behavior is specified in the @Persistent annotation.

4.3.2.9.1 Synopsis
 public final class NullValue extends, Enum<NullValue> {
// Public Static Fields  public static final NullValue DEFAULT ;
  public static final NullValue EXCEPTION ;
  public static final NullValue NONE ;
// Public Static Methods  public static NullValue valueOf(String name);
  public static NullValue[] values();
}

Methods inherited from java.lang.Enum: compareTo , equals , getDeclaringClass , hashCode , name , ordinal , toString , valueOf

Methods inherited from java.lang.Object: getClass , notify , notifyAll , wait

Figure 4.31 NullValue Class

NullValue Class

4.3.2.10 PartitionKey

Annotation on a class or member to define the partition key. If annotating a class or interface, either a single column or multiple columns can be specified. If annotating a member, neither column nor columns should be specified.

4.3.2.10.1 Synopsis
 @Target(value={java.lang.annotation.ElementType.TYPE, java.lang.annotation.ElementType.FIELD, java.lang.annotation.ElementType.METHOD}) @Retention(value=java.lang.annotation.RetentionPolicy.RUNTIME) public @interface PartitionKey {
  public String column ;
  public Column[] columns ;
}

Figure 4.32 PartitionKey Class

PartitionKey Class

4.3.2.10.2 column

Name of the column to use for the partition key

Parameters

return

the name of the column to use for the partition key

4.3.2.10.3 columns

The column(s) for the partition key

Parameters

return

the column(s) for the partition key

4.3.2.11 PersistenceCapable

Annotation for whether the class or interface is persistence-capable.

4.3.2.11.1 Synopsis
 @Target(value=java.lang.annotation.ElementType.TYPE) @Retention(value=java.lang.annotation.RetentionPolicy.RUNTIME) public @interface PersistenceCapable {
  public String table ;
  public String database ;
  public String schema ;
}

Figure 4.33 PersistenceCapable Class

PersistenceCapable Class

4.3.2.12 PersistenceModifier

Enumeration of the persistence-modifier values for a member.

4.3.2.12.1 Synopsis
 public final class PersistenceModifier extends, Enum<PersistenceModifier> {
// Public Static Fields  public static final PersistenceModifier NONE ;
  public static final PersistenceModifier PERSISTENT ;
  public static final PersistenceModifier UNSPECIFIED ;
// Public Static Methods  public static PersistenceModifier valueOf(String name);
  public static PersistenceModifier[] values();
}

Methods inherited from java.lang.Enum: compareTo , equals , getDeclaringClass , hashCode , name , ordinal , toString , valueOf

Methods inherited from java.lang.Object: getClass , notify , notifyAll , wait

Figure 4.34 PersistenceModifier Class

PersistenceModifier Class

4.3.2.13 Persistent

Annotation for defining the persistence of a member.

4.3.2.13.1 Synopsis
 @Target(value={java.lang.annotation.ElementType.FIELD, java.lang.annotation.ElementType.METHOD}) @Retention(value=java.lang.annotation.RetentionPolicy.RUNTIME) public @interface Persistent {
  public NullValue nullValue ;
  public String primaryKey ;
  public String column ;
  public Extension[] extensions ;
}

Figure 4.35 Persistent Class

Persistent Class

4.3.2.13.2 column

Column name where the values are stored for this member.

Parameters

return

the name of the column

4.3.2.13.3 extensions

Non-standard extensions for this member.

Parameters

return

the non-standard extensions

4.3.2.13.4 nullValue

Behavior when this member contains a null value.

Parameters

return

the behavior when this member contains a null value

4.3.2.13.5 primaryKey

Whether this member is part of the primary key for the table. This is equivalent to specifying @PrimaryKey as a separate annotation on the member.

Parameters

return

whether this member is part of the primary key

4.3.2.14 PrimaryKey

Annotation on a member to define it as a primary key member of a class or persistent interface.

4.3.2.14.1 Synopsis
 @Target(value={java.lang.annotation.ElementType.TYPE, java.lang.annotation.ElementType.FIELD, java.lang.annotation.ElementType.METHOD}) @Retention(value=java.lang.annotation.RetentionPolicy.RUNTIME) public @interface PrimaryKey {
  public String name ;
  public String column ;
  public Column[] columns ;
}

Figure 4.36 PrimaryKey Class

PrimaryKey Class

4.3.2.14.2 column

Name of the column to use for the primary key

Parameters

return

the name of the column to use for the primary key

4.3.2.14.3 columns

The column(s) for the primary key

Parameters

return

the column(s) for the primary key

4.3.2.14.4 name

Name of the primary key constraint

Parameters

return

the name of the primary key constraint

4.3.3 com.mysql.clusterj.query

Provides interfaces for building queries for ClusterJ.

4.3.3.1 Predicate

Used to combine multiple predicates with boolean operations.

4.3.3.1.1 Synopsis
 public interface Predicate {
// Public Methods  public abstract Predicate and(Predicate predicate);
  public abstract Predicate not();
  public abstract Predicate or(Predicate predicate);
}

Figure 4.37 Predicate Class

Predicate Class

4.3.3.1.2 and(Predicate)
public abstract Predicate and(Predicate predicate);

Combine this Predicate with another, using the "and" semantic.

Parameters

predicate

the other predicate

return

a new Predicate combining both Predicates

4.3.3.1.3 not()
public abstract Predicate not();

Negate this Predicate.

Parameters

return

this predicate

4.3.3.1.4 or(Predicate)
public abstract Predicate or(Predicate predicate);

Combine this Predicate with another, using the "or" semantic.

Parameters

predicate

the other predicate

return

a new Predicate combining both Predicates

4.3.3.2 PredicateOperand

PredicateOperand represents a column or parameter that can be compared to another

4.3.3.2.1 Synopsis
 public interface PredicateOperand {
// Public Methods  public abstract Predicate between(PredicateOperand lower,
                                    PredicateOperand upper);

  public abstract Predicate equal(PredicateOperand other);
  public abstract Predicate greaterEqual(PredicateOperand other);
  public abstract Predicate greaterThan(PredicateOperand other);
  public abstract Predicate in(PredicateOperand other);
  public abstract Predicate isNotNull();
  public abstract Predicate isNull();
  public abstract Predicate lessEqual(PredicateOperand other);
  public abstract Predicate lessThan(PredicateOperand other);
  public abstract Predicate like(PredicateOperand other);
}

Figure 4.38 PredicateOperand Class

PredicateOperand Class

4.3.3.2.2 between(PredicateOperand, PredicateOperand)
public abstract Predicate between(PredicateOperand lower,
                                  PredicateOperand upper);

Return a Predicate representing comparing this to another using "between" semantics.

Parameters

lower

another PredicateOperand

upper

another PredicateOperand

return

a new Predicate

4.3.3.2.3 equal(PredicateOperand)
public abstract Predicate equal(PredicateOperand other);

Return a Predicate representing comparing this to another using "equal to" semantics.

Parameters

other

the other PredicateOperand

return

a new Predicate

4.3.3.2.4 greaterEqual(PredicateOperand)
public abstract Predicate greaterEqual(PredicateOperand other);

Return a Predicate representing comparing this to another using "greater than or equal to" semantics.

Parameters

other

the other PredicateOperand

return

a new Predicate

4.3.3.2.5 greaterThan(PredicateOperand)
public abstract Predicate greaterThan(PredicateOperand other);

Return a Predicate representing comparing this to another using "greater than" semantics.

Parameters

other

the other PredicateOperand

return

a new Predicate

4.3.3.2.6 in(PredicateOperand)
public abstract Predicate in(PredicateOperand other);

Return a Predicate representing comparing this to a collection of values using "in" semantics.

Parameters

other

another PredicateOperand

return

a new Predicate

4.3.3.2.7 isNotNull()
public abstract Predicate isNotNull();

Return a Predicate representing comparing this to not null.

Parameters

return

a new Predicate

4.3.3.2.8 isNull()
public abstract Predicate isNull();

Return a Predicate representing comparing this to null.

Parameters

return

a new Predicate

4.3.3.2.9 lessEqual(PredicateOperand)
public abstract Predicate lessEqual(PredicateOperand other);

Return a Predicate representing comparing this to another using "less than or equal to" semantics.

Parameters

other

the other PredicateOperand

return

a new Predicate

4.3.3.2.10 lessThan(PredicateOperand)
public abstract Predicate lessThan(PredicateOperand other);

Return a Predicate representing comparing this to another using "less than" semantics.

Parameters

other

the other PredicateOperand

return

a new Predicate

4.3.3.2.11 like(PredicateOperand)
public abstract Predicate like(PredicateOperand other);

Return a Predicate representing comparing this to another using "like" semantics.

Parameters

other

another PredicateOperand

return

a new Predicate

4.3.3.3 QueryBuilder

QueryBuilder represents a factory for queries.

4.3.3.3.1 Synopsis
 public interface QueryBuilder {
// Public Methods  public abstract QueryDomainType<T> createQueryDefinition(Class<T> cls);
}

Figure 4.39 QueryBuilder Class

QueryBuilder Class

4.3.3.3.2 createQueryDefinition(Class<T>)
public abstract QueryDomainType<T> createQueryDefinition(Class<T> cls);

Create a QueryDefinition to define queries.

Parameters

cls

the class of the type to be queried

return

the QueryDomainType to define the query

4.3.3.4 QueryDefinition

QueryDefinition allows users to define queries.

4.3.3.4.1 Synopsis
 public interface QueryDefinition<E> {
// Public Methods  public abstract Predicate not(Predicate predicate);
  public abstract PredicateOperand param(String parameterName);
  public abstract QueryDefinition<E> where(Predicate predicate);
}

Figure 4.40 QueryDefinition Class

QueryDefinition Class

4.3.3.4.2 not(Predicate)
public abstract Predicate not(Predicate predicate);

Convenience method to negate a predicate.

Parameters

predicate

the predicate to negate

return

the inverted predicate

4.3.3.4.3 param(String)
public abstract PredicateOperand param(String parameterName);

Specify a parameter for the query.

Parameters

parameterName

the name of the parameter

return

the PredicateOperand representing the parameter

4.3.3.4.4 where(Predicate)
public abstract QueryDefinition<E> where(Predicate predicate);

Specify the predicate to satisfy the query.

Parameters

predicate

the Predicate

return

this query definition

4.3.3.5 QueryDomainType

QueryDomainType represents the domain type of a query. The domain type validates property names that are used to filter results.

4.3.3.5.1 Synopsis
 public interface QueryDomainType<E> extends, QueryDefinition<E> {
// Public Methods  public abstract PredicateOperand get(String propertyName);
  public abstract Class<E> getType();
}

Figure 4.41 QueryDomainType Class

QueryDomainType Class

4.3.3.5.2 get(String)
public abstract PredicateOperand get(String propertyName);

Get a PredicateOperand representing a property of the domain type.

Parameters

propertyName

the name of the property

return

a representation the value of the property

4.3.3.5.3 getType()
public abstract Class<E> getType();

Get the domain type of the query.

Parameters

return

the domain type of the query

4.3.4 Constant field values

4.3.4.1 com.mysql.clusterj.*

Table 4.1 com.mysql.clusterj.* Constants and Default Values

Name:

Default Value:

Name: DEFAULT_PROPERTY_CLUSTER_BYTE_BUFFER_POOL_SIZES

Default Value: "256, 10240, 102400, 1048576"

Name: DEFAULT_PROPERTY_CLUSTER_CONNECT_AUTO_INCREMENT_BATCH_SIZE

Default Value: 10

Name: DEFAULT_PROPERTY_CLUSTER_CONNECT_AUTO_INCREMENT_START

Default Value: 1

Name: DEFAULT_PROPERTY_CLUSTER_CONNECT_AUTO_INCREMENT_STEP

Default Value: 1

Name: DEFAULT_PROPERTY_CLUSTER_CONNECT_DELAY

Default Value: 5

Name: DEFAULT_PROPERTY_CLUSTER_CONNECT_RETRIES

Default Value: 4

Name: DEFAULT_PROPERTY_CLUSTER_CONNECT_TIMEOUT_AFTER

Default Value: 20

Name: DEFAULT_PROPERTY_CLUSTER_CONNECT_TIMEOUT_BEFORE

Default Value: 30

Name: DEFAULT_PROPERTY_CLUSTER_CONNECT_TIMEOUT_MGM

Default Value: 30000

Name: DEFAULT_PROPERTY_CLUSTER_CONNECT_VERBOSE

Default Value: 0

Name: DEFAULT_PROPERTY_CLUSTER_DATABASE

Default Value: "test"

Name: DEFAULT_PROPERTY_CLUSTER_MAX_TRANSACTIONS

Default Value: 4

Name: DEFAULT_PROPERTY_CONNECTION_POOL_SIZE

Default Value: 1

Name: ENV_CLUSTERJ_LOGGER_FACTORY_NAME

Default Value: "CLUSTERJ_LOGGER_FACTORY"

Name: PROPERTY_CLUSTER_BYTE_BUFFER_POOL_SIZES

Default Value: "com.mysql.clusterj.byte.buffer.pool.sizes"

Name: PROPERTY_CLUSTER_CONNECTION_SERVICE

Default Value: "com.mysql.clusterj.connection.service"

Name: PROPERTY_CLUSTER_CONNECTSTRING

Default Value: "com.mysql.clusterj.connectstring"

Name: PROPERTY_CLUSTER_CONNECT_AUTO_INCREMENT_BATCH_SIZE

Default Value: "com.mysql.clusterj.connect.autoincrement.batchsize"

Name: PROPERTY_CLUSTER_CONNECT_AUTO_INCREMENT_START

Default Value: "com.mysql.clusterj.connect.autoincrement.offset"

Name: PROPERTY_CLUSTER_CONNECT_AUTO_INCREMENT_STEP

Default Value: "com.mysql.clusterj.connect.autoincrement.increment"

Name: PROPERTY_CLUSTER_CONNECT_DELAY

Default Value: "com.mysql.clusterj.connect.delay"

Name: PROPERTY_CLUSTER_CONNECT_RETRIES

Default Value: "com.mysql.clusterj.connect.retries"

Name: PROPERTY_CLUSTER_CONNECT_TIMEOUT_AFTER

Default Value: "com.mysql.clusterj.connect.timeout.after"

Name: PROPERTY_CLUSTER_CONNECT_TIMEOUT_BEFORE

Default Value: "com.mysql.clusterj.connect.timeout.before"

Name: PROPERTY_CLUSTER_CONNECT_TIMEOUT_MGM

Default Value: "com.mysql.clusterj.connect.timeout.mgm"

Name: PROPERTY_CLUSTER_CONNECT_VERBOSE

Default Value: "com.mysql.clusterj.connect.verbose"

Name: PROPERTY_CLUSTER_DATABASE

Default Value: "com.mysql.clusterj.database"

Name: PROPERTY_CLUSTER_MAX_TRANSACTIONS

Default Value: "com.mysql.clusterj.max.transactions"

Name: PROPERTY_CONNECTION_POOL_NODEIDS

Default Value: "com.mysql.clusterj.connection.pool.nodeids"

Name: PROPERTY_CONNECTION_POOL_SIZE

Default Value: "com.mysql.clusterj.connection.pool.size"

Name: PROPERTY_DEFER_CHANGES

Default Value: "com.mysql.clusterj.defer.changes"

Name: PROPERTY_JDBC_DRIVER_NAME

Default Value: "com.mysql.clusterj.jdbc.driver"

Name: PROPERTY_JDBC_PASSWORD

Default Value: "com.mysql.clusterj.jdbc.password"

Name: PROPERTY_JDBC_URL

Default Value: "com.mysql.clusterj.jdbc.url"

Name: PROPERTY_JDBC_USERNAME

Default Value: "com.mysql.clusterj.jdbc.username"

Name: SESSION_FACTORY_SERVICE_CLASS_NAME

Default Value: "com.mysql.clusterj.SessionFactoryService"

Name: SESSION_FACTORY_SERVICE_FILE_NAME

Default Value: "META-INF/services/com.mysql.clusterj.SessionFactoryService"


Table 4.2 Query Constants and Default Values

Name:

Default Value:

Name: INDEX_USED

Default Value: "IndexUsed"

Name: SCAN_TYPE

Default Value: "ScanType"

Name: SCAN_TYPE_INDEX_SCAN

Default Value: "INDEX_SCAN"

Name: SCAN_TYPE_PRIMARY_KEY

Default Value: "PRIMARY_KEY"

Name: SCAN_TYPE_TABLE_SCAN

Default Value: "TABLE_SCAN"

Name: SCAN_TYPE_UNIQUE_KEY

Default Value: "UNIQUE_KEY"


4.4 MySQL Cluster Connector for Java: Limitations and Known Issues

This section discusses the limitations and known issues in the MySQL Cluster Connector for Java APIs.

Known issues in ClusterJ:

  • Joins: With ClusterJ, queries are limited to single tables. This is not a problem with JPA or JDBC, both of which support joins.

  • Database views: Because MySQL database views do not use the NDB storage engine, ClusterJ applications cannot see views, and thus cannot access them. To work with views using Java, you should use JPA or JDBC.

  • Relations and inheritance: ClusterJ does not support relations or inheritance. Tables are mapped one-to-one onto domain classes, and only single-table operations are supported. NDB tables for NDB Cluster 7.3 and later support foreign keys, and foreign key constraints are enforced when using ClusterJ for inserts, updates, and deletes.

  • TIMESTAMP: Currently, ClusterJ does not support the TIMESTAMP data type for a primary key field.

Known issues in JPA: For information about limitations and known issues with OpenJPA, see the OpenJPA documentation.

Known issues in JDBC and Connector/J: For information about limitations and known issues with JDBC and Connector/J, see JDBC API Implementation Notes, and Troubleshooting Connector/J Applications.

Known issues in NDB Cluster: For information about limitations and other known issues with NDB Cluster, see Known Limitations of NDB Cluster.