类图 vs ER 图:领域建模

类图 vs ER 图:领域建模

puml.online

简介 / Introduction

类图(UML Class Diagram)和 ER 图(Entity-Relationship Diagram)都是描述结构化数据的利器,但侧重点不同:类图面向面向对象设计,强调类、属性和方法;ER 图面向数据库设计,强调实体、属性和关系。本文用同一业务场景分别展示两种图的 PlantUML 和 Mermaid 写法,并做横向对比。

PlantUML 版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@startuml
class User {
-id: Long
-name: String
-email: String
+getName(): String
}
class Order {
-id: Long
-total: BigDecimal
+calculateTotal(): BigDecimal
}
class Product {
-id: Long
-title: String
-price: BigDecimal
}
User "1" --> "*" Order : places
Order "*" --> "*" Product : contains
@enduml

PlantUML 类图使用 class 关键字定义类块,- 表示 private,+ 表示 public,方法用 (): ReturnType 语法。关系用 A --> B 加 multiplicity 表示。

Mermaid 版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
classDiagram
class User {
-id: Long
-name: String
-email: String
+getName(): String
}
class Order {
-id: Long
-total: BigDecimal
+calculateTotal(): BigDecimal
}
class Product {
-id: Long
-title: String
-price: BigDecimal
}
User "1" --> "*" Order : places
Order "*" --> "*" Product : contains

Mermaid classDiagram 用 class + 大括号定义类成员,访问修饰符同样用 - 和 +。关系用 --> 加 multiplicity,--> 在 HTML 渲染时需转义为 -->。

对比 / Side-by-side

特性 PlantUML Mermaid
关系箭头 A --> B A --> B
Multiplicity 位置 关系尾部 "1" --> "*" 关系尾部 "1" -- *"
方法返回类型 +method(): Type +method(): Type
私有成员 -field -field
关系标签 : label : label

小结 / Wrap-up

类图适合面向对象分析与设计阶段,ER 图更适合数据库schema设计。PlantUML 在复杂项目中生态更成熟(支持skinparam、主题等),Mermaid 在 Markdown 文档和网页中嵌入更便捷。同一业务概念掌握两种画法,沟通时更具灵活性。

  • 标题: 类图 vs ER 图:领域建模
  • 作者: puml.online
  • 创建于 : 2026-10-14 01:00:33
  • 更新于 : 2026-10-14 01:07:04
  • 链接: https://puml.online/blog/class-vs-er-for-domain/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。