为什么需要规范?
当项目规模变大,随意使用 Prisma 会导致查询逻辑分散、事务混乱、性能不可控,最终演变为“无法维护的数据库代码”。
无规范问题
查询散落各处
Controller / UI / Utils 混用
事务边界混乱
多层嵌套难以维护
重复查询逻辑
代码冗余严重
性能不可控
N+1 / 深层 include
推荐分层架构
三层结构
Controller
只处理请求与响应
Service
业务逻辑层
Repository
数据库访问层(Prisma)
Repository 封装 Prisma
user.repository.ts
typescript
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
export class UserRepository {
async findById(id: number) {
return prisma.user.findUnique({
where: { id }
});
}
async create(data: { name: string; email: string }) {
return prisma.user.create({ data });
}
async findWithPosts(id: number) {
return prisma.user.findUnique({
where: { id },
include: { posts: true }
});
}
}Service 层示例
user.service.ts
typescript
import { UserRepository } from './user.repository';
export class UserService {
constructor(private repo = new UserRepository()) {}
async registerUser(data: { name: string; email: string }) {
const exists = await this.repo.findByEmail(data.email);
if (exists) throw new Error('User already exists');
return this.repo.create(data);
}
}查询规范(统一标准)
查询原则
select 优先
减少数据传输
避免深层 include
不超过 2 层嵌套
分页必须 cursor
高并发推荐
索引优先设计
where 字段必须有索引
事务边界规范
事务必须在 Service 层控制,Repository 不能自行开启事务,避免事务嵌套混乱。
transaction.ts
typescript
await prisma.$transaction(async (tx) => {
const user = await tx.user.create({ data: { name: 'A' } });
await tx.post.create({ data: { title: 'B', userId: user.id } });
});目录结构推荐
structure.txt
text
src/
modules/
user/
user.controller.ts
user.service.ts
user.repository.ts
prisma/
schema.prisma
common/
utils/
dto/企业级核心原则
必须遵守
禁止直连 Prisma
必须通过 Repository
事务只在 Service
避免跨层混乱
所有查询可复用
避免重复逻辑
字段输出统一 DTO
前后端结构一致
总结
Prisma 在企业级项目中的核心不是 API 使用,而是架构约束。只要分层清晰、事务边界明确、查询规范统一,就可以支撑高并发系统。
最终下一步
系列收尾方向
完整 Prisma 架构模板
可直接用于项目初始化
高并发数据库设计
真实生产系统架构
相关笔记
在数字化一期,此笔记未产生更深相关的共鸣分枝。