BaseDAOImpl最佳实践:Entity探索

实体 一般都会继承自 BaseEntity 这个里面主要字段:

  • 主键id
  • 创建人createdBy
  • 创建时间createdAt
  • 更新人updatedBy
  • 更新时间updatedAt
  • 逻辑删除delete

详细使用参考:https://xhope.top/?p=1266

但有的时候不需要除主键id以外的其他字段怎么办(id字段是必须的额)?这就需要继承自SimpleEntity,比如消息实体 Message,只需要 id text createdAt 三个字段。

Message.java

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@SuperBuilder
@Table(value = "t_message", comment = "消息")
public class Message extends SimpleEntity {

    private String text;

    @Column(updatable = false)
    private Instant createdAt;
}

SimpleEntity.java

@SuperBuilder
@Getter
@Setter
@NoArgsConstructor
public class SimpleEntity {

    @Id
    @JsonSerialize(using = ToStringSerializer.class)
    private Long id;

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        if (obj instanceof SimpleEntity) {
            SimpleEntity dataEntity = (SimpleEntity)obj ;
            if (dataEntity.id != null && dataEntity.id.equals(id))
                return true;
        }

        return false;
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 37)
                .append(id).toHashCode();
    }
}

也可以不继承任何类, id也可以是String类型
Message2.java

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@SuperBuilder
@Table(value = "t_message2", comment = "消息2")
public class Message2 {

    @Id
    @JsonSerialize(using = ToStringSerializer.class)
    private String seqId;

    private String text;

}