Hibernate 7 共享 Notification 关联查询包含 NULL 与多键
不建议靠在 Student/Teacher 上挂一个普通 @OneToMany,让 Hibernate 把“自己的通知 + parent IS NULL 的全局通知”塞进同一个集合。标准 JPA 关联表达不了 owner_id = ? OR owner_id IS NULL 这种可变条件。可行的做法是保留共享的 NOTIFICATIONS 表,在 NotificationRepository 里写显式 JPQL 或原生 SQL,批量查出来以后在 service 层组装 DTO。把 Student/Teacher 的 Notification 实体拆成两套不是必须的,多数情况下只会多出维护成本。
为什么普通 @OneToMany 不行
@OneToMany 的语义是“一个 owner 对应多个 child”,Hibernate 生成的关联条件基本就是 notification.parent = student.id 或 notification.parent = teacher.id。就算加上 @Where、@SQLRestriction 或 @Filter,也很难把关联条件改成 (parent = owner.id OR parent IS NULL)。何况 join 条件里已经要求 parent = owner.id 时,parent IS NULL 的行根本进不了结果集。
另外原 SQL 里那句 parent IN (:id_parent, NULL) 本身也不成立:SQL 中 parent = NULL 的结果是 UNKNOWN,匹配不到 parent IS NULL。应该写成:
SELECT * FROM NOTIFICATIONS
WHERE type = 'TEACHER'
AND (parent = :id_parent OR parent IS NULL);
批量版本:
SELECT * FROM NOTIFICATIONS
WHERE type = 'TEACHER'
AND (parent IN (:parentIds) OR parent IS NULL);
推荐做法:Repository 批量查询 + service 组装
实体照旧共用一张表就行。如果这些集合只为这个接口服务,不建议在 Student 和 Teacher 上用普通 @OneToMany 直接序列化。真要映射“只属于自己的通知”,得显式写 @JoinColumn(name = "parent"),但它不会带上 parent IS NULL 的全局通知。
NotificationRepository 示例:
public interface NotificationRepository extends JpaRepository<Notification, Long> {
@Query("select n from Notification n where n.type = :type and (n.parent = :parentId or n.parent is null) order by n.id")
List<Notification> findForOwner(@Param("parentId") Long parentId,
@Param("type") String type);
@Query("select n from Notification n where n.type = :type and (n.parent in :parentIds or n.parent is null) order by n.id")
List<Notification> findForOwners(@Param("parentIds") Collection<Long> parentIds,
@Param("type") String type);
@Query("select n from Notification n where n.type = :type and n.parent is null order by n.id")
List<Notification> findGlobalByType(@Param("type") String type);
}
findForOwners 传入空集合时,不同数据库和 JPQL 实现的表现可能出问题,最好在 service 里先判断 ID 列表是否为空。为空就只查 findGlobalByType。
Service 里先查出当前页的 Students,再一次性查 Notifications,然后按 parent 分组,把全局通知合并到每个 Student:
public record NotificationDto(Long id, String text) {}
public record StudentDto(Long id, String name, List<NotificationDto> notes) {}
@Service
@Transactional(readOnly = true)
public class StudentQueryService {
private final StudentRepository studentRepository;
private final NotificationRepository notificationRepository;
public StudentQueryService(StudentRepository studentRepository,
NotificationRepository notificationRepository) {
this.studentRepository = studentRepository;
this.notificationRepository = notificationRepository;
}
public List<StudentDto> findStudents() {
List<Student> students = studentRepository.findAll();
if (students.isEmpty()) {
return List.of();
}
List<Long> ids = students.stream().map(Student::getId).toList();
List<Notification> notifications =
notificationRepository.findForOwners(ids, "STUDENT");
Map<Long, List<Notification>> byParent = notifications.stream()
.filter(n -> n.getParent() != null)
.collect(Collectors.groupingBy(Notification::getParent));
List<Notification> global = notifications.stream()
.filter(n -> n.getParent() == null)
.toList();
return students.stream()
.map(s -> {
List<Notification> merged = new ArrayList<>();
merged.addAll(global);
merged.addAll(byParent.getOrDefault(s.getId(), List.of()));
List<NotificationDto> notes = merged.stream()
.map(n -> new NotificationDto(n.getId(), n.getText()))
.toList();
return new StudentDto(s.getId(), s.getName(), notes);
})
.toList();
}
}
Teacher 侧同理,把 "STUDENT" 换成 "TEACHER",查出 Teacher 列表后走同一套批量组装逻辑。这样不会有 N+1 查询,也不用逐个遍历实体去触发懒加载。
是否要拆分实体
一般不必要。共享表加 type 字段本身是合理的,尤其 Notification 的结构对 Student 和 Teacher 完全一致的时候。拆开之后要么变成两套表,要么变成两套实体,全局通知、查询逻辑和代码复用都会更麻烦。只有当两边字段差异很大、生命周期不同、约束也完全不一样时,才值得考虑拆分或继承映射。
如果确实想让 Hibernate 自动填充集合
可以看看 Hibernate 专有的 @JoinFormula:
@OneToMany
@JoinFormula("(parent = id OR parent IS NULL) AND type = 'STUDENT'")
private List<Notification> notes;
但这类 SQL 片段要自己处理列名歧义、硬编码的 type、数据库方言和 Hibernate 版本差异,维护风险不低。@Where / @SQLRestriction 通常解决不了关联条件里带 OR NULL 的情况。生产代码还是用显式 Repository 查询更稳妥。
注意事项
- 给
NOTIFICATIONS建(type, parent)复合索引,例如CREATE INDEX idx_notifications_type_parent ON NOTIFICATIONS(type, parent);。 - 返回嵌套结构时用 DTO,别把实体集合直接序列化,避免懒加载、循环引用和字段泄漏。
- 分页查询 Students/Teachers 时,只拿当前页的 ID 去批量查 Notifications。
parent如果同时指向 Student 和 Teacher,数据库层一般没法加单一外键,一致性得在业务层保证。- ID 列表很大时,
IN参数可能触达数据库的限制,需要分批查询。
备注:内容仅供参考。
