Java记录类(Record)实战:5个现代数据建模技巧 | Java17新特性

2025-07-17 0 773

Java记录类(Record)实战:5个现代数据建模技巧

核心价值: Java Record是Java14引入的不可变数据载体。本文将展示5个实际开发中的高级应用场景,帮助开发者简化DTO、值对象等数据类的编写。

1. 基础Record使用

创建简单的不可变数据类

// 定义Record类
public record Product(
    Long id,
    String name,
    BigDecimal price,
    LocalDateTime createTime
) {}

// 使用Record
Product product = new Product(1L, "Java编程", 
    new BigDecimal("99.99"), LocalDateTime.now());

// 自动生成的访问器方法
System.out.println(product.name()); // Java编程
System.out.println(product); // 自动生成的toString()

2. 自定义构造器

添加验证逻辑的紧凑构造器:

public record User(
    Long id,
    String username,
    String email
) {
    // 紧凑构造器(无参数列表)
    public User {
        if (username == null || username.isBlank()) {
            throw new IllegalArgumentException("用户名不能为空");
        }
        if (email != null && !email.contains("@")) {
            throw new IllegalArgumentException("邮箱格式不正确");
        }
        // 自动赋值给字段
    }
}

// 使用
User user = new User(1L, "张三", "zhangsan@example.com");

3. 添加业务方法

在Record中定义业务逻辑:

public record OrderItem(
    Long productId,
    String productName,
    BigDecimal price,
    int quantity
) {
    // 计算订单项总价
    public BigDecimal totalPrice() {
        return price.multiply(BigDecimal.valueOf(quantity));
    }
    
    // 静态工厂方法
    public static OrderItem of(Product product, int quantity) {
        return new OrderItem(
            product.id(),
            product.name(),
            product.price(),
            quantity
        );
    }
}

// 使用
OrderItem item = OrderItem.of(product, 2);
System.out.println(item.totalPrice());

4. 与JSON转换

Record与Jackson库的集成:

public record Address(
    String street,
    String city,
    String zipCode
) {}

// JSON序列化
ObjectMapper mapper = new ObjectMapper();
Address address = new Address("人民路", "北京市", "100000");
String json = mapper.writeValueAsString(address);

// JSON反序列化
Address parsed = mapper.readValue(json, Address.class);
特性 传统类 Record
代码量
不可变性 需手动实现 默认不可变
equals/hashCode 需重写 自动生成

5. 电商实战:订单处理

完整订单处理示例:

public record Order(
    Long id,
    String orderNo,
    List<OrderItem> items,
    Address shippingAddress,
    OrderStatus status
) {
    public BigDecimal totalAmount() {
        return items.stream()
            .map(OrderItem::totalPrice)
            .reduce(BigDecimal.ZERO, BigDecimal::add);
    }
    
    public Order withStatus(OrderStatus newStatus) {
        return new Order(id, orderNo, items, shippingAddress, newStatus);
    }
}

// 使用
Order order = orderRepository.findById(1L);
Order paidOrder = order.withStatus(OrderStatus.PAID);
BigDecimal total = order.totalAmount();

Java Record为数据建模提供了简洁高效的解决方案,特别适合DTO、值对象、配置类等场景,能大幅减少样板代码并提高代码可读性。

Java记录类(Record)实战:5个现代数据建模技巧 | Java17新特性
收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

淘吗网 java Java记录类(Record)实战:5个现代数据建模技巧 | Java17新特性 https://www.taomawang.com/server/java/412.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务