Surreal
The Surreal class is the main entry point for the Java SDK. It provides methods for connecting to a SurrealDB instance, authenticating, querying, and managing data. The class implements AutoCloseable, so it can be used in a try-with-resources block to ensure the connection is closed automatically.
Source: surrealdb.java
Connection Methods
Surreal()
Creates a new Surreal instance. The instance is not connected to any server until .connect() is called.
Method Syntax
Surreal db = new Surreal();
Returns: Surreal
Example
Surreal db = new Surreal();
.connect(url)
Connects the instance to a SurrealDB server using the specified URL. The URL scheme determines the connection protocol. See the start command documentation for server configuration options.
Method Syntax
db.connect(url)
| Parameter | Type | Description |
|---|
url required | String | The connection URL. Supported schemes: ws://, wss://, http://, https://, memory://, surrealkv://. |
Returns: Surreal (for method chaining)
Example
db.connect("ws://localhost:8000");
.close()
Closes the active connection and releases all associated resources. This is called automatically when using try-with-resources.
Method Syntax
db.close()
Returns: void
Example
db.close();
.useNs(namespace)
Switches the connection to a specific namespace.
Method Syntax
db.useNs(ns)
| Parameter | Type | Description |
|---|
ns required | String | The namespace to switch to. |
Returns: Surreal (for method chaining)
Example
db.useNs("surrealdb").useDb("docs");
.useDb(database)
Switches the connection to a specific database.
Method Syntax
db.useDb(database)
| Parameter | Type | Description |
|---|
db required | String | The database to switch to. |
Returns: Surreal (for method chaining)
Example
db.useDb("docs");
.useDefaults()
Resets the namespace and database to the server defaults.
Method Syntax
db.useDefaults()
Returns: Surreal (for method chaining)
Example
db.useDefaults();
.getNamespace()
Returns the namespace currently in use on this connection.
Method Syntax
db.getNamespace()
Returns: String
Example
String ns = db.getNamespace();
.getDatabase()
Returns the database currently in use on this connection.
Method Syntax
db.getDatabase()
Returns: String
Example
String database = db.getDatabase();
.newSession()
Creates a new isolated session that shares the underlying connection but maintains its own namespace, database, authentication state, and variables.
Method Syntax
db.newSession()
Returns: Surreal
Example
Surreal session = db.newSession();
session.useNs("other_ns").useDb("other_db");
Authentication Methods
.signin(credential)
Signs in to the database with the provided credentials. The credential type determines the authentication level: root, namespace, database, or record access.
Method Syntax
db.signin(credential)
| Parameter | Type | Description |
|---|
credential required | Credential | The credentials to sign in with. Use RootCredential, NamespaceCredential, DatabaseCredential, or RecordCredential. |
Returns: Token
Example
Token token = db.signin(new RootCredential("root", "root"));
.signup(credential)
Signs up a new record user using a record access method defined with DEFINE ACCESS.
Method Syntax
db.signup(credential)
| Parameter | Type | Description |
|---|
credential required | RecordCredential | The record access credentials including namespace, database, access method, and any additional fields required by the access definition. |
Returns: Token
Example
Token token = db.signup(new RecordCredential(
"surrealdb", "docs", "user_access",
Map.of("email", "user@example.com", "password", "s3cret")
));
.authenticate(token)
Authenticates the current connection using an existing JWT token.
Method Syntax
db.authenticate(token)
| Parameter | Type | Description |
|---|
token required | String | A valid JWT token string. |
Returns: Surreal (for method chaining)
Example
db.authenticate("eyJhbGciOiJIUzI1NiIs...");
.invalidate()
Invalidates the current authentication, removing the associated session token.
Method Syntax
db.invalidate()
Returns: Surreal (for method chaining)
Example
db.invalidate();
Query Methods
.query(sql)
Executes one or more SurrealQL statements and returns a Response containing the results of each statement.
Method Syntax
db.query(sql)
| Parameter | Type | Description |
|---|
sql required | String | The SurrealQL query string to execute. |
Returns: Response
Example
Response response = db.query("SELECT * FROM users");
List<User> users = response.take(User.class, 0);
.queryBind(sql, params)
Executes a parameterized SurrealQL query. Parameters are safely injected into the query, preventing SurrealQL injection.
Method Syntax
db.queryBind(sql, params)
| Parameter | Type | Description |
|---|
sql required | String | The SurrealQL query string with parameter placeholders. |
params required | Map<String, ?> | A map of parameter names to values. |
Returns: Response
Example
Response response = db.queryBind(
"SELECT * FROM users WHERE age > $min_age",
Map.of("min_age", 18)
);
.run(name, args)
Runs a server-side SurrealDB function defined with DEFINE FUNCTION.
Method Syntax
db.run(name, args)
| Parameter | Type | Description |
|---|
name required | String | The function name (e.g. “fn::calculate_total”). |
args optional | Object… | Arguments to pass to the function. |
Returns: Value
Example
Value result = db.run("fn::calculate_total", 100, 0.2);
Data Methods
Most data methods have multiple overloads. The typed variants accepting Class<T> are shown below. Untyped variants returning Value or Iterator<Value> are also available.
.create(type, target, content)
Creates one or more records. When called with a table name, SurrealDB generates random IDs. When called with a RecordId, the record is created with that specific ID.
Method Syntax
<T> List<T> create(Class<T> type, String target, T... contents)
<T> T create(Class<T> type, RecordId recordId, T content)
| Parameter | Type | Description |
|---|
type required | Class<T> | The class to deserialize results into. |
target required | String or RecordId | The table name or specific record ID. |
contents required | T or T… | The record content(s) to create. |
Returns: List<T> (table target) or T (record ID target)
Example
Person alice = new Person();
alice.name = "Alice";
alice.age = 30;
List<Person> created = db.create(Person.class, "person", alice);
Person specific = db.create(Person.class, new RecordId("person", "tobie"), alice);
.select(type, target)
Selects records from a table or retrieves specific records by ID.
Method Syntax
<T> Iterator<T> select(Class<T> type, String target)
<T> Optional<T> select(Class<T> type, RecordId recordId)
<T> List<T> select(Class<T> type, RecordId... recordIds)
<T> List<T> select(Class<T> type, RecordIdRange range)
| Parameter | Type | Description |
|---|
type required | Class<T> | The class to deserialize results into. |
target required | String, RecordId, RecordId…, or RecordIdRange | The table name, a single record ID, multiple record IDs, or a record ID range. |
Returns: Iterator<T> (table), Optional<T> (single ID), List<T> (multiple IDs or range)
Example
Iterator<Person> all = db.select(Person.class, "person");
Optional<Person> one = db.select(Person.class, new RecordId("person", "tobie"));
List<Person> range = db.select(Person.class,
new RecordIdRange("person", Id.from("a"), Id.from("m")));
.selectSync(type, target)
Thread-safe variant of .select() for table-level queries. Returns a synchronized iterator safe for use across multiple threads.
Method Syntax
<T> Iterator<T> selectSync(Class<T> type, String target)
| Parameter | Type | Description |
|---|
type required | Class<T> | The class to deserialize results into. |
target required | String | The table name to select from. |
Returns: Iterator<T> (synchronized)
Example
Iterator<Person> all = db.selectSync(Person.class, "person");
.insert(type, target, content)
Inserts one or more records into a table.
Method Syntax
<T> List<T> insert(Class<T> type, String target, T... contents)
| Parameter | Type | Description |
|---|
type required | Class<T> | The class to deserialize results into. |
target required | String | The table to insert into. |
contents required | T… | The record content(s) to insert. |
Returns: List<T>
Example
Person alice = new Person();
alice.name = "Alice";
List<Person> inserted = db.insert(Person.class, "person", alice);
.update(type, target, upType, content)
Updates existing records. Use UpType.CONTENT to replace the entire record, UpType.MERGE to merge fields into the existing record, or UpType.PATCH to apply a JSON Patch.
Method Syntax
<T> T update(Class<T> type, RecordId recordId, UpType upType, T content)
<T> Iterator<T> update(Class<T> type, String target, UpType upType, T content)
<T> Value update(RecordIdRange range, UpType upType, T content)
| Parameter | Type | Description |
|---|
type required | Class<T> | The class to deserialize results into. |
target required | RecordId, RecordIdRange, or String | The record ID, record ID range, or table name to update. |
upType required | UpType | The update strategy: UpType.CONTENT (replace), UpType.MERGE (merge), or UpType.PATCH (JSON Patch). |
content required | T | The update content. |
Returns: T (single record) or Iterator<T> (table)
Example
Person updated = new Person();
updated.name = "Alice Smith";
updated.age = 31;
Person result = db.update(Person.class, new RecordId("person", "alice"), UpType.CONTENT, updated);
.updateSync(type, target, upType, content)
Thread-safe variant of .update() for table-level updates. Returns a synchronized iterator safe for use across multiple threads.
Method Syntax
<T> Iterator<T> updateSync(Class<T> type, String target, UpType upType, T content)
Returns: Iterator<T> (synchronized)
Example
Iterator<Person> results = db.updateSync(Person.class, "person", UpType.MERGE, updates);
.upsert(type, target, upType, content)
Updates an existing record or creates a new one if it does not exist. Accepts the same parameters as .update().
Method Syntax
<T> T upsert(Class<T> type, RecordId recordId, UpType upType, T content)
<T> Iterator<T> upsert(Class<T> type, String target, UpType upType, T content)
<T> Value upsert(RecordIdRange range, UpType upType, T content)
| Parameter | Type | Description |
|---|
type required | Class<T> | The class to deserialize results into. |
target required | RecordId, RecordIdRange, or String | The record ID, record ID range, or table name to upsert. |
upType required | UpType | The update strategy: UpType.CONTENT (replace), UpType.MERGE (merge), or UpType.PATCH (JSON Patch). |
content required | T | The record content. |
Returns: T (single record) or Iterator<T> (table)
Example
Person person = new Person();
person.name = "Alice";
person.age = 30;
Person result = db.upsert(Person.class, new RecordId("person", "alice"), UpType.CONTENT, person);
.upsertSync(type, target, upType, content)
Thread-safe variant of .upsert() for table-level upserts. Returns a synchronized iterator safe for use across multiple threads.
Method Syntax
<T> Iterator<T> upsertSync(Class<T> type, String target, UpType upType, T content)
Returns: Iterator<T> (synchronized)
Example
Iterator<Person> results = db.upsertSync(Person.class, "person", UpType.CONTENT, person);
.delete(target)
Deletes records from the database. Supports deleting a single record, multiple records by ID, a range of records, or all records in a table.
Method Syntax
void delete(RecordId recordId)
void delete(RecordId... recordIds)
void delete(RecordIdRange range)
void delete(String target)
| Parameter | Type | Description |
|---|
target required | RecordId, RecordId…, RecordIdRange, or String | A single record ID, multiple record IDs, a record ID range, or a table name. |
Returns: void
Example
db.delete(new RecordId("person", "tobie"));
db.delete(new RecordId("person", "alice"), new RecordId("person", "bob"));
db.delete(new RecordIdRange("person", Id.from("a"), Id.from("f")));
db.delete("temp_data");
.relate(from, table, to)
Creates a graph relation between two records.
Method Syntax
Value relate(RecordId from, String table, RecordId to)
<T extends Relation> T relate(Class<T> type, RecordId from, String table, RecordId to)
<T> Value relate(RecordId from, String table, RecordId to, T content)
<R extends Relation, T> R relate(Class<R> type, RecordId from, String table, RecordId to, T content)
| Parameter | Type | Description |
|---|
type optional | Class<T extends Relation> | The class to deserialize the relation into. Omit for untyped Value return. |
from required | RecordId | The source record. |
table required | String | The relation table name. |
to required | RecordId | The target record. |
content optional | T | Additional data to attach to the edge record. |
Returns: Value or T
Example
Value relation = db.relate(
new RecordId("person", "alice"),
"likes",
new RecordId("post", "post1")
);
Value withContent = db.relate(
new RecordId("person", "alice"),
"likes",
new RecordId("post", "post1"),
Map.of("timestamp", "2026-01-01T00:00:00Z")
);
.insertRelation(target, content)
Inserts a relation record into a relation table with additional data.
Method Syntax
<T extends InsertRelation> T insertRelation(Class<T> type, String target, T content)
| Parameter | Type | Description |
|---|
type required | Class<T extends InsertRelation> | The relation class to deserialize into. |
target required | String | The relation table name. |
content required | T | The relation content, including in and out fields. |
Returns: T
Example
Likes like = new Likes();
like.in = new RecordId("person", "alice");
like.out = new RecordId("post", "post1");
like.createdAt = "2025-01-01T00:00:00Z";
Likes result = db.insertRelation(Likes.class, "likes", like);
.insertRelations(target, contents)
Inserts multiple relation records into a relation table using varargs.
Method Syntax
<T extends InsertRelation> List<T> insertRelations(Class<T> type, String target, T... contents)
| Parameter | Type | Description |
|---|
type required | Class<T extends InsertRelation> | The relation class to deserialize into. |
target required | String | The relation table name. |
contents required | T… | The relation records to insert, each including in and out fields. |
Returns: List<T>
Example
Likes like1 = new Likes();
like1.in = new RecordId("person", "alice");
like1.out = new RecordId("post", "post1");
Likes like2 = new Likes();
like2.in = new RecordId("person", "alice");
like2.out = new RecordId("post", "post2");
List<Likes> results = db.insertRelations(Likes.class, "likes", like1, like2);
Live Query Methods
Live queries require a WebSocket connection (ws:// or wss://).
.selectLive(table)
Starts a live query that receives real-time notifications when records in the specified table are created, updated, or deleted.
Method Syntax
db.selectLive(table)
| Parameter | Type | Description |
|---|
table required | String | The table to watch for changes. |
Returns: LiveStream
Example
LiveStream stream = db.selectLive("person");
Transaction Methods
.beginTransaction()
Starts a new atomic transaction. All operations performed on the returned Transaction are grouped and only applied when committed.
Method Syntax
db.beginTransaction()
Returns: Transaction
Example
Transaction tx = db.beginTransaction();
Utility Methods
.version()
Returns the version string of the connected SurrealDB server.
Method Syntax
db.version()
Returns: String
Example
String version = db.version();
.health()
Checks the health of the connected SurrealDB server.
Method Syntax
db.health()
Returns: boolean
Example
boolean healthy = db.health();
.exportSql(path)
Exports the current database to a file at the specified path.
Method Syntax
db.exportSql(path)
| Parameter | Type | Description |
|---|
path required | String | The file path to export the database to. |
Returns: boolean
Example
boolean success = db.exportSql("/tmp/backup.surql");
.importSql(path)
Imports a database from a file at the specified path.
Method Syntax
db.importSql(path)
| Parameter | Type | Description |
|---|
path required | String | The file path to import the database from. |
Returns: boolean
Example
boolean success = db.importSql("/tmp/backup.surql");
See Also