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.
Surreal db = new Surreal();Returns: Surreal
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.
db.connect(url)Parameter | Type | Description |
|---|---|---|
url | String | The connection URL. Supported schemes: ws://, wss://, http://, https://, memory://, surrealkv://. |
Returns: Surreal (for method chaining)
db.connect("ws://localhost:8000"); .close()
Closes the active connection and releases all associated resources. This is called automatically when using try-with-resources.
db.close()Returns: void
db.close(); .useNs(namespace)
Switches the connection to a specific namespace.
db.useNs(ns)Parameter | Type | Description |
|---|---|---|
ns | String | The namespace to switch to. |
Returns: Surreal (for method chaining)
db.useNs("surrealdb").useDb("docs"); .useDb(database)
Switches the connection to a specific database.
db.useDb(database)Parameter | Type | Description |
|---|---|---|
db | String | The database to switch to. |
Returns: Surreal (for method chaining)
db.useDb("docs"); .useDefaults()
Resets the namespace and database to the server defaults.
db.useDefaults()Returns: Surreal (for method chaining)
db.useDefaults(); .getNamespace()
Returns the namespace currently in use on this connection.
db.getNamespace()Returns: String
String ns = db.getNamespace(); .getDatabase()
Returns the database currently in use on this connection.
db.getDatabase()Returns: String
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.
db.newSession()Returns: Surreal
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.
db.signin(credential)Parameter | Type | Description |
|---|---|---|
credential | Credential | The credentials to sign in with. Use RootCredential, NamespaceCredential, DatabaseCredential, or RecordCredential. |
Returns: Token
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.
db.signup(credential)Parameter | Type | Description |
|---|---|---|
credential | RecordCredential | The record access credentials including namespace, database, access method, and any additional fields required by the access definition. |
Returns: Token
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.
db.authenticate(token)Parameter | Type | Description |
|---|---|---|
token | String | A valid JWT token string. |
Returns: Surreal (for method chaining)
db.authenticate("eyJhbGciOiJIUzI1NiIs..."); .invalidate()
Invalidates the current authentication, removing the associated session token.
db.invalidate()Returns: Surreal (for method chaining)
db.invalidate();Query methods
.query(sql)
Executes one or more SurrealQL statements and returns a Response containing the results of each statement.
db.query(sql)Parameter | Type | Description |
|---|---|---|
sql | String | The SurrealQL query string to execute. |
Returns: Response
Response response = db.query("SELECT * FROM users");
List<User> users = response.take(User.class, 0); .queryBind(sql, params)
Executes a parameterised SurrealQL query. Parameters are safely injected into the query, preventing SurrealQL injection.
db.queryBind(sql, params)Parameter | Type | Description |
|---|---|---|
sql | String | The SurrealQL query string with parameter placeholders. |
params | Map<String, ?> | A map of parameter names to values. |
Returns: Response
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.
db.run(name, args)Parameter | Type | Description |
|---|---|---|
name | String | The function name (e.g. "fn::calculate_total"). |
args | Object... | Arguments to pass to the function. |
Returns: Value
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.
<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 | Class<T> | The class to deserialize results into. |
target | Stringor RecordId | The table name or specific record ID. |
contents | Tor T... | The record content(s) to create. |
**Returns:** `List` (table target) or `T` (record ID target)
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.
<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 | Class<T> | The class to deserialize results into. |
target | String, RecordId, RecordId..., or RecordIdRange | The table name, a single record ID, multiple record IDs, or a record ID range. |
**Returns:** `Iterator` (table), `Optional` (single ID), `List` (multiple IDs or range)
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.
<T> Iterator<T> selectSync(Class<T> type, String target)Parameter | Type | Description |
|---|---|---|
type | Class<T> | The class to deserialize results into. |
target | String | The table name to select from. |
**Returns:** `Iterator` (synchronized)
Iterator<Person> all = db.selectSync(Person.class, "person"); .insert(type, target, content)
Inserts one or more records into a table.
<T> List<T> insert(Class<T> type, String target, T... contents)Parameter | Type | Description |
|---|---|---|
type | Class<T> | The class to deserialize results into. |
target | String | The table to insert into. |
contents | T... | The record content(s) to insert. |
**Returns:** `List`
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.
<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 | Class<T> | The class to deserialize results into. |
target | RecordId, RecordIdRange, or String | The record ID, record ID range, or table name to update. |
upType | UpType | The update strategy: UpType.CONTENT(replace), UpType.MERGE(merge), or UpType.PATCH(JSON Patch). |
content | T | The update content. |
**Returns:** `T` (single record) or `Iterator` (table)
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.
<T> Iterator<T> updateSync(Class<T> type, String target, UpType upType, T content)**Returns:** `Iterator` (synchronized)
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().
<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 | Class<T> | The class to deserialize results into. |
target | RecordId, RecordIdRange, or String | The record ID, record ID range, or table name to upsert. |
upType | UpType | The update strategy: UpType.CONTENT(replace), UpType.MERGE(merge), or UpType.PATCH(JSON Patch). |
content | T | The record content. |
**Returns:** `T` (single record) or `Iterator` (table)
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.
<T> Iterator<T> upsertSync(Class<T> type, String target, UpType upType, T content)**Returns:** `Iterator` (synchronized)
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.
void delete(RecordId recordId)
void delete(RecordId... recordIds)
void delete(RecordIdRange range)
void delete(String target)Parameter | Type | Description |
|---|---|---|
target | RecordId, RecordId..., RecordIdRange, or String | A single record ID, multiple record IDs, a record ID range, or a table name. |
Returns: void
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.
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 | Class<T extends Relation> | The class to deserialize the relation into. Omit for untyped Valuereturn. |
from | RecordId | The source record. |
table | String | The relation table name. |
to | RecordId | The target record. |
content | T | Additional data to attach to the edge record. |
Returns: Value or T
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.
<T extends InsertRelation> T insertRelation(Class<T> type, String target, T content)Parameter | Type | Description |
|---|---|---|
type | Class<T extends InsertRelation> | The relation class to deserialize into. |
target | String | The relation table name. |
content | T | The relation content, including inand outfields. |
Returns: T
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.
<T extends InsertRelation> List<T> insertRelations(Class<T> type, String target, T... contents)Parameter | Type | Description |
|---|---|---|
type | Class<T extends InsertRelation> | The relation class to deserialize into. |
target | String | The relation table name. |
contents | T... | The relation records to insert, each including inand outfields. |
**Returns:** `List`
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.
db.selectLive(table)Parameter | Type | Description |
|---|---|---|
table | String | The table to watch for changes. |
Returns: LiveStream
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.
db.beginTransaction()Returns: Transaction
Transaction tx = db.beginTransaction();Utility methods
.version()
Returns the version string of the connected SurrealDB server.
db.version()Returns: String
String version = db.version(); .health()
Checks the health of the connected SurrealDB server.
db.health()Returns: boolean
boolean healthy = db.health(); .exportSql(path)
Exports the current database to a file at the specified path.
db.exportSql(path)Parameter | Type | Description |
|---|---|---|
path | String | The file path to export the database to. |
Returns: boolean
boolean success = db.exportSql("/tmp/backup.surql"); .importSql(path)
Imports a database from a file at the specified path.
db.importSql(path)Parameter | Type | Description |
|---|---|---|
path | String | The file path to import the database from. |
Returns: boolean
boolean success = db.importSql("/tmp/backup.surql");See also
Transaction — Transaction reference
Response — Query response reference
LiveStream — Live query reference
Connecting to SurrealDB — Connection protocols and patterns
Authentication — Authentication concepts
SurrealQL — Query language reference
DEFINE USER — System user configuration
DEFINE ACCESS — Record access method configuration