You can declare a fixed binary field using the
BINARY()
statement. When you do this, you
must also specify the field's size in bytes. You then read and
write the field value using Java byte arrays. However, if the
byte array does not equal the specified size, then
IllegalArgumentException
is thrown when
you attempt to write the field. Write the field value using a
Java byte array.
If you want to store a large binary object, then you should use the LOB APIs rather than a binary field. For information on using the LOB APIs, see the Oracle NoSQL API Large Object API introduction.
Fixed binary should be used over the binary datatype any time you know that all the field values will be of the same size. Fixed binary is a more compact storage format because it does not need to store the size of the array. See Using Binary for information on the binary datatype.
To define a simple two-field table where the primary key is a UID and the second field contains a fixed binary field, you use the following script:
CREATE TABLE myTable ( uid INTEGER, myByteArray BINARY(20), PRIMARY KEY (uid) )
CHECK
, DEFAULT
and NOT NULL
constraints are not supported for binary values.
To write the byte array, use Row.putFixed()
.
Again, if the byte array does not match the size defined for
this field, then IllegalArgumentException
is thrown.
TableAPI tableH = kvstore.getTableAPI(); Table myTable = tableH.getTable("myTable"); Row row = myTable.createRow(); row.put("uid", 12345); String aString = "The quick brown fox."; try { row.putFixed("myByteArray", aString.getBytes("UTF-8")); } catch (UnsupportedEncodingException uee) { uee.printStackTrace(); } tableH.put(row, null, null);
To read the fixed binary field, use
Row.get().asFixedBinary()
. This returns a
FixedBinaryValue
class instance. You can then
use FixedBinaryValue.get()
to retrieve the
stored byte array.
For example:
TableAPI tableH = kvstore.getTableAPI(); Table myTable = tableH.getTable("myTable"); /* Create a primary key for user id 12345 and get a row */ PrimaryKey key = myTable.createPrimaryKey(); key.put("uid", 12345); Row row = tableH.get(key, null); byte[] b = row.get("myByteArray").asFixedBinary().get(); String aString = new String(b); System.out.println("aString: " + aString);