fix(hibernate): improve transaction management and optimize entity fetching (#176)

* fix(hibernate): improve transaction management and optimize entity fetching

* chore(tests): clean-up comments

* chore: fix config issue in the kotlin dsl

* fix(hibernate): fix entity equality checks

* fix(hibernate): add transactional read-only support to BookService

* Update booklore-api/src/main/java/org/booklore/model/entity/BookLoreUserEntity.java

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* fix(hibernate): remove redundant annotations in BookLoreUserEntity

* fix(hibernate): import Hibernate

* fix(tests): fix merge conflict caused errors

* refactor(book): optimize book retrieval methods and reduce cache sizes

* refactor(metadata): remove lazy loading from description field in BookMetadataEntity

* fix(build): increase max heap size for test tasks

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
This commit is contained in:
brios
2026-04-22 17:27:01 -04:00
committed by Zach Yale
co-authored by coderabbitai[bot]
parent be0b717ff4
commit ad3a981ad1
73 changed files with 1902 additions and 435 deletions
@@ -38,6 +38,7 @@ import java.util.stream.Collectors;
@Service
@AllArgsConstructor
@Transactional(readOnly = true)
public class AppBookService {
private static final int DEFAULT_PAGE_SIZE = 20;
@@ -52,7 +53,6 @@ public class AppBookService {
private final MagicShelfBookService magicShelfBookService;
private final EntityManager entityManager;
@Transactional(readOnly = true)
public AppPageResponse<AppBookSummary> getBooks(
Integer page,
Integer size,
@@ -86,7 +86,6 @@ public class AppBookService {
return buildPageResponse(bookPage, userId, pageNum, pageSize);
}
@Transactional(readOnly = true)
public AppBookDetail getBookDetail(Long bookId) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
Long userId = user.getId();
@@ -110,7 +109,6 @@ public class AppBookService {
return mobileBookMapper.toDetail(book, progress, fileProgress);
}
@Transactional(readOnly = true)
public AppPageResponse<AppBookSummary> searchBooks(
String query,
Integer page,
@@ -140,7 +138,6 @@ public class AppBookService {
return buildPageResponse(bookPage, userId, pageNum, pageSize);
}
@Transactional(readOnly = true)
public List<AppBookSummary> getContinueReading(Integer limit) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
Long userId = user.getId();
@@ -148,33 +145,13 @@ public class AppBookService {
int maxItems = validateLimit(limit, 10);
Specification<BookEntity> spec = AppBookSpecification.combine(
AppBookSpecification.notDeleted(),
AppBookSpecification.hasDigitalFile(),
AppBookSpecification.inLibraries(accessibleLibraryIds),
AppBookSpecification.inProgress(userId),
AppBookSpecification.hasNonAudiobookFile()
);
List<BookEntity> books = bookRepository.findAll(spec);
Map<Long, UserBookProgressEntity> progressMap = getProgressMapForBooks(userId, books);
List<Long> topIds = books.stream()
.filter(b -> progressMap.containsKey(b.getId()))
.sorted((b1, b2) -> {
Instant t1 = progressMap.get(b1.getId()).getLastReadTime();
Instant t2 = progressMap.get(b2.getId()).getLastReadTime();
if (t1 == null && t2 == null) return 0;
if (t1 == null) return 1;
if (t2 == null) return -1;
return t2.compareTo(t1);
})
.limit(maxItems)
.map(BookEntity::getId)
.collect(Collectors.toList());
List<Long> topIds = userBookProgressRepository.findTopContinueReadingBookIds(
userId, accessibleLibraryIds, PageRequest.of(0, maxItems));
if (topIds.isEmpty()) return Collections.emptyList();
Map<Long, UserBookProgressEntity> progressMap = getProgressMap(userId, new HashSet<>(topIds));
Map<Long, BookEntity> enrichedMap = bookRepository.findAllForSummaryByIds(topIds)
.stream().collect(Collectors.toMap(BookEntity::getId, b -> b));
@@ -184,7 +161,6 @@ public class AppBookService {
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public List<AppBookSummary> getContinueListening(Integer limit) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
Long userId = user.getId();
@@ -192,33 +168,13 @@ public class AppBookService {
int maxItems = validateLimit(limit, 10);
Specification<BookEntity> spec = AppBookSpecification.combine(
AppBookSpecification.notDeleted(),
AppBookSpecification.hasDigitalFile(),
AppBookSpecification.inLibraries(accessibleLibraryIds),
AppBookSpecification.inProgress(userId),
AppBookSpecification.hasAudiobookFile()
);
List<BookEntity> books = bookRepository.findAll(spec);
Map<Long, UserBookProgressEntity> progressMap = getProgressMapForBooks(userId, books);
List<Long> topIds = books.stream()
.filter(b -> progressMap.containsKey(b.getId()))
.sorted((b1, b2) -> {
Instant t1 = progressMap.get(b1.getId()).getLastReadTime();
Instant t2 = progressMap.get(b2.getId()).getLastReadTime();
if (t1 == null && t2 == null) return 0;
if (t1 == null) return 1;
if (t2 == null) return -1;
return t2.compareTo(t1);
})
.limit(maxItems)
.map(BookEntity::getId)
.collect(Collectors.toList());
List<Long> topIds = userBookProgressRepository.findTopContinueListeningBookIds(
userId, accessibleLibraryIds, PageRequest.of(0, maxItems));
if (topIds.isEmpty()) return Collections.emptyList();
Map<Long, UserBookProgressEntity> progressMap = getProgressMap(userId, new HashSet<>(topIds));
Map<Long, BookEntity> enrichedMap = bookRepository.findAllForSummaryByIds(topIds)
.stream().collect(Collectors.toMap(BookEntity::getId, b -> b));
@@ -228,7 +184,6 @@ public class AppBookService {
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public List<AppBookSummary> getRecentlyAdded(Integer limit) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
Long userId = user.getId();
@@ -252,7 +207,6 @@ public class AppBookService {
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public List<AppBookSummary> getRecentlyScanned(Integer limit) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
Long userId = user.getId();
@@ -275,7 +229,6 @@ public class AppBookService {
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public AppPageResponse<AppBookSummary> getRandomBooks(
Integer page,
Integer size,
@@ -305,7 +258,6 @@ public class AppBookService {
return buildPageResponse(bookPage, userId, pageNum, pageSize);
}
@Transactional(readOnly = true)
public AppPageResponse<AppBookSummary> getBooksByMagicShelf(
Long magicShelfId,
Integer page,
@@ -338,7 +290,6 @@ public class AppBookService {
return AppPageResponse.of(summaries, pageNum, pageSize, booksPage.getTotalElements());
}
@Transactional(readOnly = true)
public AppFilterOptions getFilterOptions(Long libraryId, Long shelfId, Long magicShelfId) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
Long userId = user.getId();
@@ -172,11 +172,10 @@ public class AppSeriesService {
.map(t -> t.get(0, String.class))
.toList();
// Phase 2: Fetch books for enrichment
// Phase 2: Fetch books for enrichment (only ToOne joins; collections loaded via @BatchSize)
String libraryClause = buildLibraryClause(accessibleLibraryIds, libraryId);
String booksQuery = "SELECT b FROM BookEntity b"
+ " JOIN FETCH b.metadata m LEFT JOIN FETCH m.authors"
+ " LEFT JOIN FETCH b.bookFiles"
+ " JOIN FETCH b.metadata m"
+ " WHERE m.seriesName IN :seriesNames"
+ " AND (b.deleted IS NULL OR b.deleted = false)"
+ " AND b.bookFiles IS NOT EMPTY"
@@ -31,7 +31,7 @@ public class BackchannelLogoutService {
private static final Cache<String, Instant> PROCESSED_JTIS = Caffeine.newBuilder()
.expireAfterWrite(Duration.ofHours(1))
.maximumSize(10_000)
.maximumSize(1_000)
.build();
private final AppSettingService appSettingService;
@@ -14,7 +14,7 @@ public class OidcStateService {
private static final Cache<String, Boolean> STATE_CACHE = Caffeine.newBuilder()
.expireAfterWrite(Duration.ofMinutes(5))
.maximumSize(10_000)
.maximumSize(500)
.build();
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
@@ -23,7 +23,7 @@ public class AuthRateLimitService {
public AuthRateLimitService(AuditService auditService) {
this.auditService = auditService;
this.attemptCache = Caffeine.newBuilder()
.maximumSize(10000)
.maximumSize(1000)
.expireAfterWrite(Duration.ofMinutes(15))
.build();
}
@@ -23,6 +23,7 @@ public class LoginRateLimitService {
public LoginRateLimitService(AuditService auditService) {
this.auditService = auditService;
this.attemptCache = Caffeine.newBuilder()
.maximumSize(1000)
.expireAfterWrite(Duration.ofMinutes(15))
.build();
}
@@ -17,9 +17,11 @@ import org.booklore.service.appsettings.AppSettingService;
import org.booklore.service.audit.AuditService;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.UriComponentsBuilder;
import java.time.Instant;
import java.util.List;
@Slf4j
@Service
@@ -34,6 +36,7 @@ public class LogoutService {
private final AuditService auditService;
private final AuthenticationService authenticationService;
@Transactional
public LogoutResponse logout(Authentication auth, String refreshToken, String origin) {
BookLoreUserEntity user = resolveUser(auth, refreshToken);
@@ -65,11 +68,12 @@ public class LogoutService {
}
private void revokeRefreshToken(BookLoreUserEntity user) {
refreshTokenRepository.findAllByUserAndRevokedFalse(user).forEach(token -> {
List<RefreshTokenEntity> tokens = refreshTokenRepository.findAllByUserAndRevokedFalse(user);
tokens.forEach(token -> {
token.setRevoked(true);
token.setRevocationDate(Instant.now());
refreshTokenRepository.save(token);
});
refreshTokenRepository.saveAll(tokens);
}
private String buildOidcLogoutUrl(BookLoreUserEntity user, String origin) {
@@ -39,6 +39,8 @@ import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.Size;
import lombok.AllArgsConstructor;
import org.springframework.core.io.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
@@ -74,6 +76,14 @@ public class BookController {
return ResponseEntity.ok(bookService.getBookDTOs(withDescription, stripForListView));
}
@Operation(summary = "Get books (paginated)", description = "Retrieve a paginated list of books. Supports sorting via 'sort' parameter (e.g. sort=metadata.title,asc).")
@ApiResponse(responseCode = "200", description = "Page of books returned successfully")
@GetMapping("/page")
public ResponseEntity<Page<Book>> getBooksPaged(
@Parameter(hidden = true) Pageable pageable) {
return ResponseEntity.ok(bookService.getBookDTOsPaged(pageable));
}
@Operation(summary = "Get a book by ID", description = "Retrieve details of a specific book by its ID.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Book details returned successfully"),
@@ -82,7 +82,6 @@ public class MetadataController {
.build();
bookMetadataUpdater.setBookMetadata(context);
bookRepository.save(bookEntity);
auditService.log(AuditAction.METADATA_UPDATED, "Book", bookId, "Updated metadata for book: " + bookEntity.getMetadata().getTitle());
BookMetadata bookMetadata = bookMetadataMapper.toBookMetadata(bookEntity.getMetadata(), true);
return ResponseEntity.ok(bookMetadata);
@@ -29,6 +29,7 @@ public interface BookMapperV2 {
Book toDTO(BookEntity bookEntity);
@Named("mapMetadata")
@Mapping(target = "description", ignore = true)
@Mapping(target = "authors", source = "authors", qualifiedByName = "mapAuthors")
@Mapping(target = "categories", source = "categories", qualifiedByName = "mapCategories")
@Mapping(target = "moods", source = "moods", qualifiedByName = "mapMoods")
@@ -1,11 +1,13 @@
package org.booklore.model.entity;
import jakarta.persistence.*;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
@Entity
@Table(name = "app_settings")
@Data
@Getter
@Setter
public class AppSettingEntity {
@Id
@@ -2,9 +2,11 @@ package org.booklore.model.entity;
import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.BatchSize;
import java.util.List;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
@Entity
@Getter
@@ -41,7 +43,9 @@ public class AuthorEntity {
private boolean photoLocked;
@ManyToMany(mappedBy = "authors", fetch = FetchType.LAZY)
private List<BookMetadataEntity> bookMetadataEntityList;
@BatchSize(size = 20)
@Builder.Default
private Set<BookMetadataEntity> bookMetadataEntityList = new HashSet<>();
@Override
public boolean equals(Object o) {
@@ -6,11 +6,13 @@ import org.booklore.convertor.BookRecommendationIdsListConverter;
import org.booklore.model.dto.BookRecommendationLite;
import org.booklore.model.enums.BookFileType;
import org.hibernate.annotations.BatchSize;
import org.hibernate.annotations.LazyGroup;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@@ -77,8 +79,11 @@ public class BookEntity {
joinColumns = @JoinColumn(name = "book_id"),
inverseJoinColumns = @JoinColumn(name = "shelf_id")
)
private Set<ShelfEntity> shelves;
@Builder.Default
private Set<ShelfEntity> shelves = new HashSet<>();
@Basic(fetch = FetchType.LAZY)
@LazyGroup("recommendations")
@Convert(converter = BookRecommendationIdsListConverter.class)
@Column(name = "similar_books_json", columnDefinition = "TEXT")
private Set<BookRecommendationLite> similarBooksJson;
@@ -91,7 +96,8 @@ public class BookEntity {
@BatchSize(size = 20)
@OneToMany(mappedBy = "book", fetch = FetchType.LAZY)
private List<UserBookProgressEntity> userBookProgress;
@Builder.Default
private List<UserBookProgressEntity> userBookProgress = new ArrayList<>();
public Path getFullFilePath() {
BookFileEntity primaryBookFile = getPrimaryBookFile();
@@ -3,10 +3,12 @@ package org.booklore.model.entity;
import jakarta.persistence.*;
import lombok.*;
import org.booklore.model.enums.ProvisioningMethod;
import org.hibernate.Hibernate;
import org.hibernate.annotations.BatchSize;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
@Getter
@@ -93,4 +95,17 @@ public class BookLoreUserEntity {
public void prePersist() {
this.createdAt = LocalDateTime.now();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false;
BookLoreUserEntity that = (BookLoreUserEntity) o;
return id != null && Objects.equals(id, that.id);
}
@Override
public int hashCode() {
return Hibernate.getClass(this).hashCode();
}
}
@@ -4,9 +4,9 @@ import org.booklore.util.BookUtils;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.BatchSize;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.annotations.LazyGroup;
import java.time.Instant;
import java.time.LocalDate;
@@ -21,7 +21,7 @@ import java.util.Set;
@Builder
@NoArgsConstructor
@AllArgsConstructor
@DynamicUpdate // 93+ columns; only include changed columns in UPDATE SQL
@DynamicUpdate
@Table(name = "book_metadata")
public class BookMetadataEntity {
@@ -300,12 +300,16 @@ public class BookMetadataEntity {
@Builder.Default
private Boolean abridgedLocked = Boolean.FALSE;
@Basic(fetch = FetchType.LAZY)
@LazyGroup("embedding")
@Column(name = "embedding_vector", columnDefinition = "TEXT")
private String embeddingVector;
@Column(name = "embedding_updated_at")
private Instant embeddingUpdatedAt;
@Basic(fetch = FetchType.LAZY)
@LazyGroup("heavyText")
@Column(name = "search_text", columnDefinition = "TEXT")
private String searchText;
@@ -372,9 +376,10 @@ public class BookMetadataEntity {
name = "book_metadata_author_mapping",
joinColumns = @JoinColumn(name = "book_id"),
inverseJoinColumns = @JoinColumn(name = "author_id"))
@Fetch(FetchMode.SUBSELECT)
@BatchSize(size = 20)
@OrderColumn(name = "sort_order")
private List<AuthorEntity> authors;
@Builder.Default
private List<AuthorEntity> authors = new ArrayList<>();
@ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinTable(
@@ -382,8 +387,9 @@ public class BookMetadataEntity {
joinColumns = @JoinColumn(name = "book_id"),
inverseJoinColumns = @JoinColumn(name = "category_id")
)
@Fetch(FetchMode.SUBSELECT)
private Set<CategoryEntity> categories;
@BatchSize(size = 20)
@Builder.Default
private Set<CategoryEntity> categories = new HashSet<>();
@ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinTable(
@@ -391,8 +397,9 @@ public class BookMetadataEntity {
joinColumns = @JoinColumn(name = "book_id"),
inverseJoinColumns = @JoinColumn(name = "mood_id")
)
@Fetch(FetchMode.SUBSELECT)
private Set<MoodEntity> moods;
@BatchSize(size = 20)
@Builder.Default
private Set<MoodEntity> moods = new HashSet<>();
@ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinTable(
@@ -400,11 +407,12 @@ public class BookMetadataEntity {
joinColumns = @JoinColumn(name = "book_id"),
inverseJoinColumns = @JoinColumn(name = "tag_id")
)
@Fetch(FetchMode.SUBSELECT)
private Set<TagEntity> tags;
@BatchSize(size = 20)
@Builder.Default
private Set<TagEntity> tags = new HashSet<>();
@OneToMany(mappedBy = "bookMetadata", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
@Fetch(FetchMode.SUBSELECT)
@BatchSize(size = 20)
@Builder.Default
private Set<BookReviewEntity> reviews = new HashSet<>();
@@ -3,6 +3,7 @@ package org.booklore.model.entity;
import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.LazyGroup;
import org.hibernate.annotations.UpdateTimestamp;
import java.time.Instant;
@@ -35,10 +36,14 @@ public class BookdropFileEntity {
private Status status = Status.PENDING_REVIEW;
@Lob
@Basic(fetch = FetchType.LAZY)
@LazyGroup("metadata")
@Column(name = "original_metadata", columnDefinition = "JSON")
private String originalMetadata;
@Lob
@Basic(fetch = FetchType.LAZY)
@LazyGroup("metadata")
@Column(name = "fetched_metadata", columnDefinition = "JSON")
private String fetchedMetadata;
@@ -2,6 +2,7 @@ package org.booklore.model.entity;
import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.BatchSize;
import java.util.HashSet;
import java.util.Objects;
@@ -24,6 +25,7 @@ public class CategoryEntity {
private String name;
@ManyToMany(mappedBy = "categories", fetch = FetchType.LAZY)
@BatchSize(size = 20)
@Builder.Default
private Set<BookMetadataEntity> bookMetadataEntityList = new HashSet<>();
@@ -3,9 +3,8 @@ package org.booklore.model.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.BatchSize;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import java.util.HashSet;
import java.util.Set;
@@ -80,7 +79,7 @@ public class ComicMetadataEntity {
name = "comic_metadata_character_mapping",
joinColumns = @JoinColumn(name = "book_id"),
inverseJoinColumns = @JoinColumn(name = "character_id"))
@Fetch(FetchMode.SUBSELECT)
@BatchSize(size = 20)
@Builder.Default
private Set<ComicCharacterEntity> characters = new HashSet<>();
@@ -89,7 +88,7 @@ public class ComicMetadataEntity {
name = "comic_metadata_team_mapping",
joinColumns = @JoinColumn(name = "book_id"),
inverseJoinColumns = @JoinColumn(name = "team_id"))
@Fetch(FetchMode.SUBSELECT)
@BatchSize(size = 20)
@Builder.Default
private Set<ComicTeamEntity> teams = new HashSet<>();
@@ -98,12 +97,12 @@ public class ComicMetadataEntity {
name = "comic_metadata_location_mapping",
joinColumns = @JoinColumn(name = "book_id"),
inverseJoinColumns = @JoinColumn(name = "location_id"))
@Fetch(FetchMode.SUBSELECT)
@BatchSize(size = 20)
@Builder.Default
private Set<ComicLocationEntity> locations = new HashSet<>();
@OneToMany(mappedBy = "comicMetadata", cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.LAZY)
@Fetch(FetchMode.SUBSELECT)
@BatchSize(size = 20)
@Builder.Default
private Set<ComicCreatorMappingEntity> creatorMappings = new HashSet<>();
@@ -4,6 +4,7 @@ import jakarta.persistence.*;
import lombok.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
@Entity
@@ -24,6 +25,7 @@ public class KoboLibrarySnapshotEntity {
@Column(name = "created_date", nullable = false)
private LocalDateTime createdDate;
@OneToMany(mappedBy = "snapshot", cascade = CascadeType.ALL, orphanRemoval = true)
private List<KoboSnapshotBookEntity> books;
@OneToMany(mappedBy = "snapshot", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
@Builder.Default
private List<KoboSnapshotBookEntity> books = new ArrayList<>();
}
@@ -10,8 +10,7 @@ import org.booklore.model.enums.MetadataSource;
import jakarta.persistence.*;
import lombok.*;
import java.util.ArrayList;
import java.util.List;
import java.util.*;
@Entity
@Getter
@@ -31,14 +30,17 @@ public class LibraryEntity {
@Convert(converter = SortConverter.class)
private Sort sort;
@OneToMany(mappedBy = "library", orphanRemoval = true)
private List<BookEntity> bookEntities;
@OneToMany(mappedBy = "library", orphanRemoval = true, fetch = FetchType.LAZY)
@Builder.Default
private List<BookEntity> bookEntities = new ArrayList<>();
@OneToMany(mappedBy = "library", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
private List<LibraryPathEntity> libraryPaths;
@Builder.Default
private List<LibraryPathEntity> libraryPaths = new ArrayList<>();
@ManyToMany(mappedBy = "libraries")
private List<BookLoreUserEntity> users;
@ManyToMany(mappedBy = "libraries", fetch = FetchType.LAZY)
@Builder.Default
private Set<BookLoreUserEntity> users = new HashSet<>();
private boolean watch;
@@ -70,4 +72,16 @@ public class LibraryEntity {
@Builder.Default
private MetadataSource metadataSource = MetadataSource.EMBEDDED;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof LibraryEntity that)) return false;
return id != null && Objects.equals(id, that.id);
}
@Override
public int hashCode() {
return getClass().hashCode();
}
}
@@ -4,14 +4,17 @@ import org.booklore.model.enums.FetchedMetadataProposalStatus;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.LazyGroup;
import java.time.Instant;
@Entity
@Table(name = "metadata_fetch_proposals")
@Data
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@@ -43,6 +46,8 @@ public class MetadataFetchProposalEntity {
private FetchedMetadataProposalStatus status;
@Lob
@Basic(fetch = FetchType.LAZY)
@LazyGroup("lob")
@Column(name = "metadata_json", columnDefinition = "JSON")
private String metadataJson;
}
}
@@ -2,6 +2,7 @@ package org.booklore.model.entity;
import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.BatchSize;
import java.util.HashSet;
import java.util.Objects;
@@ -24,6 +25,7 @@ public class MoodEntity {
private String name;
@ManyToMany(mappedBy = "moods", fetch = FetchType.LAZY)
@BatchSize(size = 20)
@Builder.Default
private Set<BookMetadataEntity> bookMetadataEntityList = new HashSet<>();
@@ -3,6 +3,7 @@ package org.booklore.model.entity;
import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.LazyGroup;
import org.hibernate.annotations.UpdateTimestamp;
import java.time.LocalDateTime;
@@ -35,6 +36,8 @@ public class PdfAnnotationEntity {
private Long bookId;
@Lob
@Basic(fetch = FetchType.LAZY)
@LazyGroup("lob")
@Column(name = "data", nullable = false, columnDefinition = "LONGTEXT")
private String data;
@@ -2,6 +2,7 @@ package org.booklore.model.entity;
import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.BatchSize;
import java.util.HashSet;
import java.util.Objects;
@@ -24,6 +25,7 @@ public class TagEntity {
private String name;
@ManyToMany(mappedBy = "tags", fetch = FetchType.LAZY)
@BatchSize(size = 20)
@Builder.Default
private Set<BookMetadataEntity> bookMetadataEntityList = new HashSet<>();
@@ -5,6 +5,7 @@ import org.booklore.task.TaskStatus;
import org.booklore.model.enums.TaskType;
import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.LazyGroup;
import java.time.LocalDateTime;
import java.util.Map;
@@ -49,9 +50,11 @@ public class TaskHistoryEntity {
private String message;
@Lob
@Basic(fetch = FetchType.LAZY)
@LazyGroup("lob")
private String errorDetails;
@Convert(converter = JpaJsonConverter.class)
@Column(name = "task_options", columnDefinition = "TEXT")
private Map<String, Object> taskOptions;
}
}
@@ -1,5 +1,6 @@
package org.booklore.repository;
import org.springframework.data.domain.Page;
import org.springframework.transaction.annotation.Transactional;
import org.booklore.model.entity.BookEntity;
import org.booklore.model.entity.LibraryPathEntity;
@@ -33,8 +34,8 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
Optional<BookEntity> findByIdFull(@Param("id") Long id);
// Minimal graph for summary mapping: metadata (OneToOne), library (ManyToOne), bookFiles (OneToMany).
// metadata.authors is intentionally excluded — @Fetch(SUBSELECT) on BookMetadataEntity.authors
// triggers a single batch query when first accessed, so no N+1 occurs.
// metadata.authors is intentionally excluded — @BatchSize on BookMetadataEntity.authors
// triggers a batched query when first accessed, so no N+1 occurs.
@EntityGraph(attributePaths = { "metadata", "library", "bookFiles" })
@Query("SELECT b FROM BookEntity b WHERE b.id IN :bookIds AND (b.deleted IS NULL OR b.deleted = false)")
List<BookEntity> findAllForSummaryByIds(@Param("bookIds") Collection<Long> bookIds);
@@ -65,12 +66,8 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
@Query("SELECT b.id FROM BookEntity b WHERE b.libraryPath.id IN :libraryPathIds AND (b.deleted IS NULL OR b.deleted = false)")
List<Long> findAllBookIdsByLibraryPathIdIn(@Param("libraryPathIds") Collection<Long> libraryPathIds);
@EntityGraph(attributePaths = {
"metadata", "metadata.comicMetadata",
"metadata.comicMetadata.characters", "metadata.comicMetadata.teams", "metadata.comicMetadata.locations", "metadata.comicMetadata.creatorMappings",
"metadata.authors", "metadata.categories", "metadata.moods", "metadata.tags",
"shelves", "libraryPath", "library", "bookFiles"
})
// Only ToOne paths in EntityGraph; collections (authors, categories, moods, tags, shelves, bookFiles) loaded via @BatchSize.
@EntityGraph(attributePaths = {"metadata", "metadata.comicMetadata", "library"})
@Query("SELECT b FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false)")
List<BookEntity> findAllWithMetadata();
@@ -83,15 +80,6 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
@Query("SELECT b FROM BookEntity b WHERE b.id IN :bookIds AND (b.deleted IS NULL OR b.deleted = false)")
List<BookEntity> findAllWithMetadataByIds(@Param("bookIds") Set<Long> bookIds);
@EntityGraph(attributePaths = {
"metadata", "metadata.comicMetadata",
"metadata.comicMetadata.characters", "metadata.comicMetadata.teams", "metadata.comicMetadata.locations", "metadata.comicMetadata.creatorMappings",
"metadata.authors", "metadata.categories", "metadata.moods", "metadata.tags",
"shelves", "libraryPath", "library", "bookFiles"
})
@Query("SELECT b FROM BookEntity b WHERE b.id IN :bookIds AND (b.deleted IS NULL OR b.deleted = false)")
List<BookEntity> findWithMetadataByIdsWithPagination(@Param("bookIds") Set<Long> bookIds, Pageable pageable);
@EntityGraph(attributePaths = {
"metadata", "metadata.comicMetadata",
"metadata.comicMetadata.characters", "metadata.comicMetadata.teams", "metadata.comicMetadata.locations", "metadata.comicMetadata.creatorMappings",
@@ -105,23 +93,21 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
@Query("SELECT b FROM BookEntity b WHERE b.library.id = :libraryId AND (b.deleted IS NULL OR b.deleted = false)")
List<BookEntity> findAllByLibraryIdWithFiles(@Param("libraryId") Long libraryId);
@Query("""
SELECT DISTINCT b FROM BookEntity b
LEFT JOIN FETCH b.metadata m
LEFT JOIN FETCH m.authors
LEFT JOIN FETCH b.bookFiles
LEFT JOIN FETCH b.libraryPath
WHERE b.library.id = :libraryId
AND (b.deleted IS NULL OR b.deleted = false)
""")
@EntityGraph(attributePaths = {"bookFiles", "libraryPath"})
@Query("SELECT b FROM BookEntity b WHERE b.library.id = :libraryId")
List<BookEntity> findAllByLibraryIdForRescan(@Param("libraryId") Long libraryId);
@EntityGraph(attributePaths = {"bookFiles", "libraryPath"})
@Query("SELECT b FROM BookEntity b WHERE b.library.id = :libraryId AND b.deleted = true")
List<BookEntity> findDeletedByLibraryIdWithFiles(@Param("libraryId") Long libraryId);
// Only ToOne paths in EntityGraph; collections (authors, bookFiles) loaded via @BatchSize.
@EntityGraph(attributePaths = {"metadata", "libraryPath"})
@Query("SELECT b FROM BookEntity b WHERE b.library.id = :libraryId AND (b.deleted IS NULL OR b.deleted = false)")
List<BookEntity> findAllForDuplicateDetection(@Param("libraryId") Long libraryId);
@EntityGraph(attributePaths = {
"metadata", "metadata.comicMetadata",
"metadata.comicMetadata.characters", "metadata.comicMetadata.teams", "metadata.comicMetadata.locations", "metadata.comicMetadata.creatorMappings",
"metadata.authors", "metadata.categories", "metadata.moods", "metadata.tags",
"shelves", "libraryPath", "library", "bookFiles"
})
// Only ToOne paths in EntityGraph; collections (authors, categories, moods, tags, shelves, bookFiles) loaded via @BatchSize.
@EntityGraph(attributePaths = {"metadata", "metadata.comicMetadata", "library"})
@Query("SELECT b FROM BookEntity b WHERE b.library.id IN :libraryIds AND (b.deleted IS NULL OR b.deleted = false)")
List<BookEntity> findAllWithMetadataByLibraryIds(@Param("libraryIds") Collection<Long> libraryIds);
@@ -138,15 +124,9 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
@Query("SELECT DISTINCT b FROM BookEntity b JOIN b.bookFiles bf WHERE bf.isBookFormat = true AND bf.fileSizeKb IS NULL AND (b.deleted IS NULL OR b.deleted = false)")
List<BookEntity> findAllWithMetadataByFileSizeKbIsNull();
@Query("""
SELECT DISTINCT b FROM BookEntity b
LEFT JOIN FETCH b.metadata m
LEFT JOIN FETCH m.authors
LEFT JOIN FETCH m.categories
LEFT JOIN FETCH m.comicMetadata
LEFT JOIN FETCH b.shelves
WHERE (b.deleted IS NULL OR b.deleted = false)
""")
// Only ToOne paths in EntityGraph; collections (authors, categories, shelves) loaded via @BatchSize.
@EntityGraph(attributePaths = {"metadata", "metadata.comicMetadata"})
@Query("SELECT b FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false)")
List<BookEntity> findAllFullBooks();
@Query(value = """
@@ -357,19 +337,10 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
@Query("""
SELECT DISTINCT b FROM BookEntity b
LEFT JOIN b.metadata m
LEFT JOIN b.bookFiles bf
WHERE b.library.id = :libraryId
AND (
(m.seriesName = :seriesName)
OR (
m.seriesName IS NULL
AND bf.isBookFormat = true
AND bf.id = (
SELECT MIN(bf2.id) FROM BookFileEntity bf2
WHERE bf2.book = b AND bf2.isBookFormat = true
)
AND bf.fileName = :seriesName
)
OR (m.seriesName IS NULL AND :seriesName = :unknownSeriesName)
)
AND (b.deleted IS NULL OR b.deleted = false)
ORDER BY COALESCE(m.seriesNumber, 0)
@@ -408,4 +379,129 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
List<BookEntity> findBooksBySeriesNameUngroupedByLibraryId(
@Param("seriesName") String seriesName,
@Param("libraryId") Long libraryId);
/**
* Find books by series name across all libraries when groupUnknown=true.
*/
@EntityGraph(attributePaths = {"metadata", "metadata.comicMetadata", "shelves", "libraryPath", "bookFiles"})
@Query("""
SELECT DISTINCT b FROM BookEntity b
LEFT JOIN b.metadata m
WHERE (
(m.seriesName = :seriesName)
OR (
m.seriesName IS NULL
AND :seriesName = :unknownSeriesName
)
)
AND (b.deleted IS NULL OR b.deleted = false)
ORDER BY COALESCE(m.seriesNumber, 0)
""")
List<BookEntity> findBooksBySeriesNameGrouped(
@Param("seriesName") String seriesName,
@Param("unknownSeriesName") String unknownSeriesName);
/**
* Find books by series name across all libraries when groupUnknown=false.
*/
@EntityGraph(attributePaths = {"metadata", "metadata.comicMetadata", "shelves", "libraryPath", "bookFiles"})
@Query("""
SELECT b FROM BookEntity b
LEFT JOIN b.metadata m
LEFT JOIN b.bookFiles bf
WHERE (
(m.seriesName = :seriesName)
OR (m.seriesName IS NULL AND m.title = :seriesName)
OR (
m.seriesName IS NULL AND m.title IS NULL
AND bf.isBookFormat = true
AND bf.id = (
SELECT MIN(bf2.id) FROM BookFileEntity bf2
WHERE bf2.book = b AND bf2.isBookFormat = true
)
AND bf.fileName = :seriesName
)
)
AND (b.deleted IS NULL OR b.deleted = false)
ORDER BY COALESCE(m.seriesNumber, 0)
""")
List<BookEntity> findBooksBySeriesNameUngrouped(
@Param("seriesName") String seriesName);
/**
* Paginated query for all non-deleted books with Komga-relevant metadata.
* Only ToOne paths in EntityGraph to avoid Cartesian product; collections loaded via @BatchSize.
*/
@EntityGraph(attributePaths = {"metadata", "metadata.comicMetadata", "libraryPath", "library"})
@Query("SELECT b FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false)")
Page<BookEntity> findAllWithMetadataPaged(Pageable pageable);
/**
* Paginated query for non-deleted books by library with Komga-relevant metadata.
* Only ToOne paths in EntityGraph to avoid Cartesian product; collections loaded via @BatchSize.
*/
@EntityGraph(attributePaths = {"metadata", "metadata.comicMetadata", "libraryPath", "library"})
@Query("SELECT b FROM BookEntity b WHERE b.library.id = :libraryId AND (b.deleted IS NULL OR b.deleted = false)")
Page<BookEntity> findAllWithMetadataByLibraryIdPaged(@Param("libraryId") Long libraryId, Pageable pageable);
@Query("SELECT COUNT(b) FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false)")
long countNonDeleted();
@Query("SELECT COUNT(b) FROM BookEntity b WHERE b.library.id = :libraryId AND (b.deleted IS NULL OR b.deleted = false)")
long countByLibraryIdNonDeleted(@Param("libraryId") Long libraryId);
/**
* Lightweight query for recommendation: loads only metadata with authors and categories (no bookFiles, shelves, etc.)
*/
@Query("""
SELECT DISTINCT b FROM BookEntity b
LEFT JOIN FETCH b.metadata m
LEFT JOIN FETCH m.authors
LEFT JOIN FETCH m.categories
WHERE (b.deleted IS NULL OR b.deleted = false)
AND b.id <> :excludeBookId
""")
List<BookEntity> findAllForRecommendation(@Param("excludeBookId") Long excludeBookId);
/**
* Paginated query for all non-deleted books (main UI listing).
* Only ToOne paths in EntityGraph to avoid Cartesian product with LIMIT;
* collections (authors, categories, tags, moods, shelves, bookFiles) loaded via @BatchSize.
*/
@EntityGraph(attributePaths = {"metadata", "metadata.comicMetadata", "libraryPath", "library"})
@Query("SELECT b FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false)")
Page<BookEntity> findAllWithMetadataPage(Pageable pageable);
/**
* Paginated query for non-deleted books filtered by library IDs.
* Only ToOne paths in EntityGraph to avoid Cartesian product with LIMIT;
* collections (authors, categories, tags, moods, shelves, bookFiles) loaded via @BatchSize.
*/
@EntityGraph(attributePaths = {"metadata", "metadata.comicMetadata", "libraryPath", "library"})
@Query("SELECT b FROM BookEntity b WHERE b.library.id IN :libraryIds AND (b.deleted IS NULL OR b.deleted = false)")
Page<BookEntity> findAllWithMetadataByLibraryIdsPage(@Param("libraryIds") Collection<Long> libraryIds, Pageable pageable);
/**
* Batched query for embedding/recommendation computation.
* Only ToOne paths in EntityGraph to avoid Cartesian product with LIMIT/OFFSET;
* collections (authors, categories, shelves) loaded via @BatchSize when accessed.
*/
@EntityGraph(attributePaths = {"metadata", "metadata.comicMetadata"})
@Query("SELECT b FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false) ORDER BY b.id")
List<BookEntity> findAllFullBooksBatch(Pageable pageable);
/**
* Lightweight projection for on-demand recommendation: returns only bookId, embedding vector,
* and series name. Avoids loading full entities when pre-computed embeddings are available.
*/
@Query("""
SELECT b.id as bookId, m.embeddingVector as embeddingVector, m.seriesName as seriesName
FROM BookEntity b
LEFT JOIN b.metadata m
WHERE (b.deleted IS NULL OR b.deleted = false)
AND b.id <> :excludeBookId
AND m.embeddingVector IS NOT NULL
""")
List<org.booklore.repository.projection.BookEmbeddingProjection> findAllEmbeddingsForRecommendation(@Param("excludeBookId") Long excludeBookId);
}
@@ -6,6 +6,7 @@ import org.booklore.model.dto.ProgressPercentDto;
import org.booklore.model.dto.RatingDistributionDto;
import org.booklore.model.dto.StatusDistributionDto;
import org.booklore.model.entity.UserBookProgressEntity;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
@@ -14,6 +15,7 @@ import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.Set;
@@ -202,4 +204,46 @@ public interface UserBookProgressRepository extends JpaRepository<UserBookProgre
WHERE ubp.user.id = :userId
""")
List<ProgressPercentDto> findAllProgressPercentsByUser(@Param("userId") Long userId);
/**
* Returns book IDs for in-progress reading (non-audiobook), ordered by most recently read.
*/
@Query("""
SELECT DISTINCT ubp.book.id FROM UserBookProgressEntity ubp
JOIN ubp.book b
JOIN b.bookFiles bf
WHERE ubp.user.id = :userId
AND ubp.readStatus IN (org.booklore.model.enums.ReadStatus.READING, org.booklore.model.enums.ReadStatus.RE_READING)
AND (b.deleted IS NULL OR b.deleted = false)
AND bf.isBookFormat = true
AND bf.bookType <> org.booklore.model.enums.BookFileType.AUDIOBOOK
AND b.library.id IN :libraryIds
AND ubp.lastReadTime IS NOT NULL
ORDER BY ubp.lastReadTime DESC
""")
List<Long> findTopContinueReadingBookIds(
@Param("userId") Long userId,
@Param("libraryIds") Collection<Long> libraryIds,
Pageable pageable);
/**
* Returns book IDs for in-progress listening (audiobook), ordered by most recently read.
*/
@Query("""
SELECT DISTINCT ubp.book.id FROM UserBookProgressEntity ubp
JOIN ubp.book b
JOIN b.bookFiles bf
WHERE ubp.user.id = :userId
AND ubp.readStatus IN (org.booklore.model.enums.ReadStatus.READING, org.booklore.model.enums.ReadStatus.RE_READING)
AND (b.deleted IS NULL OR b.deleted = false)
AND bf.isBookFormat = true
AND bf.bookType = org.booklore.model.enums.BookFileType.AUDIOBOOK
AND b.library.id IN :libraryIds
AND ubp.lastReadTime IS NOT NULL
ORDER BY ubp.lastReadTime DESC
""")
List<Long> findTopContinueListeningBookIds(
@Param("userId") Long userId,
@Param("libraryIds") Collection<Long> libraryIds,
Pageable pageable);
}
@@ -0,0 +1,7 @@
package org.booklore.repository.projection;
public interface BookEmbeddingProjection {
Long getBookId();
String getEmbeddingVector();
String getSeriesName();
}
@@ -38,7 +38,7 @@ public class IconService {
private static final String ICONS_DIR = "icons";
private static final String SVG_DIR = "svg";
private static final String SVG_EXTENSION = ".svg";
private static final int MAX_CACHE_SIZE = 1000;
private static final int MAX_CACHE_SIZE = 200;
private static final String SVG_START_TAG = "<svg";
private static final String XML_DECLARATION = "<?xml";
private static final String SVG_END_TAG = "</svg>";
@@ -15,6 +15,7 @@ import java.util.stream.Collectors;
@AllArgsConstructor
@Service
@Transactional(readOnly = true)
public class MagicShelfService {
private final MagicShelfRepository magicShelfRepository;
@@ -43,6 +43,7 @@ import java.util.stream.Collectors;
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class ReadingSessionService {
private final AuthenticationService authenticationService;
@@ -84,7 +85,6 @@ public class ReadingSessionService {
log.info("Reading session persisted successfully: sessionId={}, userId={}, bookId={}, duration={}s", session.getId(), userId, request.getBookId(), request.getDurationSeconds());
}
@Transactional(readOnly = true)
public List<ReadingSessionHeatmapResponse> getSessionHeatmapForYear(int year) {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
Long userId = authenticatedUser.getId();
@@ -98,7 +98,6 @@ public class ReadingSessionService {
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public List<ReadingSessionHeatmapResponse> getSessionHeatmapForMonth(int year, int month) {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
Long userId = authenticatedUser.getId();
@@ -112,7 +111,6 @@ public class ReadingSessionService {
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public List<ReadingSessionTimelineResponse> getSessionTimelineForWeek(int year, int week) {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
Long userId = authenticatedUser.getId();
@@ -136,7 +134,6 @@ public class ReadingSessionService {
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public List<ReadingSpeedResponse> getReadingSpeedForYear(int year) {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
Long userId = authenticatedUser.getId();
@@ -151,7 +148,6 @@ public class ReadingSessionService {
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public List<PeakHoursResponse> getPeakReadingHours(Integer year, Integer month) {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
Long userId = authenticatedUser.getId();
@@ -166,7 +162,6 @@ public class ReadingSessionService {
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public List<FavoriteReadingDaysResponse> getFavoriteReadingDays(Integer year, Integer month) {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
Long userId = authenticatedUser.getId();
@@ -184,7 +179,6 @@ public class ReadingSessionService {
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public List<GenreStatisticsResponse> getGenreStatistics() {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
Long userId = authenticatedUser.getId();
@@ -207,7 +201,6 @@ public class ReadingSessionService {
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public List<CompletionTimelineResponse> getCompletionTimeline(int year) {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
Long userId = authenticatedUser.getId();
@@ -246,7 +239,6 @@ public class ReadingSessionService {
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public Page<ReadingSessionResponse> getReadingSessionsForBook(Long bookId, int page, int size) {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
Long userId = authenticatedUser.getId();
@@ -275,7 +267,6 @@ public class ReadingSessionService {
.build());
}
@Transactional(readOnly = true)
public List<BookCompletionHeatmapResponse> getBookCompletionHeatmap() {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
Long userId = authenticatedUser.getId();
@@ -293,7 +284,6 @@ public class ReadingSessionService {
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public List<PageTurnerScoreResponse> getPageTurnerScores() {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
Long userId = authenticatedUser.getId();
@@ -377,7 +367,6 @@ public class ReadingSessionService {
private static final int COMPLETION_RACE_BOOK_LIMIT = 10;
@Transactional(readOnly = true)
public List<CompletionRaceResponse> getCompletionRace(int year) {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
Long userId = authenticatedUser.getId();
@@ -409,7 +398,6 @@ public class ReadingSessionService {
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public List<ReadingSessionHeatmapResponse> getReadingDates() {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
Long userId = authenticatedUser.getId();
@@ -423,7 +411,6 @@ public class ReadingSessionService {
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public BookDistributionsResponse getBookDistributions() {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
Long userId = authenticatedUser.getId();
@@ -497,7 +484,6 @@ public class ReadingSessionService {
return max;
}
@Transactional(readOnly = true)
public List<SessionScatterResponse> getSessionScatter(int year) {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
Long userId = authenticatedUser.getId();
@@ -512,7 +498,6 @@ public class ReadingSessionService {
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public ReadingStreakResponse getReadingStreak() {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
Long userId = authenticatedUser.getId();
@@ -570,7 +555,6 @@ public class ReadingSessionService {
.build();
}
@Transactional(readOnly = true)
public List<BookTimelineResponse> getBookTimeline(int year) {
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
Long userId = authenticatedUser.getId();
@@ -620,7 +604,6 @@ public class ReadingSessionService {
// Listening (audiobook) stats
// ========================================================================
@Transactional(readOnly = true)
public List<ListeningHeatmapResponse> getListeningHeatmapForMonth(int year, int month) {
Long userId = authenticationService.getAuthenticatedUser().getId();
return readingSessionRepository.findListeningSessionsByUserAndMonth(userId, year, month, getTimezoneOffset())
@@ -633,7 +616,6 @@ public class ReadingSessionService {
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public List<WeeklyListeningTrendResponse> getWeeklyListeningTrend(int weeks) {
Long userId = authenticationService.getAuthenticatedUser().getId();
return readingSessionRepository.findWeeklyListeningTrend(userId, weeks, getTimezoneOffset())
@@ -647,7 +629,6 @@ public class ReadingSessionService {
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public ListeningCompletionResponse getListeningCompletion() {
Long userId = authenticationService.getAuthenticatedUser().getId();
var progressList = readingSessionRepository.findAudiobookProgressByUser(userId);
@@ -684,7 +665,6 @@ public class ReadingSessionService {
.build();
}
@Transactional(readOnly = true)
public List<MonthlyPaceResponse> getMonthlyListeningPace(int months) {
Long userId = authenticationService.getAuthenticatedUser().getId();
@@ -714,7 +694,6 @@ public class ReadingSessionService {
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public ListeningFinishFunnelResponse getListeningFinishFunnel() {
Long userId = authenticationService.getAuthenticatedUser().getId();
var progressList = readingSessionRepository.findAudiobookProgressByUser(userId);
@@ -745,7 +724,6 @@ public class ReadingSessionService {
.build();
}
@Transactional(readOnly = true)
public List<PeakHoursResponse> getListeningPeakHours(Integer year, Integer month) {
Long userId = authenticationService.getAuthenticatedUser().getId();
return readingSessionRepository.findListeningPeakHoursByUser(userId, year, month, getTimezoneOffset())
@@ -758,7 +736,6 @@ public class ReadingSessionService {
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public List<GenreStatisticsResponse> getListeningGenreStatistics() {
Long userId = authenticationService.getAuthenticatedUser().getId();
return readingSessionRepository.findListeningGenreStatisticsByUser(userId)
@@ -779,7 +756,6 @@ public class ReadingSessionService {
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public List<ListeningAuthorResponse> getListeningAuthorStats() {
Long userId = authenticationService.getAuthenticatedUser().getId();
return readingSessionRepository.findListeningAuthorStatsByUser(userId)
@@ -793,7 +769,6 @@ public class ReadingSessionService {
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public List<SessionScatterResponse> getListeningSessionScatter() {
Long userId = authenticationService.getAuthenticatedUser().getId();
return readingSessionRepository.findListeningSessionScatterByUser(userId, getTimezoneOffset())
@@ -806,7 +781,6 @@ public class ReadingSessionService {
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public List<LongestAudiobookResponse> getListeningLongestBooks() {
Long userId = authenticationService.getAuthenticatedUser().getId();
return readingSessionRepository.findAudiobookProgressByUser(userId)
@@ -4,15 +4,19 @@ import lombok.RequiredArgsConstructor;
import org.booklore.mapper.v2.BookMapperV2;
import org.booklore.model.dto.Book;
import org.booklore.model.dto.BookMetadata;
import org.booklore.model.dto.BookRecommendationLite;
import org.booklore.model.dto.ComicMetadata;
import org.booklore.model.entity.BookEntity;
import org.booklore.repository.BookRepository;
import org.booklore.service.restriction.ContentRestrictionService;
import org.hibernate.Hibernate;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Set;
import java.util.*;
import java.util.stream.Collectors;
@RequiredArgsConstructor
@@ -35,6 +39,35 @@ public class BookQueryService {
return mapBooksToDto(books, includeDescription, userId, StripForListView);
}
public Page<Book> getAllBooksPaged(Pageable pageable) {
Page<BookEntity> page = bookRepository.findAllWithMetadataPage(pageable);
return page.map(book -> mapBookToDto(book, false, null, true));
}
public Page<Book> getAllBooksByLibraryIdsPaged(Collection<Long> libraryIds, Long userId, Pageable pageable) {
Page<BookEntity> page = bookRepository.findAllWithMetadataByLibraryIdsPage(libraryIds, pageable);
List<BookEntity> filtered = contentRestrictionService.applyRestrictions(page.getContent(), userId);
List<Book> dtos = filtered.stream()
.map(book -> mapBookToDto(book, false, userId, true))
.toList();
return new PageImpl<>(dtos, pageable, page.getTotalElements());
}
public List<BookEntity> getAllFullBookEntitiesBatch(Pageable pageable) {
List<BookEntity> books = bookRepository.findAllFullBooksBatch(pageable);
for (BookEntity book : books) {
if (book.getMetadata() != null) {
Hibernate.initialize(book.getMetadata().getAuthors());
Hibernate.initialize(book.getMetadata().getCategories());
}
}
return books;
}
public long countAllNonDeleted() {
return bookRepository.countNonDeleted();
}
public List<BookEntity> findAllWithMetadataByIds(Set<Long> bookIds) {
return bookRepository.findAllWithMetadataByIds(bookIds);
}
@@ -52,6 +85,36 @@ public class BookQueryService {
bookRepository.saveAll(books);
}
@Transactional
public void compareAndSaveEmbeddings(Map<Long, String> embeddingJsonByBookId) {
List<BookEntity> books = bookRepository.findAllWithMetadataByIds(new HashSet<>(embeddingJsonByBookId.keySet()));
for (BookEntity book : books) {
String embeddingJson = embeddingJsonByBookId.get(book.getId());
if (embeddingJson != null && book.getMetadata() != null) {
if (!Objects.equals(book.getMetadata().getEmbeddingVector(), embeddingJson)) {
book.getMetadata().setEmbeddingVector(embeddingJson);
book.getMetadata().setEmbeddingUpdatedAt(java.time.Instant.now());
}
}
}
}
@Transactional
public void saveRecommendationsInBatches(Map<Long, Set<BookRecommendationLite>> recommendations, int batchSize) {
List<Long> bookIds = new ArrayList<>(recommendations.keySet());
for (int i = 0; i < bookIds.size(); i += batchSize) {
List<Long> batchIds = bookIds.subList(i, Math.min(i + batchSize, bookIds.size()));
List<BookEntity> batch = bookRepository.findAllById(batchIds);
for (BookEntity book : batch) {
Set<BookRecommendationLite> recs = recommendations.get(book.getId());
if (recs != null) {
book.setSimilarBooksJson(recs);
}
}
bookRepository.saveAll(batch);
}
}
private List<Book> mapBooksToDto(List<BookEntity> books, boolean includeDescription, Long userId, boolean stripForListView) {
return books.stream()
.map(book -> mapBookToDto(book, includeDescription, userId, stripForListView))
@@ -61,8 +124,8 @@ public class BookQueryService {
private Book mapBookToDto(BookEntity bookEntity, boolean includeDescription, Long userId, boolean stripForListView) {
Book dto = bookMapperV2.toDTO(bookEntity);
if (!includeDescription && dto.getMetadata() != null) {
dto.getMetadata().setDescription(null);
if (includeDescription && dto.getMetadata() != null && bookEntity.getMetadata() != null) {
dto.getMetadata().setDescription(bookEntity.getMetadata().getDescription());
}
if (dto.getShelves() != null && userId != null) {
@@ -1,6 +1,5 @@
package org.booklore.service.book;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@@ -22,14 +21,13 @@ import org.booklore.service.monitoring.MonitoringRegistrationService;
import org.booklore.service.progress.ReadingProgressService;
import org.booklore.util.FileService;
import org.booklore.util.FileUtils;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -47,6 +45,7 @@ import java.util.stream.Collectors;
@Slf4j
@AllArgsConstructor
@Service
@Transactional(readOnly = true)
public class BookService {
private final BookRepository bookRepository;
@@ -69,7 +68,6 @@ public class BookService {
private final AuditService auditService;
@Transactional(readOnly = true)
public List<Book> getBookDTOs(boolean includeDescription, boolean stripForListView) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
boolean isAdmin = user.getPermissions().isAdmin();
@@ -102,12 +100,42 @@ public class BookService {
return books;
}
public Page<Book> getBookDTOsPaged(Pageable pageable) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
boolean isAdmin = user.getPermissions().isAdmin();
Page<Book> bookPage = isAdmin
? bookQueryService.getAllBooksPaged(pageable)
: bookQueryService.getAllBooksByLibraryIdsPaged(
getUserLibraryIds(user),
user.getId(),
pageable
);
Set<Long> bookIds = bookPage.getContent().stream().map(Book::getId).collect(Collectors.toSet());
Map<Long, UserBookProgressEntity> progressMap =
readingProgressService.fetchUserProgress(user.getId(), bookIds);
Map<Long, UserBookFileProgressEntity> fileProgressMap =
readingProgressService.fetchUserFileProgress(user.getId(), bookIds);
bookPage.getContent().forEach(book -> {
readingProgressService.enrichBookWithProgress(
book,
progressMap.get(book.getId()),
fileProgressMap.get(book.getId())
);
Set<Shelf> filtered = filterShelvesByUserId(book.getShelves(), user.getId());
book.setShelves(filtered != null && filtered.isEmpty() ? null : filtered);
});
return bookPage;
}
private Set<Long> getUserLibraryIds(BookLoreUser user) {
return user.getAssignedLibraries().stream()
.map(Library::getId)
.collect(Collectors.toSet());
}
@Transactional(readOnly = true)
public List<Book> getBooksByIds(Set<Long> bookIds, boolean withDescription) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
boolean isAdmin = user.getPermissions().isAdmin();
@@ -140,7 +168,6 @@ public class BookService {
}).collect(Collectors.toList());
}
@Transactional(readOnly = true)
public Book getBook(long bookId, boolean withDescription) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
@@ -165,7 +192,6 @@ public class BookService {
}
@Transactional(readOnly = true)
public BookViewerSettings getBookViewerSetting(long bookId, long bookFileId) {
BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
BookLoreUser user = authenticationService.getAuthenticatedUser();
@@ -230,6 +256,7 @@ public class BookService {
return settingsBuilder.build();
}
@Transactional
public void updateBookViewerSetting(long bookId, BookViewerSettings bookViewerSettings) {
bookUpdateService.updateBookViewerSetting(bookId, bookViewerSettings);
}
@@ -40,6 +40,7 @@ public class BookUpdateService {
private final ReadingProgressService readingProgressService;
private final EbookViewerPreferenceRepository ebookViewerPreferenceRepository;
@Transactional
public void updateBookViewerSetting(long bookId, BookViewerSettings bookViewerSettings) {
BookEntity book = bookRepository.findByIdWithBookFiles(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
BookLoreUser user = authenticationService.getAuthenticatedUser();
@@ -17,6 +17,7 @@ import java.util.Set;
@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class NotebookService {
private static final int EXPORT_LIMIT = 50_000;
@@ -25,7 +26,6 @@ public class NotebookService {
private final NotebookEntryRepository repository;
private final AuthenticationService authenticationService;
@Transactional(readOnly = true)
public Page<NotebookEntry> getNotebookEntries(int page, int size, Set<String> types, Long bookId,
String search, String sort) {
Long userId = authenticationService.getAuthenticatedUser().getId();
@@ -34,7 +34,6 @@ public class NotebookService {
.map(NotebookService::toDto);
}
@Transactional(readOnly = true)
public List<NotebookEntry> getAllNotebookEntries(Set<String> types, Long bookId, String search, String sort) {
Long userId = authenticationService.getAuthenticatedUser().getId();
Pageable pageable = PageRequest.of(0, EXPORT_LIMIT, toSort(sort));
@@ -43,7 +42,6 @@ public class NotebookService {
.getContent();
}
@Transactional(readOnly = true)
public List<NotebookBookOption> getBooksWithAnnotations(String search) {
Long userId = authenticationService.getAuthenticatedUser().getId();
return repository.findBooksWithAnnotations(userId, wrapSearch(search), Pageable.ofSize(BOOK_OPTIONS_LIMIT))
@@ -40,6 +40,9 @@ import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.TransactionTemplate;
import tools.jackson.databind.ObjectMapper;
import java.io.File;
@@ -75,6 +78,7 @@ public class BookDropService {
private final FileMovingHelper fileMovingHelper;
private final MonitoringRegistrationService monitoringRegistrationService;
private final KoboAutoShelfService koboAutoShelfService;
private final PlatformTransactionManager transactionManager;
private static final int CHUNK_SIZE = 100;
@@ -467,24 +471,32 @@ public class BookDropService {
.orElseThrow(() -> ApiError.INVALID_FILE_FORMAT.createException("Unsupported file extension"))
.getType());
BookEntity bookEntity = bookRepository.findByIdWithBookFiles(fileProcessResult.getBook().getId())
.orElseThrow(() -> ApiError.FILE_NOT_FOUND.createException("Book ID missing after import"));
// Post-processing runs in REQUIRES_NEW so it gets a fresh REPEATABLE_READ snapshot
// that can see the book committed by processFile()'s own REQUIRES_NEW transaction
TransactionTemplate newTx = new TransactionTemplate(transactionManager);
newTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
Long bookId = fileProcessResult.getBook().getId();
newTx.executeWithoutResult(status -> {
BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId)
.orElseThrow(() -> ApiError.FILE_NOT_FOUND.createException("Book ID missing after import"));
notificationService.sendMessage(Topic.BOOK_ADD, fileProcessResult.getBook());
MetadataUpdateContext context = MetadataUpdateContext.builder()
.bookEntity(bookEntity)
.metadataUpdateWrapper(MetadataUpdateWrapper.builder()
.metadata(metadata)
.build())
.updateThumbnail(metadata.getThumbnailUrl() != null)
.mergeCategories(false)
.replaceMode(MetadataReplaceMode.REPLACE_WHEN_PROVIDED)
.mergeMoods(true)
.mergeTags(true)
.build();
MetadataUpdateContext context = MetadataUpdateContext.builder()
.bookEntity(bookEntity)
.metadataUpdateWrapper(MetadataUpdateWrapper.builder()
.metadata(metadata)
.build())
.updateThumbnail(metadata.getThumbnailUrl() != null)
.mergeCategories(false)
.replaceMode(MetadataReplaceMode.REPLACE_WHEN_PROVIDED)
.mergeMoods(true)
.mergeTags(true)
.build();
metadataRefreshService.updateBookMetadata(context);
koboAutoShelfService.autoAddBookToKoboShelves(bookEntity.getId());
metadataRefreshService.updateBookMetadata(context);
koboAutoShelfService.autoAddBookToKoboShelves(bookEntity.getId());
notificationService.sendMessage(Topic.BOOK_ADD, fileProcessResult.getBook());
});
cleanupBookdropData(bookdropFile);
@@ -639,4 +651,3 @@ public class BookDropService {
private record FileProcessingContext(Long libraryId, Long pathId, BookMetadata metadata) {
}
}
@@ -17,6 +17,9 @@ import org.booklore.service.reader.CbxReaderService;
import org.booklore.service.reader.PdfReaderService;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -121,11 +124,13 @@ public class KomgaService {
seriesName, libraryId);
}
} else {
// For all libraries, need to load all books and filter (less common case)
List<BookEntity> allBooks = bookRepository.findAllWithMetadata();
seriesBooks = allBooks.stream()
.filter(book -> komgaMapper.getBookSeriesName(book).equals(seriesName))
.collect(Collectors.toList());
// For all libraries without library filter
if (groupUnknown) {
seriesBooks = bookRepository.findBooksBySeriesNameGrouped(
seriesName, komgaMapper.getUnknownSeriesName());
} else {
seriesBooks = bookRepository.findBooksBySeriesNameUngrouped(seriesName);
}
}
if (!seriesBooks.isEmpty()) {
@@ -165,25 +170,40 @@ public class KomgaService {
Long libraryId = Long.parseLong(parts[0]);
String seriesSlug = parts[1];
// Get books matching the series - optimized to query by series name
List<BookEntity> allSeriesBooks = bookRepository.findAllWithMetadataByLibraryId(libraryId);
boolean groupUnknown = appSettingService.getAppSettings().isKomgaGroupUnknown();
// Get distinct series names for this library to find the matching name by slug
List<String> seriesNames;
if (groupUnknown) {
seriesNames = bookRepository.findDistinctSeriesNamesGroupedByLibraryId(libraryId, komgaMapper.getUnknownSeriesName());
} else {
seriesNames = bookRepository.findDistinctSeriesNamesUngroupedByLibraryId(libraryId);
}
// Find the series name that matches this slug
List<BookEntity> seriesBooks = allSeriesBooks.stream()
.filter(book -> {
String bookSeriesName = komgaMapper.getBookSeriesName(book);
String bookSeriesSlug = NON_ALPHANUMERIC_PATTERN.matcher(bookSeriesName.toLowerCase()).replaceAll("-");
return bookSeriesSlug.equals(seriesSlug);
String matchedSeriesName = seriesNames.stream()
.filter(name -> {
String slug = NON_ALPHANUMERIC_PATTERN.matcher(name.toLowerCase()).replaceAll("-");
return slug.equals(seriesSlug);
})
.collect(Collectors.toList());
.findFirst()
.orElseThrow(() -> new RuntimeException("Series not found"));
// Load only the books for this specific series
List<BookEntity> seriesBooks;
if (groupUnknown) {
seriesBooks = bookRepository.findBooksBySeriesNameGroupedByLibraryId(
matchedSeriesName, libraryId, komgaMapper.getUnknownSeriesName());
} else {
seriesBooks = bookRepository.findBooksBySeriesNameUngroupedByLibraryId(
matchedSeriesName, libraryId);
}
if (seriesBooks.isEmpty()) {
throw new RuntimeException("Series not found");
}
String seriesName = komgaMapper.getBookSeriesName(seriesBooks.get(0));
return komgaMapper.toKomgaSeriesDto(seriesName, libraryId, seriesBooks);
return komgaMapper.toKomgaSeriesDto(matchedSeriesName, libraryId, seriesBooks);
}
public KomgaPageableDto<KomgaBookDto> getBooksBySeries(String seriesId, int page, int size, boolean unpaged) {
@@ -196,23 +216,36 @@ public class KomgaService {
Long libraryId = Long.parseLong(parts[0]);
String seriesSlug = parts[1];
// Get all books for the library once
List<BookEntity> allBooks = bookRepository.findAllWithMetadataByLibraryId(libraryId);
boolean groupUnknown = appSettingService.getAppSettings().isKomgaGroupUnknown();
// Filter and sort books for this series
List<BookEntity> seriesBooks = allBooks.stream()
.filter(book -> {
String bookSeriesName = komgaMapper.getBookSeriesName(book);
String bookSeriesSlug = NON_ALPHANUMERIC_PATTERN.matcher(bookSeriesName.toLowerCase()).replaceAll("-");
return bookSeriesSlug.equals(seriesSlug);
// Get distinct series names for this library to find the matching name by slug
List<String> seriesNames;
if (groupUnknown) {
seriesNames = bookRepository.findDistinctSeriesNamesGroupedByLibraryId(libraryId, komgaMapper.getUnknownSeriesName());
} else {
seriesNames = bookRepository.findDistinctSeriesNamesUngroupedByLibraryId(libraryId);
}
// Find the series name that matches this slug
String matchedSeriesName = seriesNames.stream()
.filter(name -> {
String slug = NON_ALPHANUMERIC_PATTERN.matcher(name.toLowerCase()).replaceAll("-");
return slug.equals(seriesSlug);
})
.sorted(Comparator.comparing(book -> {
BookMetadataEntity metadata = book.getMetadata();
return metadata != null && metadata.getSeriesNumber() != null
? metadata.getSeriesNumber()
: 0f;
}))
.collect(Collectors.toList());
.findFirst()
.orElse(null);
// Load only the books for this specific series (already sorted by seriesNumber via query ORDER BY)
List<BookEntity> seriesBooks;
if (matchedSeriesName == null) {
seriesBooks = List.of();
} else if (groupUnknown) {
seriesBooks = bookRepository.findBooksBySeriesNameGroupedByLibraryId(
matchedSeriesName, libraryId, komgaMapper.getUnknownSeriesName());
} else {
seriesBooks = bookRepository.findBooksBySeriesNameUngroupedByLibraryId(
matchedSeriesName, libraryId);
}
// Handle unpaged mode
int totalElements = seriesBooks.size();
@@ -256,21 +289,16 @@ public class KomgaService {
}
public KomgaPageableDto<KomgaBookDto> getAllBooks(Long libraryId, int page, int size) {
List<BookEntity> books;
Pageable pageable = PageRequest.of(page, size);
Page<BookEntity> bookPage;
if (libraryId != null) {
books = bookRepository.findAllWithMetadataByLibraryId(libraryId);
bookPage = bookRepository.findAllWithMetadataByLibraryIdPaged(libraryId, pageable);
} else {
books = bookRepository.findAllWithMetadata();
bookPage = bookRepository.findAllWithMetadataPaged(pageable);
}
// Manual pagination
int totalElements = books.size();
int totalPages = (int) Math.ceil((double) totalElements / size);
int fromIndex = Math.min(page * size, totalElements);
int toIndex = Math.min(fromIndex + size, totalElements);
List<KomgaBookDto> content = books.subList(fromIndex, toIndex).stream()
List<KomgaBookDto> content = bookPage.getContent().stream()
.map(book -> komgaMapper.toKomgaBookDto(book))
.collect(Collectors.toList());
@@ -279,10 +307,10 @@ public class KomgaService {
.number(page)
.size(size)
.numberOfElements(content.size())
.totalElements(totalElements)
.totalPages(totalPages)
.totalElements((int) bookPage.getTotalElements())
.totalPages(bookPage.getTotalPages())
.first(page == 0)
.last(page >= totalPages - 1)
.last(page >= bookPage.getTotalPages() - 1)
.empty(content.isEmpty())
.build();
}
@@ -419,4 +447,4 @@ public class KomgaService {
return outputStream.toByteArray();
}
}
}
}
@@ -33,12 +33,13 @@ public class BookRestorationService {
if (libraryFiles.isEmpty()) return;
LibraryEntity libraryEntity = libraryFiles.getFirst().getLibraryEntity();
Long libraryId = libraryEntity.getId();
Set<Path> currentPaths = libraryFiles.stream()
.map(LibraryFile::getFullPath)
.collect(Collectors.toSet());
List<BookEntity> toRestore = libraryEntity.getBookEntities().stream()
.filter(book -> Boolean.TRUE.equals(book.getDeleted()))
List<BookEntity> deletedBooks = bookRepository.findDeletedByLibraryIdWithFiles(libraryId);
List<BookEntity> toRestore = deletedBooks.stream()
.filter(book -> book.getBookFiles() != null && !book.getBookFiles().isEmpty())
.filter(book -> currentPaths.contains(book.getFullFilePath()))
.collect(Collectors.toList());
@@ -13,6 +13,7 @@ import org.booklore.model.entity.LibraryPathEntity;
import org.booklore.model.websocket.LogNotification;
import org.booklore.model.websocket.Topic;
import org.booklore.repository.BookAdditionalFileRepository;
import org.booklore.repository.BookRepository;
import org.booklore.repository.LibraryRepository;
import org.booklore.service.NotificationService;
import org.booklore.service.file.FileFingerprint;
@@ -37,6 +38,7 @@ import java.util.stream.Collectors;
public class LibraryProcessingService {
private final LibraryRepository libraryRepository;
private final BookRepository bookRepository;
private final NotificationService notificationService;
private final BookAdditionalFileRepository bookAdditionalFileRepository;
private final FileAsBookProcessor fileAsBookProcessor;
@@ -53,7 +55,8 @@ public class LibraryProcessingService {
notificationService.sendMessage(Topic.LOG, LogNotification.info("Started processing library: " + libraryEntity.getName()));
try {
List<LibraryFile> libraryFiles = libraryFileHelper.getLibraryFiles(libraryEntity);
List<LibraryFile> newFiles = detectNewBookPaths(libraryFiles, libraryEntity);
List<BookEntity> existingBooks = bookRepository.findAllByLibraryIdForRescan(libraryId);
List<LibraryFile> newFiles = detectNewBookPaths(libraryFiles, existingBooks, libraryId);
// Use BookGroupingService for consistent grouping based on organization mode
Map<String, List<LibraryFile>> groups = bookGroupingService.groupForInitialScan(newFiles, libraryEntity);
@@ -69,16 +72,20 @@ public class LibraryProcessingService {
@Transactional
public void rescanLibrary(RescanLibraryContext context) throws IOException {
LibraryEntity libraryEntity = libraryRepository.findByIdWithBooks(context.getLibraryId()).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(context.getLibraryId()));
long libraryId = context.getLibraryId();
LibraryEntity libraryEntity = libraryRepository.findByIdWithPaths(libraryId)
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
notificationService.sendMessage(Topic.LOG, LogNotification.info("Started refreshing library: " + libraryEntity.getName()));
validateLibraryPathsAccessible(libraryEntity);
List<BookEntity> books = bookRepository.findAllByLibraryIdForRescan(libraryId);
List<LibraryFile> allLibraryFiles = libraryFileHelper.getAllLibraryFiles(libraryEntity);
List<LibraryFile> filteredFiles = libraryFileHelper.filterByAllowedFormats(
allLibraryFiles, libraryEntity.getAllowedFormats());
int existingBookCount = libraryEntity.getBookEntities().size();
int existingBookCount = books.size();
if (existingBookCount > 0 && allLibraryFiles.isEmpty()) {
String paths = libraryEntity.getLibraryPaths().stream()
.map(LibraryPathEntity::getPath)
@@ -93,7 +100,7 @@ public class LibraryProcessingService {
log.info("Detected {} removed additional files in library: {}", additionalFileIds.size(), libraryEntity.getName());
bookDeletionService.deleteRemovedAdditionalFiles(additionalFileIds);
}
List<Long> bookIds = detectDeletedBookIds(allLibraryFiles, libraryEntity);
List<Long> bookIds = detectDeletedBookIds(allLibraryFiles, books);
if (!bookIds.isEmpty()) {
log.info("Detected {} removed books in library: {}", bookIds.size(), libraryEntity.getName());
bookDeletionService.processDeletedLibraryFiles(bookIds, allLibraryFiles);
@@ -101,11 +108,12 @@ public class LibraryProcessingService {
bookRestorationService.restoreDeletedBooks(allLibraryFiles);
bookDeletionService.purgeDisallowedFormats(libraryEntity);
entityManager.clear();
// Re-fetch library entity with books to get fresh state after entity manager was cleared
libraryEntity = libraryRepository.findByIdWithBooks(context.getLibraryId())
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(context.getLibraryId()));
// Re-fetch fresh state after entity manager was cleared
libraryEntity = libraryRepository.findByIdWithPaths(libraryId)
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
books = bookRepository.findAllByLibraryIdForRescan(libraryId);
List<LibraryFile> newFiles = detectNewBookPaths(filteredFiles, libraryEntity);
List<LibraryFile> newFiles = detectNewBookPaths(filteredFiles, books, libraryId);
// Use BookGroupingService to determine what to attach vs create new
BookGroupingService.GroupingResult groupingResult = bookGroupingService.groupForRescan(newFiles, libraryEntity);
@@ -137,12 +145,12 @@ public class LibraryProcessingService {
}
}
protected static List<Long> detectDeletedBookIds(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity) {
protected static List<Long> detectDeletedBookIds(List<LibraryFile> libraryFiles, List<BookEntity> books) {
Set<Path> currentFullPaths = libraryFiles.stream()
.map(LibraryFile::getFullPath)
.collect(Collectors.toSet());
return libraryEntity.getBookEntities().stream()
return books.stream()
.filter(book -> (book.getDeleted() == null || !book.getDeleted()))
.filter(book -> {
// Don't mark fileless books as deleted - they're intentionally without files
@@ -155,13 +163,13 @@ public class LibraryProcessingService {
.collect(Collectors.toList());
}
protected List<LibraryFile> detectNewBookPaths(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity) {
Set<String> existingKeys = libraryEntity.getBookEntities().stream()
protected List<LibraryFile> detectNewBookPaths(List<LibraryFile> libraryFiles, List<BookEntity> books, Long libraryId) {
Set<String> existingKeys = books.stream()
.filter(book -> book.getBookFiles() != null && !book.getBookFiles().isEmpty())
.map(this::generateUniqueKey)
.collect(Collectors.toSet());
Set<String> additionalFileKeys = bookAdditionalFileRepository.findByLibraryId(libraryEntity.getId()).stream()
Set<String> additionalFileKeys = bookAdditionalFileRepository.findByLibraryId(libraryId).stream()
.map(this::generateUniqueKey)
.collect(Collectors.toSet());
@@ -51,6 +51,7 @@ import java.util.stream.Collectors;
@Service
@AllArgsConstructor
@DependsOnDatabaseInitialization
@Transactional(readOnly = true)
public class LibraryService {
private static final Set<Long> scanningLibraries = ConcurrentHashMap.newKeySet();
@@ -161,7 +162,8 @@ public class LibraryService {
@Transactional
public Library createLibrary(CreateLibraryRequest request) {
BookLoreUser bookLoreUser = authenticationService.getAuthenticatedUser();
Optional<BookLoreUserEntity> user = userRepository.findById(bookLoreUser.getId());
BookLoreUserEntity userEntity = userRepository.findById(bookLoreUser.getId())
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(bookLoreUser.getId()));
LibraryEntity libraryEntity = LibraryEntity.builder()
.name(request.getName())
@@ -179,9 +181,13 @@ public class LibraryService {
.allowedFormats(request.getAllowedFormats())
.metadataSource(request.getMetadataSource())
.organizationMode(request.getOrganizationMode())
.users(List.of(user.get()))
.users(new HashSet<>(Set.of(userEntity)))
.build();
for (LibraryPathEntity p : libraryEntity.getLibraryPaths()) {
p.setLibrary(libraryEntity);
}
libraryEntity = libraryRepository.save(libraryEntity);
Long libraryId = libraryEntity.getId();
@@ -198,6 +204,7 @@ public class LibraryService {
return libraryMapper.toLibrary(libraryEntity);
}
@Transactional
public void rescanLibrary(long libraryId) {
LibraryEntity lib = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
auditService.log(AuditAction.LIBRARY_SCANNED, "Library", libraryId, "Scanned library: " + lib.getName());
@@ -223,19 +230,16 @@ public class LibraryService {
});
}
@Transactional(readOnly = true)
public Library getLibrary(long libraryId) {
LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
return libraryMapper.toLibrary(libraryEntity);
}
@Transactional(readOnly = true)
public List<Library> getAllLibraries() {
List<LibraryEntity> libraries = libraryRepository.findAll();
return libraries.stream().map(libraryMapper::toLibrary).toList();
}
@Transactional(readOnly = true)
public List<Library> getLibraries() {
BookLoreUser user = authenticationService.getAuthenticatedUser();
BookLoreUserEntity userEntity = userRepository.findByIdWithLibraries(user.getId()).orElseThrow(() -> new UsernameNotFoundException("User not found"));
@@ -251,10 +255,10 @@ public class LibraryService {
@Transactional
public void deleteLibrary(long id) {
LibraryEntity library = libraryRepository.findByIdWithBooks(id)
LibraryEntity library = libraryRepository.findById(id)
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(id));
libraryWatchService.unregisterLibrary(id);
Set<Long> bookIds = library.getBookEntities().stream().map(BookEntity::getId).collect(Collectors.toSet());
Set<Long> bookIds = bookRepository.findBookIdsByLibraryId(id);
fileService.deleteBookCovers(bookIds);
String libraryName = library.getName();
libraryRepository.deleteById(id);
@@ -262,14 +266,12 @@ public class LibraryService {
log.info("Library deleted successfully: {}", id);
}
@Transactional(readOnly = true)
public Book getBook(long libraryId, long bookId) {
libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId).filter(b -> b.getLibrary().getId() == libraryId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
return bookMapper.toBook(bookEntity);
}
@Transactional(readOnly = true)
public List<Book> getBooks(long libraryId) {
libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
List<BookEntity> bookEntities = bookRepository.findAllWithMetadataByLibraryId(libraryId);
@@ -285,7 +287,6 @@ public class LibraryService {
return result;
}
@Transactional(readOnly = true)
public Map<String, Long> getBookCountsByFormat(long libraryId) {
libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
Map<String, Long> counts = new HashMap<>();
@@ -226,7 +226,6 @@ public class BookMetadataService {
.build();
bookMetadataUpdater.setBookMetadata(context);
bookRepository.save(bookEntity);
auditService.log(AuditAction.METADATA_UPDATED, "Book", bookId, "Updated metadata for book: " + bookEntity.getMetadata().getTitle());
return bookMetadataMapper.toBookMetadata(bookEntity.getMetadata(), true);
}
@@ -29,6 +29,7 @@ public class MetadataTaskService {
private final FetchedProposalMapper fetchedProposalMapper;
private final AuthenticationService authenticationService;
@Transactional(readOnly = true)
public Optional<MetadataTaskDetailsResponse> getTaskWithProposals(String taskId) {
return metadataFetchTaskRepository.findById(taskId)
.map(this::buildTaskDetailsResponse);
@@ -64,6 +65,7 @@ public class MetadataTaskService {
.orElse(false);
}
@Transactional
public boolean updateProposalStatus(String taskId, Long proposalId, String statusStr) {
Long userId = authenticationService.getAuthenticatedUser().getId();
Optional<FetchedMetadataProposalStatus> statusOpt = parseStatus(statusStr);
@@ -134,4 +136,4 @@ public class MetadataTaskService {
.filter(n -> n.getTotal() > 0)
.toList();
}
}
}
@@ -34,6 +34,7 @@ import java.util.stream.Collectors;
@Slf4j
@RequiredArgsConstructor
@Service
@Transactional(readOnly = true)
public class ReadingProgressService {
private static final float READING_THRESHOLD = 0.1f;
@@ -10,6 +10,7 @@ import org.booklore.model.entity.AuthorEntity;
import org.booklore.model.entity.BookEntity;
import org.booklore.model.entity.BookMetadataEntity;
import org.booklore.repository.BookRepository;
import org.booklore.repository.projection.BookEmbeddingProjection;
import org.booklore.service.book.BookQueryService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -26,6 +27,7 @@ import java.util.stream.Collectors;
public class BookRecommendationService {
private final BookSimilarityService similarityService;
private final BookVectorService vectorService;
private final BookRepository bookRepository;
private final BookQueryService bookQueryService;
private final BookMapper bookMapper;
@@ -92,7 +94,74 @@ public class BookRecommendationService {
protected List<BookRecommendation> findSimilarBooks(Long bookId, int limit) {
BookEntity target = bookRepository.findByIdWithMetadata(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
List<BookEntity> candidates = bookQueryService.getAllFullBookEntities();
String targetVectorJson = Optional.ofNullable(target.getMetadata())
.map(BookMetadataEntity::getEmbeddingVector)
.orElse(null);
if (targetVectorJson != null) {
double[] targetVector = vectorService.deserializeVector(targetVectorJson);
if (targetVector != null) {
return findSimilarBooksViaEmbeddings(bookId, target, targetVector, limit);
}
}
// Fallback: entity-based similarity (loads all candidates)
return findSimilarBooksViaEntities(bookId, target, limit);
}
private List<BookRecommendation> findSimilarBooksViaEmbeddings(Long bookId, BookEntity target, double[] targetVector, int limit) {
String targetSeriesName = Optional.ofNullable(target.getMetadata())
.map(BookMetadataEntity::getSeriesName)
.map(String::toLowerCase)
.orElse(null);
List<BookEmbeddingProjection> projections = bookRepository.findAllEmbeddingsForRecommendation(bookId);
List<SimpleEntry<Long, Double>> scored = projections.stream()
.filter(p -> {
if (targetSeriesName == null) return true;
String candidateSeries = Optional.ofNullable(p.getSeriesName())
.map(String::toLowerCase)
.orElse(null);
return !targetSeriesName.equals(candidateSeries);
})
.map(p -> {
double[] candidateVector = vectorService.deserializeVector(p.getEmbeddingVector());
double similarity = candidateVector != null
? vectorService.cosineSimilarity(targetVector, candidateVector)
: 0.0;
return new SimpleEntry<>(p.getBookId(), similarity);
})
.filter(entry -> entry.getValue() > 0.1)
.sorted(Map.Entry.<Long, Double>comparingByValue().reversed())
.limit(limit * 3L)
.toList();
Set<Long> topBookIds = scored.stream().map(SimpleEntry::getKey).collect(Collectors.toSet());
Map<Long, BookEntity> bookMap = bookQueryService.findAllWithMetadataByIds(topBookIds).stream()
.collect(Collectors.toMap(BookEntity::getId, Function.identity()));
Map<String, Integer> authorCounts = new HashMap<>();
List<BookRecommendation> recommendations = new ArrayList<>();
for (SimpleEntry<Long, Double> entry : scored) {
if (recommendations.size() >= limit) break;
BookEntity bookEntity = bookMap.get(entry.getKey());
if (bookEntity == null) continue;
Set<String> authorNames = getAuthorNames(bookEntity);
boolean allowed = authorNames.stream()
.allMatch(name -> authorCounts.getOrDefault(name, 0) < MAX_BOOKS_PER_AUTHOR);
if (allowed) {
recommendations.add(new BookRecommendation(bookMapper.toBookWithDescription(bookEntity, false), entry.getValue()));
authorNames.forEach(name -> authorCounts.merge(name, 1, Integer::sum));
}
}
return recommendations;
}
private List<BookRecommendation> findSimilarBooksViaEntities(Long bookId, BookEntity target, int limit) {
List<BookEntity> candidates = bookRepository.findAllForRecommendation(bookId);
String targetSeriesName = Optional.ofNullable(target.getMetadata())
.map(BookMetadataEntity::getSeriesName)
@@ -100,7 +169,6 @@ public class BookRecommendationService {
.orElse(null);
List<SimpleEntry<BookEntity, Double>> scored = candidates.stream()
.filter(candidate -> !candidate.getId().equals(bookId))
.filter(candidate -> {
String candidateSeriesName = Optional.ofNullable(candidate.getMetadata())
.map(BookMetadataEntity::getSeriesName)
@@ -140,4 +208,4 @@ public class BookRecommendationService {
.map(String::toLowerCase)
.collect(Collectors.toSet());
}
}
}
@@ -23,19 +23,18 @@ import java.util.stream.Collectors;
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class ContentRestrictionService {
private final UserContentRestrictionRepository restrictionRepository;
private final UserRepository userRepository;
@Transactional(readOnly = true)
public List<ContentRestriction> getUserRestrictions(Long userId) {
return restrictionRepository.findByUserId(userId).stream()
.map(this::toDto)
.collect(Collectors.toList());
}
@Transactional(readOnly = true)
public ContentRestriction getRestriction(Long restrictionId) {
return restrictionRepository.findById(restrictionId)
.map(this::toDto)
@@ -96,7 +95,6 @@ public class ContentRestrictionService {
restrictionRepository.deleteByUserId(userId);
}
@Transactional(readOnly = true)
public List<BookEntity> applyRestrictions(List<BookEntity> books, Long userId) {
List<UserContentRestrictionEntity> restrictions = restrictionRepository.findByUserId(userId);
@@ -60,6 +60,7 @@ public class FileUploadService {
private final MonitoringRegistrationService monitoringRegistrationService;
private final AuditService auditService;
@Transactional
public void uploadFile(MultipartFile file, long libraryId, long pathId) {
validateFile(file);
@@ -29,6 +29,7 @@ import static org.booklore.model.enums.PermissionType.MANAGE_LIBRARY;
@Slf4j
@Service
@AllArgsConstructor
@Transactional(readOnly = true)
public class BookFilePersistenceService {
private final EntityManager entityManager;
@@ -103,12 +104,10 @@ public class BookFilePersistenceService {
return books.size();
}
@Transactional(readOnly = true)
public Optional<BookEntity> findByLibraryPathSubPathAndFileName(long libraryPathId, String fileSubPath, String fileName) {
return bookRepository.findByLibraryPath_IdAndFileSubPathAndFileName(libraryPathId, fileSubPath, fileName);
}
@Transactional(readOnly = true)
public Optional<BookFileEntity> findBookFileByLibraryPathSubPathAndFileName(long libraryPathId, String fileSubPath, String fileName) {
return bookFileRepository.findByLibraryPathIdAndFileSubPathAndFileName(libraryPathId, fileSubPath, fileName);
}
@@ -130,7 +129,6 @@ public class BookFilePersistenceService {
bookRepository.save(book);
}
@Transactional(readOnly = true)
public long countBookFilesByBookId(Long bookId) {
return bookFileRepository.countByBookId(bookId);
}
@@ -165,4 +163,4 @@ public class BookFilePersistenceService {
bookMapper.toBookWithDescription(book, false), Set.of(PermissionType.ADMIN, PermissionType.MANAGE_LIBRARY));
log.info("[RECOVERED] Book id={} recovered from folder move", book.getId());
}
}
}
@@ -129,7 +129,7 @@ public class LibraryFileEventProcessor {
log.info("[PROCESS] '{}' event for '{}'{}", event.eventKind().name(), fileName,
event.isDirectory() ? " (directory)" : "");
LibraryEntity library = libraryRepository.findById(event.libraryId())
LibraryEntity library = libraryRepository.findByIdWithPaths(event.libraryId())
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(event.libraryId()));
if (library.getLibraryPaths().stream().noneMatch(lp -> path.startsWith(lp.getPath()))) {
@@ -561,4 +561,4 @@ public class LibraryFileEventProcessor {
public record FileEvent(WatchEvent.Kind<?> eventKind, long libraryId, Path fullPath, boolean isDirectory) {
}
}
}
@@ -17,9 +17,9 @@ import org.booklore.service.recommender.BookVectorService;
import org.booklore.task.TaskStatus;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Component;
import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;
@@ -33,6 +33,7 @@ public class BookRecommendationUpdaterTask implements Task {
private final NotificationService notificationService;
private static final int RECOMMENDATION_LIMIT = 25;
private static final int BATCH_SIZE = 500;
private static final long MIN_NOTIFICATION_INTERVAL_MS = 250;
@Override
@@ -57,62 +58,77 @@ public class BookRecommendationUpdaterTask implements Task {
lastNotificationTime = sendTaskProgressNotification(taskId, 0, "Starting book recommendation update", TaskStatus.IN_PROGRESS, lastNotificationTime, true);
List<BookEntity> allBooks = bookQueryService.getAllFullBookEntities();
int totalBooks = allBooks.size();
lastNotificationTime = sendTaskProgressNotification(taskId, 5, String.format("Loaded %d books, generating embeddings...", totalBooks), TaskStatus.IN_PROGRESS, lastNotificationTime, false);
// Load books in batches, generate embeddings, store lightweight data only
long totalBooks = bookQueryService.countAllNonDeleted();
Map<Long, double[]> embeddings = new HashMap<>();
List<BookEntity> booksToUpdate = new ArrayList<>();
Map<Long, String> seriesNames = new HashMap<>();
lastNotificationTime = sendTaskProgressNotification(taskId, 2, String.format("Found %d books, generating embeddings in batches...", totalBooks), TaskStatus.IN_PROGRESS, lastNotificationTime, false);
int embeddingProgress = 0;
for (BookEntity book : allBooks) {
double[] embedding = vectorService.generateEmbedding(book);
embeddings.put(book.getId(), embedding);
int batchPage = 0;
while (true) {
List<BookEntity> batch = bookQueryService.getAllFullBookEntitiesBatch(
PageRequest.of(batchPage, BATCH_SIZE));
if (batch.isEmpty()) break;
if (book.getMetadata() != null) {
String embeddingJson = vectorService.serializeVector(embedding);
if (!Objects.equals(book.getMetadata().getEmbeddingVector(), embeddingJson)) {
book.getMetadata().setEmbeddingVector(embeddingJson);
book.getMetadata().setEmbeddingUpdatedAt(Instant.now());
for (BookEntity book : batch) {
double[] embedding = vectorService.generateEmbedding(book);
embeddings.put(book.getId(), embedding);
// Store series name for similarity filtering
String series = Optional.ofNullable(book.getMetadata())
.map(BookMetadataEntity::getSeriesName)
.map(String::toLowerCase)
.orElse(null);
if (series != null) {
seriesNames.put(book.getId(), series);
}
embeddingProgress++;
}
embeddingProgress++;
if (embeddingProgress % 10 == 0 || embeddingProgress == totalBooks) {
int progress = 5 + (embeddingProgress * 30 / totalBooks);
lastNotificationTime = sendTaskProgressNotification(taskId, progress,
String.format("Generated embeddings: %d/%d books", embeddingProgress, totalBooks),
TaskStatus.IN_PROGRESS, lastNotificationTime, false);
// Save embedding vectors for this batch within a transaction
Map<Long, String> batchEmbeddingJson = new HashMap<>();
for (BookEntity book : batch) {
batchEmbeddingJson.put(book.getId(), vectorService.serializeVector(embeddings.get(book.getId())));
}
bookQueryService.compareAndSaveEmbeddings(batchEmbeddingJson);
int progress = 5 + (int) (embeddingProgress * 30L / totalBooks);
lastNotificationTime = sendTaskProgressNotification(taskId, progress,
String.format("Generated embeddings: %d/%d books", embeddingProgress, totalBooks),
TaskStatus.IN_PROGRESS, lastNotificationTime, false);
if (batch.size() < BATCH_SIZE) break;
batchPage++;
}
lastNotificationTime = sendTaskProgressNotification(taskId, 35, "Computing book similarities...", TaskStatus.IN_PROGRESS, lastNotificationTime, false);
// Compute similarities using only in-memory vectors (no entities needed)
Set<Long> allBookIds = embeddings.keySet();
Map<Long, Set<BookRecommendationLite>> allRecommendations = new HashMap<>();
int processedBooks = 0;
for (BookEntity targetBook : allBooks) {
for (Long targetId : allBookIds) {
try {
double[] targetVector = embeddings.get(targetBook.getId());
double[] targetVector = embeddings.get(targetId);
if (targetVector == null) continue;
String targetSeries = Optional.ofNullable(targetBook.getMetadata())
.map(BookMetadataEntity::getSeriesName)
.map(String::toLowerCase)
.orElse(null);
String targetSeries = seriesNames.get(targetId);
List<BookVectorService.ScoredBook> candidates = allBooks.stream()
.filter(candidate -> !candidate.getId().equals(targetBook.getId()))
.filter(candidate -> {
String candidateSeries = Optional.ofNullable(candidate.getMetadata())
.map(BookMetadataEntity::getSeriesName)
.map(String::toLowerCase)
.orElse(null);
return targetSeries == null || !targetSeries.equals(candidateSeries);
List<BookVectorService.ScoredBook> candidates = allBookIds.stream()
.filter(candidateId -> !candidateId.equals(targetId))
.filter(candidateId -> {
if (targetSeries == null) return true;
String candidateSeries = seriesNames.get(candidateId);
return !targetSeries.equals(candidateSeries);
})
.map(candidate -> {
double[] candidateVector = embeddings.get(candidate.getId());
.map(candidateId -> {
double[] candidateVector = embeddings.get(candidateId);
double similarity = vectorService.cosineSimilarity(targetVector, candidateVector);
return new BookVectorService.ScoredBook(candidate.getId(), similarity);
return new BookVectorService.ScoredBook(candidateId, similarity);
})
.filter(scored -> scored.getScore() > 0.1)
.collect(Collectors.toList());
@@ -127,25 +143,25 @@ public class BookRecommendationUpdaterTask implements Task {
.map(scored -> new BookRecommendationLite(scored.getBookId(), scored.getScore()))
.collect(Collectors.toSet());
targetBook.setSimilarBooksJson(recommendations);
booksToUpdate.add(targetBook);
allRecommendations.put(targetId, recommendations);
} catch (Exception e) {
log.error("{}: Error updating similar books for book ID {}", getTaskType(), targetBook.getId(), e);
log.error("{}: Error computing similarity for book ID {}", getTaskType(), targetId, e);
}
processedBooks++;
if (processedBooks % 10 == 0 || processedBooks == totalBooks) {
int progress = 35 + (processedBooks * 50 / totalBooks);
int progress = 35 + (int) (processedBooks * 50L / totalBooks);
lastNotificationTime = sendTaskProgressNotification(taskId, progress,
String.format("Computing similarities: %d/%d books", processedBooks, totalBooks),
TaskStatus.IN_PROGRESS, lastNotificationTime, false);
}
}
lastNotificationTime = sendTaskProgressNotification(taskId, 85, String.format("Saving recommendations for %d books...", booksToUpdate.size()), TaskStatus.IN_PROGRESS, lastNotificationTime, false);
// Save recommendations in batches
lastNotificationTime = sendTaskProgressNotification(taskId, 85, String.format("Saving recommendations for %d books...", allRecommendations.size()), TaskStatus.IN_PROGRESS, lastNotificationTime, false);
bookQueryService.saveAll(booksToUpdate);
bookQueryService.saveRecommendationsInBatches(allRecommendations, BATCH_SIZE);
long endTime = System.currentTimeMillis();
log.info("{}: Task completed. Duration: {} ms", getTaskType(), endTime - startTime);
@@ -21,8 +21,8 @@ public class EpubCfiService {
public EpubCfiService() {
this.documentCache = Caffeine.newBuilder()
.maximumSize(50)
.expireAfterAccess(Duration.ofMinutes(10))
.maximumSize(10)
.expireAfterAccess(Duration.ofMinutes(5))
.softValues()
.build();
}
@@ -24,7 +24,6 @@ app:
disk-type: ${DISK_TYPE:LOCAL}
server:
max-http-header-size: 128KB
forward-headers-strategy: native
port: ${BOOKLORE_PORT:6060}
compression:
@@ -34,8 +33,9 @@ server:
tomcat:
relaxed-query-chars: '[,],%,{,},|'
threads:
max: 20 # Virtual threads handle concurrency; platform threads just overhead
min-spare: 4
max: 10 # Virtual threads handle concurrency; platform threads just overhead
min-spare: 2
max-http-request-header-size: 64KB
spring:
jackson:
@@ -62,6 +62,7 @@ spring:
password: ${DATABASE_PASSWORD:${MYSQL_ROOT_PASSWORD}}
hikari:
pool-name: BookloreHikariPool
auto-commit: false # Required counterpart to provider_disables_autocommit
max-lifetime: 580000 # 9.6 minutes (avoid DB-side connection cuts)
connection-test-query: SELECT 1
connection-timeout: 30000 # 30s to acquire a connection before timeout
@@ -69,7 +70,7 @@ spring:
minimum-idle: 2 # Minimal warm connections; virtual threads handle bursts
idle-timeout: 300000 # 5 minutes before idle connections are closed
jpa:
open-in-view: true # true until we implement proper DTOs and service-layer data fetching
open-in-view: false
hibernate:
naming:
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
@@ -78,16 +79,21 @@ spring:
hibernate:
query:
timeout: 30 # 30s max for any HQL/JPQL query
plan_cache_max_size: 256 # Reduce from 2048 default; ~200 unique queries max
plan_cache_max_size: 128 # Reduce from 2048 default; small self-hosted app
plan_parameter_metadata_max_size: 32 # Reduce from 128 default
in_clause_parameter_padding: true # Pad IN params to power-of-2; fewer unique plan cache entries
fail_on_pagination_over_collection_fetch: true # Fail fast when paginating over collection fetches (in-memory pagination)
jdbc:
time_zone: UTC
batch_size: 500
batch_size: 100
fetch_size: 50 # Reduce JDBC roundtrips for large result sets
order_inserts: true
order_updates: true
batch_versioned_data: true # Allow batching UPDATEs on @Version entities
connection:
provider_disables_autocommit: true # Skip unnecessary JDBC autocommit check; reduces roundtrips
default_batch_fetch_size: 16 # Global batch fetch for all lazy collections (prevents N+1)
log_slow_query: ${HIBERNATE_SLOW_QUERY_MS:500} # Log queries taking longer than 500ms (see org.hibernate.SQL_SLOW)
generate_statistics: ${HIBERNATE_STATISTICS:false}
threads:
virtual: