Skip to content

Conversation

@P-Peaceful
Copy link
Contributor

What's changed?

fixed: #3868

In HertzBeat AI feature, when users switch between multiple conversations, the chat history disappears and only the default welcome page is displayed. This is caused by JPA's @OneToMany lazy loading mechanism that prevents proper data loading.

Root Cause Analysis

The core issue lies in JPA's @OneToMany lazy loading behavior:

  1. Lazy Loading Mechanism: The messages field in ChatConversation entity uses @OneToMany annotation with default lazy loading (FetchType.LAZY) strategy
  2. Session Closure Issue: When fetching conversation objects via conversationDao.getReferenceById() or findById(), accessing the messages collection after Hibernate Session closure triggers LazyInitializationException or returns empty collections
  3. Proxy Object Trap: getReferenceById() returns a proxy object without immediately triggering database queries, causing associated message data to remain unloaded
  4. Transaction Boundary: After Service layer methods return, transactions are committed and Hibernate Sessions are closed, preventing lazy-loaded associations from being loaded

Solution

Adopt explicit query strategy instead of relying on JPA's automatic association loading:

  1. Add Dedicated Query Methods: Add findByConversationIdOrderByGmtCreateAsc() and findByConversationIdInOrderByGmtCreateAsc() methods in ChatMessageDao for explicit message queries
  2. Manual Message Loading: Explicitly query and set messages to conversation objects where message data is needed
  3. Batch Loading Optimization: In getAllConversations() method, use IN query to load all conversation messages at once, avoiding N+1 query problem
  4. Transaction Management: Add @Transactional annotation to deleteConversation() method to ensure atomicity of delete operations

Testing

20251214-212937.mp4

Checklist

  • I have read the Contributing Guide
  • I have written the necessary doc or comment.
  • I have added the necessary unit tests and all cases have passed.

Add or update API

  • I have added the necessary e2e tests and all cases have passed.

@tomsun28 tomsun28 added this to the 1.8.0 milestone Dec 16, 2025
Copy link
Member

@tomsun28 tomsun28 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm!

@tomsun28 tomsun28 merged commit aac5baf into apache:master Dec 16, 2025
3 checks passed
@P-Peaceful P-Peaceful deleted the bugfix-3868 branch December 24, 2025 15:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] <title>HertzBeat AI页面问题现象(已复现)

2 participants