You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求Java中RavenDB事务的实现示例(已掌握C#版本)

Java 中 RavenDB 事务实现示例

基础会话事务(默认事务)

RavenDB 的 DocumentSession 本身具备事务性,会话内的所有 CRUD 操作会在调用 saveChanges() 时原子提交,任意操作失败都会回滚整个会话的变更。

代码示例

import com.ravendb.client.documents.DocumentStore;
import com.ravendb.client.documents.session.DocumentSession;

public class RavenDBTransactionBasic {
    public static void main(String[] args) {
        // 初始化全局单例 DocumentStore
        try (DocumentStore store = new DocumentStore("http://localhost:8080", "YourDatabaseName")) {
            store.initialize();

            // 开启会话(事务上下文)
            try (DocumentSession session = store.openSession()) {
                // 1. 新增文档
                User user = new User("Alice", "alice@example.com");
                session.store(user);

                // 2. 修改已有文档
                User existingUser = session.load(User.class, "users/1001");
                existingUser.setEmail("alice_updated@example.com");

                // 原子提交所有变更:要么全部成功,要么全部回滚
                session.saveChanges();
            }
        }
    }

    // 示例实体类
    static class User {
        private String id;
        private String name;
        private String email;

        public User(String name, String email) {
            this.name = name;
            this.email = email;
        }

        // Getters & Setters
        public String getId() { return id; }
        public void setId(String id) { this.id = id; }
        public String getName() { return name; }
        public void setName(String name) { this.name = name; }
        public String getEmail() { return email; }
        public void setEmail(String email) { this.email = email; }
    }
}

显式事务配置(自定义事务规则)

如果需要更细粒度的事务控制(比如超时、隔离级别),可以通过 TransactionOptions 显式配置会话的事务行为。

代码示例

import com.ravendb.client.documents.DocumentStore;
import com.ravendb.client.documents.session.DocumentSession;
import com.ravendb.client.documents.session.TransactionOptions;
import java.time.Duration;

public class RavenDBExplicitTransaction {
    public static void main(String[] args) {
        try (DocumentStore store = new DocumentStore("http://localhost:8080", "YourDatabaseName")) {
            store.initialize();

            // 配置事务选项:30秒超时、读已提交隔离级别
            TransactionOptions options = new TransactionOptions();
            options.setTimeout(Duration.ofSeconds(30));
            options.setIsolationLevel(TransactionIsolationLevel.READ_COMMITTED);

            try (DocumentSession session = store.openSession(options)) {
                // 事务内的业务操作
                Order newOrder = new Order("ORD-2024-001", 199.99);
                session.store(newOrder);

                Inventory stock = session.load(Inventory.class, "inventory/001");
                stock.reduceStock(2);

                // 提交事务
                session.saveChanges();
            } catch (Exception e) {
                // 异常触发自动回滚
                System.err.println("事务执行失败,已回滚: " + e.getMessage());
            }
        }
    }

    // 示例实体类
    static class Order {
        private String id;
        private String orderNo;
        private double totalAmount;

        public Order(String orderNo, double totalAmount) {
            this.orderNo = orderNo;
            this.totalAmount = totalAmount;
        }

        // Getters & Setters
        public String getId() { return id; }
        public void setId(String id) { this.id = id; }
        public String getOrderNo() { return orderNo; }
        public void setOrderNo(String orderNo) { this.orderNo = orderNo; }
        public double getTotalAmount() { return totalAmount; }
        public void setTotalAmount(double totalAmount) { this.totalAmount = totalAmount; }
    }

    static class Inventory {
        private String id;
        private int stockCount;

        public void reduceStock(int quantity) {
            this.stockCount -= quantity;
        }

        // Getters & Setters
        public String getId() { return id; }
        public void setId(String id) { this.id = id; }
        public int getStockCount() { return stockCount; }
        public void setStockCount(int stockCount) { this.stockCount = stockCount; }
    }
}

手动回滚事务示例

当业务逻辑判定需要终止事务时,可主动清空会话内的未提交变更,或直接抛出异常触发自动回滚。

try (DocumentSession session = store.openSession()) {
    try {
        User user = new User("Bob", "bob@example.com");
        session.store(user);

        // 模拟业务校验失败
        if (!validateUser(user)) {
            throw new IllegalArgumentException("用户信息不符合规则");
        }

        session.saveChanges();
    } catch (Exception e) {
        // 主动清空会话内的未提交变更
        session.advanced().clear();
        System.err.println("事务已手动回滚: " + e.getMessage());
    }
}

// 模拟校验方法
private static boolean validateUser(User user) {
    return user.getEmail() != null && user.getEmail().contains("@");
}

内容的提问来源于stack exchange,提问作者ptr16

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 19:57:35