Table of Contents
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.
This section provides a conceptual and architectural overview of the APIs available using the MySQL Cluster Connector for Java.
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.
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:

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.
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.
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:
Finding persistent instances by primary key
Creating, updating, and deleting persistent instances
Getting a query builder (see com.mysql.clusterj.query.QueryBuilder)
Getting the current transaction (see com.mysql.clusterj.Transaction).
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:

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
This section provides basic information about building and running Java applications using 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=:
Required for building NDB Cluster with ClusterJPA support.
pathpath 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
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.
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.
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
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.
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
log,
where NumNum 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.
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.
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;
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.
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)));
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:
Delete all rows from a table.
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:
begin():
Begin a transaction.
commit():
Commit a transaction.
rollback():
Roll back a transaction.
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.
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.
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:
| Java Data Type | MySQL Column Type |
|---|---|
boolean,
Boolean | BIT(1) |
byte,
Byte | BIT(1) to
BIT(8),
TINYINT |
short,
Short | BIT(1) to
BIT(16),
SMALLINT,
YEAR |
int,
Integer | BIT(1) to
BIT(32),
INT |
long,
Long | BIT(1) to
BIT(64),
BIGINT,
BIGINT
UNSIGNED |
float,
Float | FLOAT |
double,
Double | DOUBLE |
java.math.BigDecimal | NUMERIC,
DECIMAL |
java.math.BigInteger | NUMERIC (precision = 0),
DECIMAL (precision = 0) |
Date and time types. The following table shows the ClusterJ mappings between Java date and time data types and MySQL column types:
| Java Data Type | MySQL Column Type |
|---|---|
Java.util.Date | DATETIME,
TIMESTAMP,
TIME,
DATE |
Java.sql.Date | DATE |
Java.sql.Time | TIME |
Java.sql.Timestamp | DATETIME,
TIMESTAMP |
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:
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.
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.
The following sections contain specifications for ClusterJ packages, interfaces, classes, and methods.
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:
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.
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();
ClusterJUserException represents a database error. The underlying cause of the exception is contained in the "cause".
public class ClusterJDatastoreException extends, ClusterJException {
// Public Constructorspublic 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 Methodspublic 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
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);
public static final class ClusterJDatastoreException.Classification extends, Enum<Classification> {
// Public Static Fieldspublic 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 Methodspublic 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
7.3.15, 7.4.13, 7.5.4
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.
If a user exception is detected during bootstrapping
(acquiring a SessionFactory), it is thrown as a fatal
exception.
com.mysql.clusterj.ClusterJFatalUserException
If an exception is detected during initialization of a
persistent interface, for example annotating a column
that doesn't exist in the mapped table, it is reported
as a user exception.
com.mysql.clusterj.ClusterJUserException
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.
public class ClusterJException extends, RuntimeException {
// Public Constructorspublic ClusterJException(String message);public ClusterJException(String message,
Throwable t);public ClusterJException(Throwable t);
// Public Methodspublic 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
ClusterJFatalException represents an exception that is not recoverable.
public class ClusterJFatalException extends, ClusterJException {
// Public Constructorspublic 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
ClusterJFatalInternalException represents an implementation error that the user cannot recover from.
public class ClusterJFatalInternalException extends, ClusterJFatalException {
// Public Constructorspublic 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
ClusterJFatalUserException represents a user error that is unrecoverable, such as programming errors in persistent classes or missing resources in the execution environment.
public class ClusterJFatalUserException extends, ClusterJFatalException {
// Public Constructorspublic 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
ClusterJHelper provides helper methods to bridge between the API and the implementation.
public class ClusterJHelper {
// Public Constructorspublic ClusterJHelper();
// Public Static Methodspublic static boolean getBooleanProperty(String propertyName,
String def);public static T getServiceInstance(Class<T> cls);public static T getServiceInstance(Class<T> cls,
ClassLoader loader);public static T getServiceInstance(Class<T> cls,
String implementationClassName);public static T 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
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 |
public static T 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 |
public static T 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 |
public static T 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 |
public static T 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 |
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 |
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
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
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 |
ClusterJUserException represents a user programming error.
public class ClusterJUserException extends, ClusterJException {
// Public Constructorspublic 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
public interface ColumnMetadata {
// Public Methodspublic 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();
}
public abstract String charsetName();Return the charset name.
Parameters | |
return | the charset name |
public abstract ColumnType columnType();Return the type of the column.
Parameters | |
return | the type of the column |
public abstract boolean isPartitionKey();Return whether this column is a partition key column.
Parameters | |
return | true if this column is a partition key column |
public abstract boolean isPrimaryKey();Return whether this column is a primary key column.
Parameters | |
return | true if this column is a primary key column |
public abstract Class<?> javaType();Return the java type of the column.
Parameters | |
return | the java type of the column |
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 |
public abstract String name();Return the name of the column.
Parameters | |
return | the name of the column |
public abstract boolean nullable();Return whether this column is nullable.
Parameters | |
return | whether this column is nullable |
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. |
public abstract int precision();Return the precision of the column.
Parameters | |
return | the precision of the column |
This class enumerates the column types for columns in ndb.
public final class ColumnType extends, Enum<ColumnType> {
// Public Static Fieldspublic 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 Methodspublic 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
Constants used in the ClusterJ project.
public interface Constants {
// Public Static Fieldspublic 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";
}
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
public static final int DEFAULT_PROPERTY_CLUSTER_CONNECT_AUTO_INCREMENT_BATCH_SIZE = 10;The default value of the connection delay property
public static final long DEFAULT_PROPERTY_CLUSTER_CONNECT_AUTO_INCREMENT_START = 1L;The default value of the connection autoincrement offset property
public static final long DEFAULT_PROPERTY_CLUSTER_CONNECT_AUTO_INCREMENT_STEP = 1L;The default value of the connection delay property
public static final int DEFAULT_PROPERTY_CLUSTER_CONNECT_DELAY = 5;The default value of the connection delay property
public static final int DEFAULT_PROPERTY_CLUSTER_CONNECT_RETRIES = 4;The default value of the connection retries property
public static final int DEFAULT_PROPERTY_CLUSTER_CONNECT_TIMEOUT_AFTER = 20;The default value of the connection timeout after property
public static final int DEFAULT_PROPERTY_CLUSTER_CONNECT_TIMEOUT_BEFORE = 30;The default value of the connection timeout before property
public static final int DEFAULT_PROPERTY_CLUSTER_CONNECT_TIMEOUT_MGM = 30000;The default value of the connection timeout mgm property
public static final int DEFAULT_PROPERTY_CLUSTER_CONNECT_VERBOSE = 0;The default value of the connection verbose property
public static final String DEFAULT_PROPERTY_CLUSTER_DATABASE = "test";The default value of the database property
public static final int DEFAULT_PROPERTY_CLUSTER_MAX_TRANSACTIONS = 4;The default value of the maximum number of transactions property
public static final int DEFAULT_PROPERTY_CONNECTION_POOL_SIZE = 1;The default value of the connection pool size property
public static final String ENV_CLUSTERJ_LOGGER_FACTORY_NAME = "CLUSTERJ_LOGGER_FACTORY";The name of the environment variable to set the logger factory
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.
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()
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()
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()
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()
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()
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()
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()
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()
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()
public static final String PROPERTY_CLUSTER_CONNECTION_SERVICE = "com.mysql.clusterj.connection.service";The name of the connection service property
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
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
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()
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.
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.
public static final String PROPERTY_DEFER_CHANGES = "com.mysql.clusterj.defer.changes";The flag for deferred inserts, deletes, and updates
public static final String PROPERTY_JDBC_DRIVER_NAME = "com.mysql.clusterj.jdbc.driver";The name of the jdbc driver
public static final String PROPERTY_JDBC_PASSWORD = "com.mysql.clusterj.jdbc.password";The jdbc password
public static final String PROPERTY_JDBC_USERNAME = "com.mysql.clusterj.jdbc.username";The jdbc username
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();
public interface Dbug {
// Public Methodspublic 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();
}
public abstract Dbug append(String fileName);Specify the file name for debug output (append).
Parameters | |
fileName | the name of the file |
return | this |
public abstract Dbug debug(String string);Set the list of debug keywords.
Parameters | |
string | the comma separated debug keywords |
return | this |
public abstract Dbug debug(String[] strings);Set the list of debug keywords.
Parameters | |
strings | the debug keywords |
return | this |
public abstract Dbug flush();Force flush after each output operation.
Parameters | |
return | this |
public abstract String get();Return the current state.
Parameters | |
return | the current state |
public abstract Dbug output(String fileName);Specify the file name for debug output (overwrite).
Parameters | |
fileName | the name of the file |
return | this |
public abstract void pop();Pop the current state. The new state will be the previously pushed state.
public abstract void print(String keyword,
String message);Print debug message.
public abstract void push(String state);Push the current state and set the parameter as the new state.
Parameters | |
state | the new state |
public abstract void set(String state);Set the current state from the parameter.
Parameters | |
state | the new state |
public abstract class DynamicObject {
// Public Constructorspublic DynamicObject();
// Public Methodspublic 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
public interface DynamicObjectDelegate {
// Public Methodspublic 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();
}
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
public final class LockMode extends, Enum<LockMode> {
// Public Static Fieldspublic static final LockMode EXCLUSIVE ;public static final LockMode READ_COMMITTED ;public static final LockMode SHARED ;
// Public Static Methodspublic 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
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>).
public interface Query<E> {
// Public Static Fieldspublic 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 Methodspublic 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);
}
public static final String SCAN_TYPE_INDEX_SCAN = "INDEX_SCAN";The query explain scan type value for index scan
public static final String SCAN_TYPE_PRIMARY_KEY = "PRIMARY_KEY";The query explain scan type value for primary key
public static final String SCAN_TYPE_TABLE_SCAN = "TABLE_SCAN";The query explain scan type value for table scan
public static final String SCAN_TYPE_UNIQUE_KEY = "UNIQUE_KEY";The query explain scan type value for unique key
public abstract int deletePersistentAll();Delete the instances that satisfy the query criteria.
Parameters | |
return | the number of instances deleted |
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 |
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 |
public abstract Results<E> execute(Object parameter);Execute the query with exactly one parameter.
Parameters | |
parameter | the parameter |
return | the result |
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
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
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. |
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 |
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 |
Ordering
public static final class Query.Ordering extends, Enum<Ordering> {
// Public Static Fieldspublic static final Ordering ASCENDING ;public static final Ordering DESCENDING ;
// Public Static Methodspublic 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
Results of a query.
public interface Results<E> extends, Iterable<E> {
// Public Methodspublic abstract Iterator<E> iterator();
}
Session is the primary user interface to the cluster.
public interface Session {
// Public Methodspublic 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 T 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 T load(T instance);public abstract T makePersistent(T instance);public abstract Iterable<?> makePersistentAll(Iterable<?> instances);public abstract void markModified(Object instance,
String fieldName);public abstract T newInstance(Class<T> cls);public abstract T newInstance(Class<T> cls,
Object key);public abstract void persist(Object instance);public abstract T release(T obj);public abstract void remove(Object instance);public abstract T savePersistent(T 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);
}
public abstract Query<T> createQuery(QueryDefinition<T> qd);Create a Query from a QueryDefinition.
Parameters | |
qd | the query definition |
return | the query instance |
public abstract Transaction currentTransaction();
Get the current
com.mysql.clusterj.Transaction.
Parameters | |
return | the transaction |
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 |
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 |
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 |
public abstract void deletePersistentAll(Iterable<?> instances);Delete all parameter instances from the database.
Parameters | |
instances | the instances to delete |
public abstract T 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 |
public abstract void flush();Flush deferred changes to the back end. Inserts, deletes, loads, and updates are sent to the back end.
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 |
|
public abstract QueryBuilder getQueryBuilder();Get a QueryBuilder.
Parameters | |
return | the query builder |
public abstract boolean isClosed();Is this session closed?
Parameters | |
return | true if the session is closed |
public abstract T load(T 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 |
public abstract T makePersistent(T 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 |
public abstract Iterable<?> makePersistentAll(Iterable<?> instances);Insert the instances into the database.
Parameters | |
instances | the instances to insert. |
return | the instances |
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 |
public abstract T 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 |
public abstract T 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 |
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 |
public abstract T release(T 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.
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 |
public abstract T savePersistent(T 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 |
public abstract Iterable<?> savePersistentAll(Iterable<?> instances);Update all parameter instances in the database.
Parameters | |
instances | the instances to update |
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 |
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
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 |
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 |
SessionFactory represents a cluster.
public interface SessionFactory {
// Public Methodspublic abstract void close();public abstract List<Integer> getConnectionPoolSessionCounts();public abstract Session getSession();public abstract Session getSession(Map properties);
}
public abstract List<Integer> getConnectionPoolSessionCounts();Get a list containing the number of open sessions for each connection in the connection pool.
7.3.14, 7.4.12, 7.5.2
public abstract Session getSession();Create a Session to use with the cluster, using all the properties of the SessionFactory.
Parameters | |
return | the session |
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 |
This interface defines the service to create a SessionFactory from a Map<String, String> of properties.
public interface SessionFactoryService {
// Public Methodspublic abstract SessionFactory getSessionFactory(Map<String, String> props);
}
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 |
Transaction represents a user transaction active in the cluster.
public interface Transaction {
// Public Methodspublic abstract void begin();public abstract void commit();public abstract boolean getRollbackOnly();public abstract boolean isActive();public abstract void rollback();public abstract void setRollbackOnly();
}
public abstract boolean getRollbackOnly();Has this transaction been marked for rollback only?
Parameters | |
return | true if the transaction has been marked for rollback only |
public abstract boolean isActive();Is there a transaction currently active?
Parameters | |
return | true if a transaction is active |
This package provides annotations for domain object model interfaces mapped to database tables.
Annotation for a column in the database.
@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 ;
}
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 |
Default value for this column.
Parameters | |
return | the default value for this column |
Annotation for a group of columns. This annotation is used for multi-column structures such as indexes and keys.
@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 ;
}
Annotation for a non-standard extension.
@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 ;
}
Annotation for a group of extensions.
@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 ;
}
Annotation for a database index.
@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 ;
}
Columns that compose this index.
Parameters | |
return | columns that compose this index |
Annotation for a group of indices. This is used on a class where there are multiple indices defined.
@Target(value=java.lang.annotation.ElementType.TYPE) @Retention(value=java.lang.annotation.RetentionPolicy.RUNTIME) public @interface Indices {public Index[] value ;
}
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.
Annotation to specify that the member is not persistent. If used, this is the only annotation allowed on a member.
Enumeration of the "null-value" behavior values. This behavior is specified in the @Persistent annotation.
public final class NullValue extends, Enum<NullValue> {
// Public Static Fieldspublic static final NullValue DEFAULT ;public static final NullValue EXCEPTION ;public static final NullValue NONE ;
// Public Static Methodspublic 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
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.
@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 ;
}
Name of the column to use for the partition key
Parameters | |
return | the name of the column to use for the partition key |
Enumeration of the persistence-modifier values for a member.
public final class PersistenceModifier extends, Enum<PersistenceModifier> {
// Public Static Fieldspublic static final PersistenceModifier NONE ;public static final PersistenceModifier PERSISTENT ;public static final PersistenceModifier UNSPECIFIED ;
// Public Static Methodspublic 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
Annotation for defining the persistence of a member.
@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 ;
}
Column name where the values are stored for this member.
Parameters | |
return | the name of the column |
Non-standard extensions for this member.
Parameters | |
return | the non-standard extensions |
Behavior when this member contains a null value.
Parameters | |
return | the behavior when this member contains a null value |
Annotation on a member to define it as a primary key member of a class or persistent interface.
@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 ;
}
Name of the column to use for the primary key
Parameters | |
return | the name of the column to use for the primary key |
The column(s) for the primary key
Parameters | |
return | the column(s) for the primary key |
Provides interfaces for building queries for ClusterJ.
Used to combine multiple predicates with boolean operations.
public interface Predicate {
// Public Methodspublic abstract Predicate and(Predicate predicate);public abstract Predicate not();public abstract Predicate or(Predicate 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 |
public abstract Predicate not();Negate this Predicate.
Parameters | |
return | this predicate |
PredicateOperand represents a column or parameter that can be compared to another
public interface PredicateOperand {
// Public Methodspublic 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);
}
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 |
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 |
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 |
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 |
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 |
public abstract Predicate isNotNull();Return a Predicate representing comparing this to not null.
Parameters | |
return | a new Predicate |
public abstract Predicate isNull();Return a Predicate representing comparing this to null.
Parameters | |
return | a new Predicate |
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 |
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 |
QueryBuilder represents a factory for queries.
public interface QueryBuilder {
// Public Methodspublic abstract QueryDomainType<T> createQueryDefinition(Class<T> cls);
}
QueryDefinition allows users to define queries.
public interface QueryDefinition<E> {
// Public Methodspublic abstract Predicate not(Predicate predicate);public abstract PredicateOperand param(String parameterName);public abstract QueryDefinition<E> where(Predicate predicate);
}
public abstract Predicate not(Predicate predicate);Convenience method to negate a predicate.
Parameters | |
predicate | the predicate to negate |
return | the inverted predicate |
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 |
QueryDomainType represents the domain type of a query. The domain type validates property names that are used to filter results.
public interface QueryDomainType<E> extends, QueryDefinition<E> {
// Public Methodspublic abstract PredicateOperand get(String propertyName);public abstract Class<E> getType();
}
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 |
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" |
This section discusses the limitations and known issues in the MySQL Cluster Connector for Java APIs.
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.