CRUD Operations

AN5 ORM provides a clean, type-safe API for all CRUD operations tailored for Java.


Client Setup

import an5.client.An5DbContext;
import an5.client.An5OrmTypes.BoolFilter;
import an5.client.An5OrmTypes.StringFilter;
import an5.client.An5OrmTypes.UserWhere;
import an5.client.User;

An5DbContext db = new An5DbContext(System.getenv("DATABASE_URL"));

An5DbContext implements AutoCloseable, so try (An5DbContext db = new An5DbContext(...)) closes the connection when the block ends.


1. Create

Create a Single Record

User user = db.getUser().create(
    new User().withEmail("john@example.com").withName("John Doe"));
System.out.println(user.getId());

Create Many Records

import java.util.Arrays;

int created = db.getUser().createMany(Arrays.asList(
    new User().withEmail("alice@example.com").withName("Alice"),
    new User().withEmail("bob@example.com").withName("Bob")), false);
System.out.println("Created " + created + " users");

The second argument is skipDuplicates.


2. Read

Find by Primary Key or Unique Field

UserWhere where = new UserWhere();
where.Email = StringFilter.is("john@example.com");

User user = db.getUser().findUnique(where.toMap());

findUnique returns null when nothing matches. The typed where also exposes and, or and not for nesting.

Find Many Records with Filter & Sort

import an5.adapters.An5Query;

UserWhere where = new UserWhere();
where.IsActive = BoolFilter.is(true);
where.Email = StringFilter.has("@example.com");

List<User> users = db.getUser().findMany(new An5Query()
    .where(where.toMap())
    .orderBy("createdAt", "desc")
    .skip(0)
    .take(10));

One An5Query carries the whole call: where, orderBy, skip, take, select and include chain onto it.


3. Update

Update Single Record

UserWhere byId = new UserWhere();
byId.Id = StringFilter.is(user.getId());

User updated = db.getUser().update(byId.toMap(),
    new User().withName("Johnny Doe"));

Columns left out of the value are left out of the statement, so they keep their current value.


4. Delete

Delete Single Record

UserWhere byId = new UserWhere();
byId.Id = StringFilter.is(user.getId());

db.getUser().delete(byId.toMap());

The deleted row comes back, or null when nothing matched. deleteMany(where) counts rows instead.


Next Steps