Skip to content

Examples

Complete working examples demonstrating Volt's features.

Full Application Example

A complete example showing setup, CRUD operations, transactions, and queries:

java
import com.zaxxer.hikari.HikariConfig;
import me.oskarscot.volt.Result;
import me.oskarscot.volt.Transaction;
import me.oskarscot.volt.Volt;
import me.oskarscot.volt.VoltFactory;
import me.oskarscot.volt.exception.VoltError;
import me.oskarscot.volt.query.Query;

import java.util.List;

public class Application {

    public static void main(String[] args) {
        // 1. Configure HikariCP
        HikariConfig hikariConfig = new HikariConfig();
        hikariConfig.setDriverClassName("org.postgresql.Driver");
        hikariConfig.setJdbcUrl("jdbc:postgresql://localhost:5432/postgres");
        hikariConfig.setUsername("postgres");
        hikariConfig.setPassword("password");

        // 2. Create Volt instance
        Volt volt = VoltFactory.createVolt(hikariConfig);

        // 3. Register entities
        volt.registerEntity(Product.class);

        // 4. Simple save
        Product product = new Product("Laptop", "Gaming laptop", 999);
        Result<Product, VoltError> saveResult = volt.save(product);

        if (saveResult.isSuccess()) {
            System.out.println("Saved with ID: " + saveResult.getValue().getId());
        } else {
            System.err.println("Save failed: " + saveResult.getError().message());
        }

        // 5. Find by ID
        Result<Product, VoltError> findResult = volt.findById(Product.class, product.getId());

        if (findResult.isSuccess()) {
            System.out.println("Found: " + findResult.getValue().getName());
        }
    }
}

Entity Definition

java
import me.oskarscot.volt.annotation.Entity;
import me.oskarscot.volt.annotation.Identifier;
import me.oskarscot.volt.annotation.NamedField;
import me.oskarscot.volt.entity.PrimaryKeyType;

@Entity("products")
public class Product {

    @Identifier(type = PrimaryKeyType.NUMBER, generated = true)
    private Long id;

    @NamedField(name = "product_name")
    private String name;

    private String description;

    private int quantity;

    // Required no-arg constructor
    public Product() {}

    public Product(String name, String description, int quantity) {
        this.name = name;
        this.description = description;
        this.quantity = quantity;
    }

    // Getters and setters
    public Long getId() { return id; }
    public String getName() { return name; }
    public String getDescription() { return description; }
    public int getQuantity() { return quantity; }

    public void setName(String name) { this.name = name; }
    public void setDescription(String description) { this.description = description; }
    public void setQuantity(int quantity) { this.quantity = quantity; }
}

Transaction with Multiple Operations

java
try (Transaction tx = volt.beginTransaction()) {
    // Save multiple entities
    Product product1 = new Product("Keyboard", "Mechanical keyboard", 100);
    Product product2 = new Product("Mouse", "Wireless mouse", 200);

    Result<Product, VoltError> result1 = tx.save(product1);
    if (result1.isFailure()) {
        System.err.println("Failed to save product1: " + result1.getError().message());
        tx.rollback();
        return;
    }
    System.out.println("Saved product1 with ID: " + result1.getValue().getId());

    Result<Product, VoltError> result2 = tx.save(product2);
    if (result2.isFailure()) {
        System.err.println("Failed to save product2: " + result2.getError().message());
        tx.rollback();
        return;
    }
    System.out.println("Saved product2 with ID: " + result2.getValue().getId());

    // Commit all changes
    tx.commit();
    System.out.println("Transaction committed successfully");
}

Querying Data

Find All Entities

java
try (Transaction tx = volt.beginTransaction()) {
    Result<List<Product>, VoltError> allResult = tx.findAll(Product.class);

    if (allResult.isSuccess()) {
        System.out.println("Found " + allResult.getValue().size() + " products:");
        for (Product p : allResult.getValue()) {
            System.out.println("  - " + p.getId() + ": " + p.getName());
        }
    }

    tx.commit();
}

Query with Conditions

java
try (Transaction tx = volt.beginTransaction()) {
    // Find products with quantity >= 100
    Query query = Query.where("quantity").gte(100);
    Result<List<Product>, VoltError> queryResult = tx.findAllBy(Product.class, query);

    if (queryResult.isSuccess()) {
        System.out.println("Found " + queryResult.getValue().size() + " products with quantity >= 100");
    }

    tx.commit();
}

Complex Query

java
Query query = Query.where("quantity").gte(50)
    .and("quantity").lte(500)
    .and("name").notLike("TEST%");

Result<List<Product>, VoltError> result = tx.findAllBy(Product.class, query);

Update and Delete

java
try (Transaction tx = volt.beginTransaction()) {
    // Find existing entity
    Result<Product, VoltError> findResult = tx.findById(Product.class, 1L);

    if (findResult.isSuccess()) {
        // Update
        Product product = findResult.getValue();
        product.setName("Updated Product Name");
        product.setQuantity(150);

        Result<Product, VoltError> updateResult = tx.save(product);
        if (updateResult.isSuccess()) {
            System.out.println("Updated: " + updateResult.getValue().getName());
        }
    }

    // Delete by entity
    Result<Void, VoltError> deleteResult = tx.delete(someProduct);
    if (deleteResult.isSuccess()) {
        System.out.println("Deleted successfully");
    }

    // Or delete by ID
    Result<Void, VoltError> deleteByIdResult = tx.deleteById(Product.class, 2L);

    tx.commit();
}

Error Handling Pattern

java
public Result<Product, VoltError> createProduct(String name, String description, int quantity) {
    Product product = new Product(name, description, quantity);

    try (Transaction tx = volt.beginTransaction()) {
        Result<Product, VoltError> saveResult = tx.save(product);

        if (saveResult.isFailure()) {
            tx.rollback();
            return saveResult; // Propagate the error
        }

        Result<Void, VoltError> commitResult = tx.commit();
        if (commitResult.isFailure()) {
            return Result.failure(commitResult.getError());
        }

        return saveResult;
    }
}

// Usage
Result<Product, VoltError> result = createProduct("Widget", "A useful widget", 50);

if (result.isSuccess()) {
    System.out.println("Created: " + result.getValue().getId());
} else {
    System.err.println("Failed: " + result.getError().message());
}

Find Methods Comparison

java
try (Transaction tx = volt.beginTransaction()) {
    // findFirstBy - Returns Optional, never errors on not found
    Result<Optional<Product>, VoltError> first = tx.findFirstBy(Product.class, "name", "Laptop");
    if (first.isSuccess() && first.getValue().isPresent()) {
        System.out.println("Found: " + first.getValue().get().getName());
    }

    // findOneBy - Errors if not found OR if multiple found
    Result<Product, VoltError> one = tx.findOneBy(Product.class, "name", "Unique Product");
    if (one.isSuccess()) {
        System.out.println("Found exactly one: " + one.getValue().getName());
    }

    // findAllBy - Returns list (may be empty)
    Result<List<Product>, VoltError> all = tx.findAllBy(Product.class, "quantity", 100);
    if (all.isSuccess()) {
        System.out.println("Found " + all.getValue().size() + " products");
    }

    tx.commit();
}

Made with ❤️