通过实体类操作数据库
保存
创建实体类
java
import nexus.io.db.annotation.ATableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@ATableName("rumi_rmp_professor_rating_tag")
public class RmpProfessorRatingTag {
private Integer id;
private String tagName;
}使用 Db 类保存数据
RmpProfessorRatingTag bean = new RmpProfessorRatingTag(id, tagName);
boolean save = Db.save(Row.fromBean(bean));布尔字段映射
Db.findFirst(Entity.class, sql, args) 和 Row.toBean(Entity.class) 使用默认实体转换器。Java 字段使用驼峰命名,SQL 列使用下划线命名即可自动对应。
- PostgreSQL 原生
boolean映射到Boolean或boolean时保留true、false。 - 数字类型状态值按照数值转换:零为
false,非零为true,支持 JDBC 常见的Integer、Long、Short等类型。 - SQL
NULL不设置属性:未初始化的Boolean保持null,boolean保持 Java 默认值false。业务需要区分“未设置”与“关闭”时选择Boolean。 - SQL 字符串不属于此处的布尔契约;文本状态应先在 SQL 中转换为明确的布尔表达式。
查询实体的示例:
java
import lombok.Data;
import nexus.io.db.activerecord.Db;
@Data
public class VerificationState {
private Long id;
private Boolean unexpired;
public static VerificationState find(long id) {
String sql = """
select id, expires_at > now() as unexpired
from verification_code where id=?
""";
return Db.findFirst(VerificationState.class, sql, id);
}
}调用方通过 Boolean.TRUE.equals(state.getUnexpired()) 明确判断有效状态;查询没有记录时先处理 state == null。这样数据库表达式、实体字段和业务条件使用一致的布尔语义。
