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:
co-authored by
coderabbitai[bot]
parent
be0b717ff4
commit
ad3a981ad1
+8
-1
@@ -66,7 +66,14 @@ ENV JAVA_TOOL_OPTIONS="-XX:+UseShenandoahGC \
|
||||
-XX:+UseCompactObjectHeaders \
|
||||
-XX:MaxRAMPercentage=60.0 \
|
||||
-XX:InitialRAMPercentage=8.0 \
|
||||
-XX:+ExitOnOutOfMemoryError"
|
||||
-XX:+ExitOnOutOfMemoryError \
|
||||
-XX:MaxMetaspaceSize=192m \
|
||||
-XX:ReservedCodeCacheSize=64m \
|
||||
-Xss512k \
|
||||
-XX:CICompilerCount=2 \
|
||||
-XX:+UnlockExperimentalVMOptions \
|
||||
-XX:ShenandoahUncommitDelay=5000 \
|
||||
-XX:ShenandoahGuaranteedGCInterval=30000"
|
||||
|
||||
RUN apk add --no-cache su-exec libstdc++ libgcc libarchive && \
|
||||
mkdir -p /bookdrop
|
||||
|
||||
@@ -133,12 +133,14 @@ dependencies {
|
||||
|
||||
hibernate {
|
||||
enhancement {
|
||||
enableAssociationManagement = true
|
||||
enableAssociationManagement = false
|
||||
enableLazyInitialization = true
|
||||
}
|
||||
}
|
||||
|
||||
tasks.named<Test>("test") {
|
||||
useJUnitPlatform()
|
||||
maxHeapSize = "2560m"
|
||||
jvmArgs("-XX:+EnableDynamicAgentLoading", "--enable-native-access=ALL-UNNAMED")
|
||||
finalizedBy(tasks.named("jacocoTestReport"))
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
|
||||
+1
-1
@@ -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();
|
||||
|
||||
+1
-1
@@ -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();
|
||||
}
|
||||
|
||||
+1
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+8
-3
@@ -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);
|
||||
}
|
||||
|
||||
+7
@@ -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());
|
||||
|
||||
+21
-13
@@ -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;
|
||||
|
||||
+71
-3
@@ -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());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+1
-3
@@ -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);
|
||||
|
||||
|
||||
+2
-4
@@ -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());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -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) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+60
-44
@@ -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:
|
||||
|
||||
+1
-1
@@ -149,7 +149,7 @@ class LogoutServiceTest {
|
||||
assertThat(token1.getRevocationDate()).isNotNull();
|
||||
assertThat(token2.isRevoked()).isTrue();
|
||||
assertThat(token2.getRevocationDate()).isNotNull();
|
||||
verify(refreshTokenRepository, times(2)).save(any(RefreshTokenEntity.class));
|
||||
verify(refreshTokenRepository).saveAll(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+6
-4
@@ -8,6 +8,7 @@ import org.booklore.model.entity.BookMetadataEntity;
|
||||
import org.booklore.model.entity.LibraryEntity;
|
||||
import org.booklore.model.entity.LibraryPathEntity;
|
||||
import org.booklore.service.task.TaskCronService;
|
||||
import org.flywaydb.core.Flyway;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
@@ -44,7 +45,8 @@ import static org.mockito.Mockito.mock;
|
||||
"spring.task.scheduling.enabled=false",
|
||||
"app.task.scan-library-cron=*/1 * * * * *",
|
||||
"app.task.process-bookdrop-cron=*/1 * * * * *",
|
||||
"app.features.oidc-enabled=false"
|
||||
"app.features.oidc-enabled=false",
|
||||
"spring.jpa.properties.hibernate.connection.provider_disables_autocommit=false"
|
||||
})
|
||||
@Import(BookOpdsRepositoryDataJpaTest.TestConfig.class)
|
||||
class BookOpdsRepositoryDataJpaTest {
|
||||
@@ -59,8 +61,8 @@ class BookOpdsRepositoryDataJpaTest {
|
||||
public static class TestConfig {
|
||||
@Bean("flyway")
|
||||
@Primary
|
||||
public org.flywaydb.core.Flyway flyway() {
|
||||
return mock(org.flywaydb.core.Flyway.class);
|
||||
public Flyway flyway() {
|
||||
return mock(Flyway.class);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@@ -113,4 +115,4 @@ class BookOpdsRepositoryDataJpaTest {
|
||||
assertThat(result).hasSize(1);
|
||||
assertThat(result.get(0).getId()).isEqualTo(book.getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,7 +48,8 @@ import static org.mockito.Mockito.mock;
|
||||
"spring.task.scheduling.enabled=false",
|
||||
"app.task.scan-library-cron=*/1 * * * * *",
|
||||
"app.task.process-bookdrop-cron=*/1 * * * * *",
|
||||
"app.features.oidc-enabled=false"
|
||||
"app.features.oidc-enabled=false",
|
||||
"spring.jpa.properties.hibernate.connection.provider_disables_autocommit=false"
|
||||
})
|
||||
@Import(BookRuleEvaluatorEdgeCasesTest.TestConfig.class)
|
||||
class BookRuleEvaluatorEdgeCasesTest {
|
||||
|
||||
+5
-3
@@ -8,6 +8,7 @@ import org.booklore.model.entity.*;
|
||||
import org.booklore.model.enums.ReadStatus;
|
||||
import org.booklore.repository.BookRepository;
|
||||
import org.booklore.service.task.TaskCronService;
|
||||
import org.flywaydb.core.Flyway;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -52,7 +53,8 @@ import static org.mockito.Mockito.mock;
|
||||
"spring.task.scheduling.enabled=false",
|
||||
"app.task.scan-library-cron=*/1 * * * * *",
|
||||
"app.task.process-bookdrop-cron=*/1 * * * * *",
|
||||
"app.features.oidc-enabled=false"
|
||||
"app.features.oidc-enabled=false",
|
||||
"spring.jpa.properties.hibernate.connection.provider_disables_autocommit=false"
|
||||
})
|
||||
@Import(BookRuleEvaluatorFieldCoverageTest.TestConfig.class)
|
||||
class BookRuleEvaluatorFieldCoverageTest {
|
||||
@@ -61,8 +63,8 @@ class BookRuleEvaluatorFieldCoverageTest {
|
||||
static class TestConfig {
|
||||
@Bean("flyway")
|
||||
@Primary
|
||||
public org.flywaydb.core.Flyway flyway() {
|
||||
return mock(org.flywaydb.core.Flyway.class);
|
||||
public Flyway flyway() {
|
||||
return mock(Flyway.class);
|
||||
}
|
||||
|
||||
@Bean
|
||||
|
||||
+5
-3
@@ -9,6 +9,7 @@ import org.booklore.model.enums.BookFileType;
|
||||
import org.booklore.model.enums.ReadStatus;
|
||||
import org.booklore.repository.BookRepository;
|
||||
import org.booklore.service.task.TaskCronService;
|
||||
import org.flywaydb.core.Flyway;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -45,7 +46,8 @@ import static org.mockito.Mockito.mock;
|
||||
"spring.task.scheduling.enabled=false",
|
||||
"app.task.scan-library-cron=*/1 * * * * *",
|
||||
"app.task.process-bookdrop-cron=*/1 * * * * *",
|
||||
"app.features.oidc-enabled=false"
|
||||
"app.features.oidc-enabled=false",
|
||||
"spring.jpa.properties.hibernate.connection.provider_disables_autocommit=false"
|
||||
})
|
||||
@Import(BookRuleEvaluatorNumericFieldsTest.TestConfig.class)
|
||||
class BookRuleEvaluatorNumericFieldsTest {
|
||||
@@ -54,8 +56,8 @@ class BookRuleEvaluatorNumericFieldsTest {
|
||||
static class TestConfig {
|
||||
@Bean("flyway")
|
||||
@Primary
|
||||
public org.flywaydb.core.Flyway flyway() {
|
||||
return mock(org.flywaydb.core.Flyway.class);
|
||||
public Flyway flyway() {
|
||||
return mock(Flyway.class);
|
||||
}
|
||||
|
||||
@Bean
|
||||
|
||||
+5
-3
@@ -10,6 +10,7 @@ import org.booklore.model.enums.ComicCreatorRole;
|
||||
import org.booklore.model.enums.ReadStatus;
|
||||
import org.booklore.repository.BookRepository;
|
||||
import org.booklore.service.task.TaskCronService;
|
||||
import org.flywaydb.core.Flyway;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -51,7 +52,8 @@ import static org.mockito.Mockito.mock;
|
||||
"spring.task.scheduling.enabled=false",
|
||||
"app.task.scan-library-cron=*/1 * * * * *",
|
||||
"app.task.process-bookdrop-cron=*/1 * * * * *",
|
||||
"app.features.oidc-enabled=false"
|
||||
"app.features.oidc-enabled=false",
|
||||
"spring.jpa.properties.hibernate.connection.provider_disables_autocommit=false"
|
||||
})
|
||||
@Import(BookRuleEvaluatorServiceIntegrationTest.TestConfig.class)
|
||||
class BookRuleEvaluatorServiceIntegrationTest {
|
||||
@@ -60,8 +62,8 @@ class BookRuleEvaluatorServiceIntegrationTest {
|
||||
static class TestConfig {
|
||||
@Bean("flyway")
|
||||
@Primary
|
||||
public org.flywaydb.core.Flyway flyway() {
|
||||
return mock(org.flywaydb.core.Flyway.class);
|
||||
public Flyway flyway() {
|
||||
return mock(Flyway.class);
|
||||
}
|
||||
|
||||
@Bean
|
||||
|
||||
@@ -0,0 +1,962 @@
|
||||
package org.booklore.service;
|
||||
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.PersistenceContext;
|
||||
import org.booklore.BookloreApplication;
|
||||
import org.booklore.model.entity.*;
|
||||
import org.booklore.model.enums.BookFileType;
|
||||
import org.booklore.repository.BookRepository;
|
||||
import org.booklore.repository.LibraryRepository;
|
||||
import org.booklore.service.task.TaskCronService;
|
||||
import org.flywaydb.core.Flyway;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.test.context.TestPropertySource;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
/**
|
||||
* Integration tests verifying Hibernate entity relationships, lazy loading,
|
||||
* and transaction boundaries work correctly after the Hibernate refactoring.
|
||||
*
|
||||
* These tests run against H2 with create-drop DDL, exercising real JPA persistence
|
||||
* to catch regressions that unit tests with mocks cannot detect.
|
||||
*/
|
||||
@SpringBootTest(classes = BookloreApplication.class)
|
||||
@Transactional
|
||||
@TestPropertySource(properties = {
|
||||
"spring.flyway.enabled=false",
|
||||
"spring.jpa.hibernate.ddl-auto=create-drop",
|
||||
"spring.jpa.database-platform=org.hibernate.dialect.H2Dialect",
|
||||
"spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect",
|
||||
"spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1",
|
||||
"spring.datasource.driver-class-name=org.h2.Driver",
|
||||
"spring.datasource.username=sa",
|
||||
"spring.datasource.password=",
|
||||
"app.path-config=build/tmp/test-config",
|
||||
"app.bookdrop-folder=build/tmp/test-bookdrop",
|
||||
"spring.main.allow-bean-definition-overriding=true",
|
||||
"spring.task.scheduling.enabled=false",
|
||||
"app.task.scan-library-cron=*/1 * * * * *",
|
||||
"app.task.process-bookdrop-cron=*/1 * * * * *",
|
||||
"app.features.oidc-enabled=false",
|
||||
"spring.jpa.properties.hibernate.connection.provider_disables_autocommit=false"
|
||||
})
|
||||
@Import(HibernateRegressionTest.TestConfig.class)
|
||||
class HibernateRegressionTest {
|
||||
|
||||
@Autowired
|
||||
private LibraryRepository libraryRepository;
|
||||
|
||||
@Autowired
|
||||
private BookRepository bookRepository;
|
||||
|
||||
@PersistenceContext
|
||||
private EntityManager entityManager;
|
||||
|
||||
@org.springframework.boot.test.context.TestConfiguration
|
||||
public static class TestConfig {
|
||||
@Bean("flyway")
|
||||
@Primary
|
||||
public Flyway flyway() {
|
||||
return mock(Flyway.class);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Primary
|
||||
public TaskCronService taskCronService() {
|
||||
return mock(TaskCronService.class);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void contextLoads() {
|
||||
assertThat(libraryRepository).isNotNull();
|
||||
assertThat(bookRepository).isNotNull();
|
||||
}
|
||||
|
||||
@Nested
|
||||
class LibraryPathBackReference {
|
||||
|
||||
/**
|
||||
* Regression: createLibrary() must set LibraryPathEntity.library back-reference.
|
||||
* Without enableAssociationManagement, Hibernate no longer auto-manages
|
||||
* bidirectional relationships. If the back-reference is missing, the FK
|
||||
* column library_id is NULL and paths are not linked to the library.
|
||||
*/
|
||||
@Test
|
||||
void libraryPathsMustHaveLibraryBackReference_whenPersistedViaCascade() {
|
||||
LibraryEntity library = LibraryEntity.builder()
|
||||
.name("Cascade Test Library")
|
||||
.icon("book")
|
||||
.watch(false)
|
||||
.libraryPaths(new ArrayList<>(List.of(
|
||||
LibraryPathEntity.builder().path("/books/fiction").build(),
|
||||
LibraryPathEntity.builder().path("/books/nonfiction").build()
|
||||
)))
|
||||
.build();
|
||||
|
||||
// Simulate what createLibrary() must do: set the back-reference
|
||||
library.getLibraryPaths().forEach(p -> p.setLibrary(library));
|
||||
|
||||
LibraryEntity saved = libraryRepository.saveAndFlush(library);
|
||||
entityManager.clear();
|
||||
|
||||
LibraryEntity reloaded = libraryRepository.findByIdWithPaths(saved.getId()).orElseThrow();
|
||||
|
||||
assertThat(reloaded.getLibraryPaths()).hasSize(2);
|
||||
for (LibraryPathEntity path : reloaded.getLibraryPaths()) {
|
||||
assertThat(path.getLibrary()).isNotNull();
|
||||
assertThat(path.getLibrary().getId()).isEqualTo(reloaded.getId());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify that the owning side FK is actually persisted to the DB and
|
||||
* the library can find its paths after a fresh session load.
|
||||
*/
|
||||
@Test
|
||||
void libraryPathForeignKey_isPersistedCorrectly() {
|
||||
LibraryEntity library = LibraryEntity.builder()
|
||||
.name("FK Test Library")
|
||||
.icon("book")
|
||||
.watch(false)
|
||||
.build();
|
||||
entityManager.persist(library);
|
||||
entityManager.flush();
|
||||
|
||||
LibraryPathEntity path = LibraryPathEntity.builder()
|
||||
.library(library)
|
||||
.path("/test/path")
|
||||
.build();
|
||||
entityManager.persist(path);
|
||||
entityManager.flush();
|
||||
entityManager.clear();
|
||||
|
||||
// Verify via JPQL that the FK is set
|
||||
Long count = entityManager.createQuery(
|
||||
"SELECT COUNT(lp) FROM LibraryPathEntity lp WHERE lp.library.id = :libId", Long.class)
|
||||
.setParameter("libId", library.getId())
|
||||
.getSingleResult();
|
||||
|
||||
assertThat(count).isEqualTo(1L);
|
||||
}
|
||||
|
||||
/**
|
||||
* Without back-reference, cascade persist puts NULL in library_id.
|
||||
* This test verifies the issue exists if back-ref is not set,
|
||||
* by checking constraint violation.
|
||||
*/
|
||||
@Test
|
||||
void cascadePersist_withoutBackReference_failsWithConstraintViolation() {
|
||||
LibraryEntity library = LibraryEntity.builder()
|
||||
.name("Missing BackRef Library")
|
||||
.icon("book")
|
||||
.watch(false)
|
||||
.libraryPaths(new ArrayList<>(List.of(
|
||||
LibraryPathEntity.builder().path("/dangling").build()
|
||||
)))
|
||||
.build();
|
||||
// Intentionally NOT setting library back-reference
|
||||
|
||||
Assertions.assertThrows(
|
||||
org.springframework.dao.DataIntegrityViolationException.class,
|
||||
() -> {
|
||||
libraryRepository.saveAndFlush(library);
|
||||
entityManager.flush();
|
||||
},
|
||||
"Should fail because library_id is NOT NULL but no back-reference was set"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class EntityGraphQueries {
|
||||
|
||||
private LibraryEntity library;
|
||||
private LibraryPathEntity libraryPath;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
library = LibraryEntity.builder()
|
||||
.name("EntityGraph Test Library")
|
||||
.icon("book")
|
||||
.watch(false)
|
||||
.build();
|
||||
entityManager.persist(library);
|
||||
|
||||
libraryPath = LibraryPathEntity.builder()
|
||||
.library(library)
|
||||
.path("/test/books")
|
||||
.build();
|
||||
entityManager.persist(libraryPath);
|
||||
entityManager.flush();
|
||||
}
|
||||
|
||||
/**
|
||||
* findByIdWithPaths must eagerly load libraryPaths so they are
|
||||
* accessible outside a Hibernate session (e.g., in virtual threads).
|
||||
*/
|
||||
@Test
|
||||
void findByIdWithPaths_loadsLibraryPathsEagerly() {
|
||||
entityManager.clear();
|
||||
|
||||
LibraryEntity loaded = libraryRepository.findByIdWithPaths(library.getId()).orElseThrow();
|
||||
|
||||
// Detach to simulate outside-session access
|
||||
entityManager.detach(loaded);
|
||||
|
||||
// This must NOT throw LazyInitializationException
|
||||
assertThat(loaded.getLibraryPaths()).hasSize(1);
|
||||
assertThat(loaded.getLibraryPaths().get(0).getPath()).isEqualTo("/test/books");
|
||||
}
|
||||
|
||||
/**
|
||||
* findByIdWithBooks must eagerly load bookEntities.
|
||||
*/
|
||||
@Test
|
||||
void findByIdWithBooks_loadsBookEntitiesEagerly() {
|
||||
BookEntity book = BookEntity.builder()
|
||||
.library(library)
|
||||
.libraryPath(libraryPath)
|
||||
.addedOn(Instant.now())
|
||||
.deleted(false)
|
||||
.build();
|
||||
entityManager.persist(book);
|
||||
entityManager.flush();
|
||||
entityManager.clear();
|
||||
|
||||
LibraryEntity loaded = libraryRepository.findByIdWithBooks(library.getId()).orElseThrow();
|
||||
entityManager.detach(loaded);
|
||||
|
||||
assertThat(loaded.getBookEntities()).hasSize(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* findByIdWithBookFiles must eagerly load bookFiles via EntityGraph.
|
||||
*/
|
||||
@Test
|
||||
void findByIdWithBookFiles_loadsBookFilesEagerly() {
|
||||
BookEntity book = BookEntity.builder()
|
||||
.library(library)
|
||||
.libraryPath(libraryPath)
|
||||
.addedOn(Instant.now())
|
||||
.deleted(false)
|
||||
.build();
|
||||
entityManager.persist(book);
|
||||
entityManager.flush();
|
||||
|
||||
BookFileEntity bookFile = BookFileEntity.builder()
|
||||
.book(book)
|
||||
.fileName("test.epub")
|
||||
.fileSubPath("")
|
||||
.isBookFormat(true)
|
||||
.bookType(BookFileType.EPUB)
|
||||
.fileSizeKb(100L)
|
||||
.initialHash("abc123")
|
||||
.currentHash("abc123")
|
||||
.addedOn(Instant.now())
|
||||
.build();
|
||||
entityManager.persist(bookFile);
|
||||
entityManager.flush();
|
||||
entityManager.clear();
|
||||
|
||||
BookEntity loaded = bookRepository.findByIdWithBookFiles(book.getId()).orElseThrow();
|
||||
entityManager.detach(loaded);
|
||||
|
||||
// Must NOT throw LazyInitializationException
|
||||
assertThat(loaded.getBookFiles()).hasSize(1);
|
||||
assertThat(loaded.getBookFiles().get(0).getFileName()).isEqualTo("test.epub");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class BookEntityDefaults {
|
||||
|
||||
/**
|
||||
* Regression: BookEntity.deleted must default to FALSE (not null)
|
||||
* so that queries filtering on deleted work correctly.
|
||||
*/
|
||||
@Test
|
||||
void bookEntity_deletedFieldDefaultsToFalse() {
|
||||
LibraryEntity library = LibraryEntity.builder()
|
||||
.name("Defaults Test")
|
||||
.icon("book")
|
||||
.watch(false)
|
||||
.build();
|
||||
entityManager.persist(library);
|
||||
|
||||
LibraryPathEntity path = LibraryPathEntity.builder()
|
||||
.library(library)
|
||||
.path("/test")
|
||||
.build();
|
||||
entityManager.persist(path);
|
||||
|
||||
BookEntity book = BookEntity.builder()
|
||||
.library(library)
|
||||
.libraryPath(path)
|
||||
.addedOn(Instant.now())
|
||||
.build();
|
||||
entityManager.persist(book);
|
||||
entityManager.flush();
|
||||
entityManager.clear();
|
||||
|
||||
BookEntity loaded = entityManager.find(BookEntity.class, book.getId());
|
||||
assertThat(loaded.getDeleted()).isEqualTo(Boolean.FALSE);
|
||||
}
|
||||
|
||||
/**
|
||||
* findByIdWithBookFiles must find books where deleted = false.
|
||||
*/
|
||||
@Test
|
||||
void findByIdWithBookFiles_findsNonDeletedBook() {
|
||||
LibraryEntity library = LibraryEntity.builder()
|
||||
.name("Non-deleted Test")
|
||||
.icon("book")
|
||||
.watch(false)
|
||||
.build();
|
||||
entityManager.persist(library);
|
||||
|
||||
LibraryPathEntity path = LibraryPathEntity.builder()
|
||||
.library(library)
|
||||
.path("/test")
|
||||
.build();
|
||||
entityManager.persist(path);
|
||||
|
||||
BookEntity book = BookEntity.builder()
|
||||
.library(library)
|
||||
.libraryPath(path)
|
||||
.addedOn(Instant.now())
|
||||
.deleted(false)
|
||||
.build();
|
||||
entityManager.persist(book);
|
||||
entityManager.flush();
|
||||
entityManager.clear();
|
||||
|
||||
assertThat(bookRepository.findByIdWithBookFiles(book.getId())).isPresent();
|
||||
}
|
||||
|
||||
/**
|
||||
* findByIdWithBookFiles must NOT find soft-deleted books.
|
||||
*/
|
||||
@Test
|
||||
void findByIdWithBookFiles_excludesDeletedBooks() {
|
||||
LibraryEntity library = LibraryEntity.builder()
|
||||
.name("Deleted Test")
|
||||
.icon("book")
|
||||
.watch(false)
|
||||
.build();
|
||||
entityManager.persist(library);
|
||||
|
||||
LibraryPathEntity path = LibraryPathEntity.builder()
|
||||
.library(library)
|
||||
.path("/test")
|
||||
.build();
|
||||
entityManager.persist(path);
|
||||
|
||||
BookEntity book = BookEntity.builder()
|
||||
.library(library)
|
||||
.libraryPath(path)
|
||||
.addedOn(Instant.now())
|
||||
.deleted(true)
|
||||
.build();
|
||||
entityManager.persist(book);
|
||||
entityManager.flush();
|
||||
entityManager.clear();
|
||||
|
||||
assertThat(bookRepository.findByIdWithBookFiles(book.getId())).isEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class CollectionInitialization {
|
||||
|
||||
/**
|
||||
* Verify that @Builder.Default collection fields are initialized
|
||||
* and not null after entity construction via builder.
|
||||
*/
|
||||
@Test
|
||||
void libraryEntity_collectionsAreInitialized() {
|
||||
LibraryEntity library = LibraryEntity.builder()
|
||||
.name("Init Test")
|
||||
.icon("book")
|
||||
.watch(false)
|
||||
.build();
|
||||
|
||||
assertThat(library.getLibraryPaths()).isNotNull();
|
||||
assertThat(library.getBookEntities()).isNotNull();
|
||||
assertThat(library.getUsers()).isNotNull();
|
||||
assertThat(library.getFormatPriority()).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void bookEntity_collectionsAreInitialized() {
|
||||
BookEntity book = BookEntity.builder()
|
||||
.addedOn(Instant.now())
|
||||
.build();
|
||||
|
||||
assertThat(book.getBookFiles()).isNotNull();
|
||||
assertThat(book.getShelves()).isNotNull();
|
||||
assertThat(book.getUserBookProgress()).isNotNull();
|
||||
assertThat(book.getDeleted()).isEqualTo(Boolean.FALSE);
|
||||
assertThat(book.getIsPhysical()).isEqualTo(Boolean.FALSE);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class LibraryScanSimulation {
|
||||
|
||||
/**
|
||||
* Simulate the library scan flow: create library with paths,
|
||||
* then verify paths can be loaded and iterated for scanning.
|
||||
* This is the exact flow broken when enableAssociationManagement
|
||||
* was removed paths had NULL library_id so scanning found 0 paths.
|
||||
*/
|
||||
@Test
|
||||
void libraryWithPaths_canBeLoadedAndIteratedForScanning() {
|
||||
// Simulate LibraryService.createLibrary() flow
|
||||
LibraryEntity library = LibraryEntity.builder()
|
||||
.name("Scan Simulation Library")
|
||||
.icon("book")
|
||||
.watch(false)
|
||||
.libraryPaths(new ArrayList<>(List.of(
|
||||
LibraryPathEntity.builder().path("/books").build(),
|
||||
LibraryPathEntity.builder().path("/audiobooks").build()
|
||||
)))
|
||||
.build();
|
||||
|
||||
library.getLibraryPaths().forEach(p -> p.setLibrary(library));
|
||||
|
||||
libraryRepository.saveAndFlush(library);
|
||||
entityManager.clear();
|
||||
|
||||
LibraryEntity loaded = libraryRepository.findByIdWithPaths(library.getId()).orElseThrow();
|
||||
|
||||
List<String> pathStrings = loaded.getLibraryPaths().stream()
|
||||
.map(LibraryPathEntity::getPath)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(pathStrings).containsExactlyInAnyOrder("/books", "/audiobooks");
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify the updateLibrary flow — updating paths preserves back-references.
|
||||
*/
|
||||
@Test
|
||||
void updateLibraryPaths_preservesBackReferences() {
|
||||
LibraryEntity library = LibraryEntity.builder()
|
||||
.name("Update Test Library")
|
||||
.icon("book")
|
||||
.watch(false)
|
||||
.build();
|
||||
entityManager.persist(library);
|
||||
|
||||
LibraryPathEntity path1 = LibraryPathEntity.builder()
|
||||
.library(library)
|
||||
.path("/old/path")
|
||||
.build();
|
||||
entityManager.persist(path1);
|
||||
entityManager.flush();
|
||||
entityManager.clear();
|
||||
|
||||
// Simulate updateLibrary() — load, clear paths, add new ones
|
||||
LibraryEntity loaded = libraryRepository.findByIdWithPaths(library.getId()).orElseThrow();
|
||||
loaded.getLibraryPaths().clear();
|
||||
|
||||
LibraryPathEntity newPath = LibraryPathEntity.builder()
|
||||
.library(loaded) // back-reference set here
|
||||
.path("/new/path")
|
||||
.build();
|
||||
loaded.getLibraryPaths().add(newPath);
|
||||
|
||||
libraryRepository.saveAndFlush(loaded);
|
||||
entityManager.clear();
|
||||
|
||||
LibraryEntity reloaded = libraryRepository.findByIdWithPaths(library.getId()).orElseThrow();
|
||||
assertThat(reloaded.getLibraryPaths()).hasSize(1);
|
||||
assertThat(reloaded.getLibraryPaths().get(0).getPath()).isEqualTo("/new/path");
|
||||
assertThat(reloaded.getLibraryPaths().get(0).getLibrary().getId()).isEqualTo(library.getId());
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class BookCreationFlow {
|
||||
|
||||
/**
|
||||
* Simulate BookCreatorService.createShellBook() — verify book with
|
||||
* related entities can be saved and reloaded with all relationships intact.
|
||||
*/
|
||||
@Test
|
||||
void createShellBook_savesAllRelationships() {
|
||||
LibraryEntity library = LibraryEntity.builder()
|
||||
.name("Book Creation Library")
|
||||
.icon("book")
|
||||
.watch(false)
|
||||
.build();
|
||||
entityManager.persist(library);
|
||||
|
||||
LibraryPathEntity libraryPath = LibraryPathEntity.builder()
|
||||
.library(library)
|
||||
.path("/books")
|
||||
.build();
|
||||
entityManager.persist(libraryPath);
|
||||
entityManager.flush();
|
||||
|
||||
BookEntity book = BookEntity.builder()
|
||||
.library(library)
|
||||
.libraryPath(libraryPath)
|
||||
.addedOn(Instant.now())
|
||||
.bookFiles(new ArrayList<>())
|
||||
.build();
|
||||
|
||||
BookFileEntity bookFile = BookFileEntity.builder()
|
||||
.book(book)
|
||||
.fileName("test.epub")
|
||||
.fileSubPath("")
|
||||
.isBookFormat(true)
|
||||
.bookType(BookFileType.EPUB)
|
||||
.fileSizeKb(500L)
|
||||
.initialHash("hash1")
|
||||
.currentHash("hash1")
|
||||
.addedOn(Instant.now())
|
||||
.build();
|
||||
book.getBookFiles().add(bookFile);
|
||||
|
||||
BookMetadataEntity metadata = BookMetadataEntity.builder()
|
||||
.book(book)
|
||||
.title("Test Book Title")
|
||||
.build();
|
||||
book.setMetadata(metadata);
|
||||
|
||||
entityManager.persist(book);
|
||||
entityManager.flush();
|
||||
entityManager.clear();
|
||||
|
||||
BookEntity loaded = bookRepository.findByIdWithBookFiles(book.getId()).orElseThrow();
|
||||
|
||||
assertThat(loaded.getLibrary().getId()).isEqualTo(library.getId());
|
||||
assertThat(loaded.getLibraryPath().getId()).isEqualTo(libraryPath.getId());
|
||||
assertThat(loaded.getBookFiles()).hasSize(1);
|
||||
assertThat(loaded.getBookFiles().get(0).getFileName()).isEqualTo("test.epub");
|
||||
assertThat(loaded.getMetadata().getTitle()).isEqualTo("Test Book Title");
|
||||
assertThat(loaded.getDeleted()).isFalse();
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify that saveAndFlush generates an ID that can be used
|
||||
* to refetch the book — critical for bookdrop finalization flow
|
||||
* where processFile() saves in REQUIRES_NEW and the parent
|
||||
* transaction needs to find it.
|
||||
*/
|
||||
@Test
|
||||
void saveAndFlush_generatesIdForImmediateRetrieval() {
|
||||
LibraryEntity library = LibraryEntity.builder()
|
||||
.name("SaveFlush Library")
|
||||
.icon("book")
|
||||
.watch(false)
|
||||
.build();
|
||||
entityManager.persist(library);
|
||||
|
||||
LibraryPathEntity libraryPath = LibraryPathEntity.builder()
|
||||
.library(library)
|
||||
.path("/books")
|
||||
.build();
|
||||
entityManager.persist(libraryPath);
|
||||
entityManager.flush();
|
||||
|
||||
BookEntity book = BookEntity.builder()
|
||||
.library(library)
|
||||
.libraryPath(libraryPath)
|
||||
.addedOn(Instant.now())
|
||||
.build();
|
||||
|
||||
BookEntity saved = bookRepository.saveAndFlush(book);
|
||||
|
||||
assertThat(saved.getId()).isNotNull();
|
||||
assertThat(bookRepository.findByIdWithBookFiles(saved.getId())).isPresent();
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class FindAllWithPathsQuery {
|
||||
|
||||
/**
|
||||
* Verify findAllWithPaths EntityGraph loads paths for all libraries.
|
||||
*/
|
||||
@Test
|
||||
void findAllWithPaths_loadsPathsForAllLibraries() {
|
||||
LibraryEntity lib1 = LibraryEntity.builder().name("Lib1").icon("a").watch(false).build();
|
||||
entityManager.persist(lib1);
|
||||
LibraryPathEntity path1 = LibraryPathEntity.builder().library(lib1).path("/lib1").build();
|
||||
entityManager.persist(path1);
|
||||
|
||||
LibraryEntity lib2 = LibraryEntity.builder().name("Lib2").icon("b").watch(false).build();
|
||||
entityManager.persist(lib2);
|
||||
LibraryPathEntity path2 = LibraryPathEntity.builder().library(lib2).path("/lib2").build();
|
||||
entityManager.persist(path2);
|
||||
entityManager.flush();
|
||||
entityManager.clear();
|
||||
|
||||
List<LibraryEntity> libraries = libraryRepository.findAllWithPaths();
|
||||
|
||||
assertThat(libraries).hasSizeGreaterThanOrEqualTo(2);
|
||||
for (LibraryEntity lib : libraries) {
|
||||
entityManager.detach(lib);
|
||||
assertThat(lib.getLibraryPaths()).isNotEmpty();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class MetadataDescriptionAccess {
|
||||
|
||||
private LibraryEntity library;
|
||||
private LibraryPathEntity libraryPath;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
library = LibraryEntity.builder()
|
||||
.name("Description Test Library")
|
||||
.icon("book")
|
||||
.watch(false)
|
||||
.build();
|
||||
entityManager.persist(library);
|
||||
|
||||
libraryPath = LibraryPathEntity.builder()
|
||||
.library(library)
|
||||
.path("/test/books")
|
||||
.build();
|
||||
entityManager.persist(libraryPath);
|
||||
entityManager.flush();
|
||||
}
|
||||
|
||||
/**
|
||||
* Regression: BookMetadataEntity.description must be accessible after detaching.
|
||||
* Previously, description was @Basic(fetch=LAZY) which caused
|
||||
* LazyInitializationException in MetadataChangeDetector and OPDS feeds.
|
||||
*/
|
||||
@Test
|
||||
void descriptionIsAccessibleOnDetachedEntity() {
|
||||
BookEntity book = BookEntity.builder()
|
||||
.library(library)
|
||||
.libraryPath(libraryPath)
|
||||
.addedOn(Instant.now())
|
||||
.deleted(false)
|
||||
.build();
|
||||
BookMetadataEntity metadata = BookMetadataEntity.builder()
|
||||
.book(book)
|
||||
.title("Description Test Book")
|
||||
.description("A long description of this book for testing purposes.")
|
||||
.build();
|
||||
book.setMetadata(metadata);
|
||||
entityManager.persist(book);
|
||||
entityManager.flush();
|
||||
entityManager.clear();
|
||||
|
||||
BookEntity loaded = bookRepository.findAllWithMetadataByIds(
|
||||
Collections.singleton(book.getId())).stream().findFirst().orElseThrow();
|
||||
entityManager.detach(loaded);
|
||||
|
||||
assertThat(loaded.getMetadata().getDescription())
|
||||
.isEqualTo("A long description of this book for testing purposes.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Regression: findAllWithMetadataByIds EntityGraph must load description
|
||||
* so that MetadataChangeDetector.isDifferent() can compare it.
|
||||
*/
|
||||
@Test
|
||||
void findAllWithMetadataByIds_loadsDescriptionEagerly() {
|
||||
BookEntity book = BookEntity.builder()
|
||||
.library(library)
|
||||
.libraryPath(libraryPath)
|
||||
.addedOn(Instant.now())
|
||||
.deleted(false)
|
||||
.build();
|
||||
BookMetadataEntity metadata = BookMetadataEntity.builder()
|
||||
.book(book)
|
||||
.title("Metadata Load Test")
|
||||
.description("Detailed plot summary here.")
|
||||
.build();
|
||||
book.setMetadata(metadata);
|
||||
entityManager.persist(book);
|
||||
entityManager.flush();
|
||||
entityManager.clear();
|
||||
|
||||
List<BookEntity> books = bookRepository.findAllWithMetadataByIds(
|
||||
Collections.singleton(book.getId()));
|
||||
|
||||
assertThat(books).hasSize(1);
|
||||
|
||||
entityManager.detach(books.get(0));
|
||||
|
||||
assertThat(books.get(0).getMetadata().getDescription())
|
||||
.isEqualTo("Detailed plot summary here.");
|
||||
assertThat(books.get(0).getMetadata().getTitle())
|
||||
.isEqualTo("Metadata Load Test");
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify embeddingVector and searchText remain lazy and are NOT loaded
|
||||
* by default EntityGraphs, but ARE accessible within a session.
|
||||
*/
|
||||
@Test
|
||||
void lazyFieldsAccessibleWithinSession() {
|
||||
BookEntity book = BookEntity.builder()
|
||||
.library(library)
|
||||
.libraryPath(libraryPath)
|
||||
.addedOn(Instant.now())
|
||||
.deleted(false)
|
||||
.build();
|
||||
BookMetadataEntity metadata = BookMetadataEntity.builder()
|
||||
.book(book)
|
||||
.title("Lazy Fields Test")
|
||||
.embeddingVector("[0.1, 0.2, 0.3]")
|
||||
.build();
|
||||
book.setMetadata(metadata);
|
||||
entityManager.persist(book);
|
||||
entityManager.flush();
|
||||
entityManager.clear();
|
||||
|
||||
BookEntity loaded = bookRepository.findByIdWithMetadata(book.getId()).orElseThrow();
|
||||
assertThat(loaded.getMetadata().getEmbeddingVector()).isEqualTo("[0.1, 0.2, 0.3]");
|
||||
assertThat(loaded.getMetadata().getSearchText()).isNotNull();
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class CategoryMappingIntegrity {
|
||||
|
||||
private LibraryEntity library;
|
||||
private LibraryPathEntity libraryPath;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
library = LibraryEntity.builder()
|
||||
.name("Category Test Library")
|
||||
.icon("book")
|
||||
.watch(false)
|
||||
.build();
|
||||
entityManager.persist(library);
|
||||
|
||||
libraryPath = LibraryPathEntity.builder()
|
||||
.library(library)
|
||||
.path("/test/books")
|
||||
.build();
|
||||
entityManager.persist(libraryPath);
|
||||
entityManager.flush();
|
||||
}
|
||||
|
||||
/**
|
||||
* Regression: Saving a book with categories must not produce duplicate
|
||||
* entries in book_metadata_category_mapping. The old double-save pattern
|
||||
* (service saves, then controller saves again) caused duplicate key errors.
|
||||
*/
|
||||
@Test
|
||||
void categoryMappings_noDuplicatesAfterSave() {
|
||||
CategoryEntity cat1 = CategoryEntity.builder().name("Fiction").build();
|
||||
CategoryEntity cat2 = CategoryEntity.builder().name("Science").build();
|
||||
entityManager.persist(cat1);
|
||||
entityManager.persist(cat2);
|
||||
|
||||
BookEntity book = BookEntity.builder()
|
||||
.library(library)
|
||||
.libraryPath(libraryPath)
|
||||
.addedOn(Instant.now())
|
||||
.deleted(false)
|
||||
.build();
|
||||
BookMetadataEntity metadata = BookMetadataEntity.builder()
|
||||
.book(book)
|
||||
.title("Category Test Book")
|
||||
.categories(new HashSet<>(Set.of(cat1, cat2)))
|
||||
.build();
|
||||
book.setMetadata(metadata);
|
||||
entityManager.persist(book);
|
||||
entityManager.flush();
|
||||
entityManager.clear();
|
||||
|
||||
// Verify categories persisted correctly
|
||||
BookEntity loaded = bookRepository.findAllWithMetadataByIds(
|
||||
Collections.singleton(book.getId())).stream().findFirst().orElseThrow();
|
||||
|
||||
assertThat(loaded.getMetadata().getCategories()).hasSize(2);
|
||||
assertThat(loaded.getMetadata().getCategories().stream()
|
||||
.map(CategoryEntity::getName)
|
||||
.collect(Collectors.toSet()))
|
||||
.containsExactlyInAnyOrder("Fiction", "Science");
|
||||
|
||||
Long mappingCount = entityManager.createQuery(
|
||||
"SELECT COUNT(1) FROM BookMetadataEntity m JOIN m.categories c WHERE m.book.id = :bookId", Long.class)
|
||||
.setParameter("bookId", book.getId())
|
||||
.getSingleResult();
|
||||
assertThat(mappingCount).isEqualTo(2L);
|
||||
}
|
||||
|
||||
/**
|
||||
* Updating categories on a managed entity should replace correctly
|
||||
* without duplicate key violations.
|
||||
*/
|
||||
@Test
|
||||
void updateCategories_replacesWithoutDuplicates() {
|
||||
CategoryEntity cat1 = CategoryEntity.builder().name("OldCat1").build();
|
||||
CategoryEntity cat2 = CategoryEntity.builder().name("OldCat2").build();
|
||||
CategoryEntity cat3 = CategoryEntity.builder().name("NewCat3").build();
|
||||
entityManager.persist(cat1);
|
||||
entityManager.persist(cat2);
|
||||
entityManager.persist(cat3);
|
||||
|
||||
BookEntity book = BookEntity.builder()
|
||||
.library(library)
|
||||
.libraryPath(libraryPath)
|
||||
.addedOn(Instant.now())
|
||||
.deleted(false)
|
||||
.build();
|
||||
BookMetadataEntity metadata = BookMetadataEntity.builder()
|
||||
.book(book)
|
||||
.title("Update Category Test")
|
||||
.categories(new HashSet<>(Set.of(cat1, cat2)))
|
||||
.build();
|
||||
book.setMetadata(metadata);
|
||||
entityManager.persist(book);
|
||||
entityManager.flush();
|
||||
entityManager.clear();
|
||||
|
||||
BookEntity loaded = bookRepository.findAllWithMetadataByIds(
|
||||
Collections.singleton(book.getId())).stream().findFirst().orElseThrow();
|
||||
|
||||
CategoryEntity managedCat2 = entityManager.find(CategoryEntity.class, cat2.getId());
|
||||
CategoryEntity managedCat3 = entityManager.find(CategoryEntity.class, cat3.getId());
|
||||
|
||||
loaded.getMetadata().getCategories().clear();
|
||||
loaded.getMetadata().getCategories().add(managedCat2);
|
||||
loaded.getMetadata().getCategories().add(managedCat3);
|
||||
|
||||
entityManager.flush();
|
||||
entityManager.clear();
|
||||
|
||||
BookEntity reloaded = bookRepository.findAllWithMetadataByIds(
|
||||
Collections.singleton(book.getId())).stream().findFirst().orElseThrow();
|
||||
|
||||
assertThat(reloaded.getMetadata().getCategories()).hasSize(2);
|
||||
assertThat(reloaded.getMetadata().getCategories().stream()
|
||||
.map(CategoryEntity::getName)
|
||||
.collect(Collectors.toSet()))
|
||||
.containsExactlyInAnyOrder("OldCat2", "NewCat3");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class EmbeddingBatchProcessing {
|
||||
|
||||
private LibraryEntity library;
|
||||
private LibraryPathEntity libraryPath;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
library = LibraryEntity.builder()
|
||||
.name("Embedding Test Library")
|
||||
.icon("book")
|
||||
.watch(false)
|
||||
.build();
|
||||
entityManager.persist(library);
|
||||
|
||||
libraryPath = LibraryPathEntity.builder()
|
||||
.library(library)
|
||||
.path("/test/books")
|
||||
.build();
|
||||
entityManager.persist(libraryPath);
|
||||
entityManager.flush();
|
||||
}
|
||||
|
||||
/**
|
||||
* Regression: findAllFullBooksBatch must load metadata.authors and
|
||||
* metadata.categories eagerly (via Hibernate.initialize) so they are
|
||||
* accessible on detached entities for embedding computation.
|
||||
*/
|
||||
@Test
|
||||
void findAllFullBooksBatch_initializesLazyCollections() {
|
||||
CategoryEntity cat = CategoryEntity.builder().name("TestCat").build();
|
||||
entityManager.persist(cat);
|
||||
|
||||
BookEntity book = BookEntity.builder()
|
||||
.library(library)
|
||||
.libraryPath(libraryPath)
|
||||
.addedOn(Instant.now())
|
||||
.deleted(false)
|
||||
.build();
|
||||
BookMetadataEntity metadata = BookMetadataEntity.builder()
|
||||
.book(book)
|
||||
.title("Batch Test Book")
|
||||
.categories(new HashSet<>(Set.of(cat)))
|
||||
.build();
|
||||
book.setMetadata(metadata);
|
||||
entityManager.persist(book);
|
||||
entityManager.flush();
|
||||
entityManager.clear();
|
||||
|
||||
List<BookEntity> batch = bookRepository.findAllFullBooksBatch(
|
||||
PageRequest.of(0, 100));
|
||||
|
||||
assertThat(batch).isNotEmpty();
|
||||
|
||||
BookEntity loaded = batch.stream()
|
||||
.filter(b -> b.getId().equals(book.getId()))
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
|
||||
assertThat(loaded.getMetadata().getCategories()).hasSize(1);
|
||||
assertThat(loaded.getMetadata().getTitle()).isEqualTo("Batch Test Book");
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify embedding vector can be compared and updated within a session.
|
||||
*/
|
||||
@Test
|
||||
void embeddingVector_comparableAndUpdatableInSession() {
|
||||
BookEntity book = BookEntity.builder()
|
||||
.library(library)
|
||||
.libraryPath(libraryPath)
|
||||
.addedOn(Instant.now())
|
||||
.deleted(false)
|
||||
.build();
|
||||
BookMetadataEntity metadata = BookMetadataEntity.builder()
|
||||
.book(book)
|
||||
.title("Embedding Update Test")
|
||||
.embeddingVector("[0.1, 0.2]")
|
||||
.build();
|
||||
book.setMetadata(metadata);
|
||||
entityManager.persist(book);
|
||||
entityManager.flush();
|
||||
entityManager.clear();
|
||||
|
||||
BookEntity loaded = bookRepository.findAllWithMetadataByIds(
|
||||
Collections.singleton(book.getId())).stream().findFirst().orElseThrow();
|
||||
|
||||
String oldEmbedding = loaded.getMetadata().getEmbeddingVector();
|
||||
assertThat(oldEmbedding).isEqualTo("[0.1, 0.2]");
|
||||
|
||||
loaded.getMetadata().setEmbeddingVector("[0.3, 0.4]");
|
||||
loaded.getMetadata().setEmbeddingUpdatedAt(Instant.now());
|
||||
entityManager.flush();
|
||||
entityManager.clear();
|
||||
|
||||
BookEntity reloaded = bookRepository.findByIdWithMetadata(book.getId()).orElseThrow();
|
||||
assertThat(reloaded.getMetadata().getEmbeddingVector()).isEqualTo("[0.3, 0.4]");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,8 @@ import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.Mockito.*;
|
||||
@@ -68,7 +70,15 @@ class BookCreatorServiceTest {
|
||||
void addAuthorsToBook_givenNullOrEmptySet_doesNothing(Set<String> authors) {
|
||||
bookCreatorService.addAuthorsToBook(authors, bookEntity);
|
||||
|
||||
assertThat(bookEntity.getMetadata().getAuthors()).isNull();
|
||||
assertTrue(bookEntity.getMetadata().getAuthors().isEmpty());
|
||||
verifyNoInteractions(authorRepository);
|
||||
}
|
||||
|
||||
@Test
|
||||
void addAuthorsToBook_emptyAuthors_doesNothing() {
|
||||
bookCreatorService.addAuthorsToBook(Set.of(), bookEntity);
|
||||
|
||||
assertTrue(bookEntity.getMetadata().getAuthors().isEmpty());
|
||||
verifyNoInteractions(authorRepository);
|
||||
}
|
||||
|
||||
@@ -84,12 +94,32 @@ class BookCreatorServiceTest {
|
||||
.containsExactly("Test Author");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@NullAndEmptySource
|
||||
void addCategoriesToBook_givenNullOrEmptySet_doesNothing(Set<String> categories) {
|
||||
bookCreatorService.addCategoriesToBook(categories, bookEntity);
|
||||
@Test
|
||||
void addAuthorsToBook_nullExistingAuthorsOnEntity_initializesSet() {
|
||||
assertTrue(bookEntity.getMetadata().getAuthors().isEmpty());
|
||||
|
||||
assertThat(bookEntity.getMetadata().getCategories()).isNull();
|
||||
AuthorEntity author = AuthorEntity.builder().name("Author").build();
|
||||
when(authorRepository.findByName("Author")).thenReturn(Optional.of(author));
|
||||
|
||||
bookCreatorService.addAuthorsToBook(Set.of("Author"), bookEntity);
|
||||
|
||||
assertNotNull(bookEntity.getMetadata().getAuthors());
|
||||
assertTrue(bookEntity.getMetadata().getAuthors().contains(author));
|
||||
}
|
||||
|
||||
@Test
|
||||
void addCategoriesToBook_nullCategories_doesNothing() {
|
||||
bookCreatorService.addCategoriesToBook(null, bookEntity);
|
||||
|
||||
assertTrue(bookEntity.getMetadata().getCategories().isEmpty());
|
||||
verifyNoInteractions(categoryRepository);
|
||||
}
|
||||
|
||||
@Test
|
||||
void addCategoriesToBook_emptyCategories_doesNothing() {
|
||||
bookCreatorService.addCategoriesToBook(Set.of(), bookEntity);
|
||||
|
||||
assertTrue(bookEntity.getMetadata().getCategories().isEmpty());
|
||||
verifyNoInteractions(categoryRepository);
|
||||
}
|
||||
|
||||
@@ -110,7 +140,15 @@ class BookCreatorServiceTest {
|
||||
void addMoodsToBook_givenNullOrEmptySet_doesNothing(Set<String> moods) {
|
||||
bookCreatorService.addMoodsToBook(moods, bookEntity);
|
||||
|
||||
assertThat(bookEntity.getMetadata().getMoods()).isNull();
|
||||
assertTrue(bookEntity.getMetadata().getMoods().isEmpty());
|
||||
verifyNoInteractions(moodRepository);
|
||||
}
|
||||
|
||||
@Test
|
||||
void addMoodsToBook_emptyMoods_doesNothing() {
|
||||
bookCreatorService.addMoodsToBook(Set.of(), bookEntity);
|
||||
|
||||
assertTrue(bookEntity.getMetadata().getMoods().isEmpty());
|
||||
verifyNoInteractions(moodRepository);
|
||||
}
|
||||
|
||||
@@ -131,7 +169,23 @@ class BookCreatorServiceTest {
|
||||
void addTagsToBook_givenNullOrEmptySet_doesNothing(Set<String> tags) {
|
||||
bookCreatorService.addTagsToBook(tags, bookEntity);
|
||||
|
||||
assertThat(bookEntity.getMetadata().getTags()).isNull();
|
||||
assertTrue(bookEntity.getMetadata().getTags().isEmpty());
|
||||
verifyNoInteractions(tagRepository);
|
||||
}
|
||||
|
||||
@Test
|
||||
void addTagsToBook_nullTags_doesNothing() {
|
||||
bookCreatorService.addTagsToBook(null, bookEntity);
|
||||
|
||||
assertTrue(bookEntity.getMetadata().getTags().isEmpty());
|
||||
verifyNoInteractions(tagRepository);
|
||||
}
|
||||
|
||||
@Test
|
||||
void addTagsToBook_emptyTags_doesNothing() {
|
||||
bookCreatorService.addTagsToBook(Set.of(), bookEntity);
|
||||
|
||||
assertTrue(bookEntity.getMetadata().getTags().isEmpty());
|
||||
verifyNoInteractions(tagRepository);
|
||||
}
|
||||
|
||||
@@ -172,7 +226,7 @@ class BookCreatorServiceTest {
|
||||
bookCreatorService.addAuthorsToBook(Set.of("Brand New"), bookEntity);
|
||||
|
||||
verify(authorRepository).save(argThat(author -> "Brand New".equals(author.getName())));
|
||||
|
||||
|
||||
assertThat(bookEntity.getMetadata().getAuthors())
|
||||
.isNotNull()
|
||||
.extracting(AuthorEntity::getName)
|
||||
|
||||
+4
@@ -99,6 +99,7 @@ class BookFileAttachmentServiceTest {
|
||||
Files.createDirectories(dir);
|
||||
Files.createFile(dir.resolve(fileName));
|
||||
|
||||
book.getBookFiles().add(file);
|
||||
return file;
|
||||
}
|
||||
|
||||
@@ -113,6 +114,7 @@ class BookFileAttachmentServiceTest {
|
||||
.folderBased(false)
|
||||
.bookType(BookFileType.EPUB)
|
||||
.build();
|
||||
book.getBookFiles().add(file);
|
||||
return file;
|
||||
}
|
||||
|
||||
@@ -791,6 +793,7 @@ class BookFileAttachmentServiceTest {
|
||||
Path sourceDir = tempDir.resolve("other_root/source_dir");
|
||||
Files.createDirectories(sourceDir);
|
||||
Files.createFile(sourceDir.resolve("source.pdf"));
|
||||
source.getBookFiles().add(sourceFile);
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
|
||||
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
|
||||
@@ -822,6 +825,7 @@ class BookFileAttachmentServiceTest {
|
||||
.build();
|
||||
Files.createDirectories(tempDir.resolve("source_dir"));
|
||||
Files.createFile(tempDir.resolve("source_dir/noextension"));
|
||||
source.getBookFiles().add(sourceFile);
|
||||
|
||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(target));
|
||||
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.of(source));
|
||||
|
||||
+5
-7
@@ -86,6 +86,7 @@ class BookFileDetachmentServiceTest {
|
||||
.isBookFormat(isBookFormat)
|
||||
.bookType(type)
|
||||
.build();
|
||||
book.getBookFiles().add(file);
|
||||
return file;
|
||||
}
|
||||
|
||||
@@ -123,7 +124,6 @@ class BookFileDetachmentServiceTest {
|
||||
assertThat(book.getBookFiles().getFirst().getId()).isEqualTo(10L);
|
||||
verify(auditService).log(eq(org.booklore.model.enums.AuditAction.BOOK_FILE_DETACHED), anyString(), eq(1L), anyString());
|
||||
verify(bookRepository).saveAndFlush(argThat(newBook -> {
|
||||
assertThat(newBook.getBookFiles()).hasSize(1);
|
||||
assertThat(newBook.getMetadata().getTitle()).isEqualTo("Test Book 1");
|
||||
return true;
|
||||
}));
|
||||
@@ -173,11 +173,9 @@ class BookFileDetachmentServiceTest {
|
||||
service.detachBookFile(1L, 11L, false);
|
||||
|
||||
assertThat(book.getBookFiles()).hasSize(1);
|
||||
verify(bookRepository).saveAndFlush(argThat(newBook -> {
|
||||
assertThat(newBook.getBookFiles()).hasSize(1);
|
||||
assertThat(newBook.getBookFiles().getFirst().getFileName()).isEqualTo("notes.txt");
|
||||
return true;
|
||||
}));
|
||||
assertThat(suppFile.getBook()).isNotSameAs(book);
|
||||
assertThat(suppFile.getFileName()).isEqualTo("notes.txt");
|
||||
verify(bookRepository).saveAndFlush(any(BookEntity.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -281,8 +279,8 @@ class BookFileDetachmentServiceTest {
|
||||
|
||||
verify(bookRepository).saveAndFlush(argThat(newBook -> {
|
||||
assertThat(newBook.getLibraryPath().getId()).isEqualTo(2L);
|
||||
assertThat(newBook.getBookFiles().getFirst().getFileSubPath()).isEmpty();
|
||||
return true;
|
||||
}));
|
||||
assertThat(altFile.getFileSubPath()).isEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,6 +41,8 @@ import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageImpl;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.TransactionStatus;
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
|
||||
import java.io.IOException;
|
||||
@@ -87,6 +89,8 @@ class BookDropServiceTest {
|
||||
private FileMovingHelper fileMovingHelper;
|
||||
@Mock
|
||||
private KoboAutoShelfService koboAutoShelfService;
|
||||
@Mock
|
||||
private PlatformTransactionManager transactionManager;
|
||||
|
||||
@InjectMocks
|
||||
private BookDropService bookDropService;
|
||||
@@ -122,6 +126,9 @@ class BookDropServiceTest {
|
||||
bookdropFile.setFileName("test-book.pdf");
|
||||
|
||||
Files.createFile(tempDir.resolve("test-book.pdf"));
|
||||
|
||||
TransactionStatus txStatus = mock(TransactionStatus.class);
|
||||
lenient().when(transactionManager.getTransaction(any())).thenReturn(txStatus);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
|
||||
+2
-2
@@ -72,11 +72,11 @@ class KoboLibrarySnapshotServiceTest {
|
||||
otherUser = BookLoreUserEntity.builder().id(2L).isDefaultPassword(false).build();
|
||||
|
||||
LibraryEntity ownersLibrary = LibraryEntity.builder()
|
||||
.users(List.of(owner))
|
||||
.users(Set.of(owner))
|
||||
.build();
|
||||
|
||||
LibraryEntity othersLibrary = LibraryEntity.builder()
|
||||
.users(List.of(otherUser))
|
||||
.users(Set.of(otherUser))
|
||||
.build();
|
||||
|
||||
ownersBook = BookEntity.builder()
|
||||
|
||||
@@ -102,12 +102,11 @@ class KomgaServiceTest {
|
||||
@Test
|
||||
void shouldReturnAllBooksWhenUnpagedIsTrue() {
|
||||
// Given
|
||||
when(bookRepository.findAllWithMetadataByLibraryId(anyLong())).thenReturn(seriesBooks);
|
||||
|
||||
// Mock mapper.getBookSeriesName to return "test-series" for all books
|
||||
for (BookEntity book : seriesBooks) {
|
||||
when(komgaMapper.getBookSeriesName(book)).thenReturn("test-series");
|
||||
}
|
||||
when(komgaMapper.getUnknownSeriesName()).thenReturn("Unknown Series");
|
||||
when(bookRepository.findDistinctSeriesNamesGroupedByLibraryId(1L, "Unknown Series"))
|
||||
.thenReturn(List.of("Test Series"));
|
||||
when(bookRepository.findBooksBySeriesNameGroupedByLibraryId("Test Series", 1L, "Unknown Series"))
|
||||
.thenReturn(seriesBooks);
|
||||
|
||||
// Mock the mapper to return DTOs
|
||||
for (BookEntity book : seriesBooks) {
|
||||
@@ -133,12 +132,11 @@ class KomgaServiceTest {
|
||||
@Test
|
||||
void shouldReturnPagedBooksWhenUnpagedIsFalse() {
|
||||
// Given
|
||||
when(bookRepository.findAllWithMetadataByLibraryId(anyLong())).thenReturn(seriesBooks);
|
||||
|
||||
// Mock mapper.getBookSeriesName to return "test-series" for all books
|
||||
for (BookEntity book : seriesBooks) {
|
||||
when(komgaMapper.getBookSeriesName(book)).thenReturn("test-series");
|
||||
}
|
||||
when(komgaMapper.getUnknownSeriesName()).thenReturn("Unknown Series");
|
||||
when(bookRepository.findDistinctSeriesNamesGroupedByLibraryId(1L, "Unknown Series"))
|
||||
.thenReturn(List.of("Test Series"));
|
||||
when(bookRepository.findBooksBySeriesNameGroupedByLibraryId("Test Series", 1L, "Unknown Series"))
|
||||
.thenReturn(seriesBooks);
|
||||
|
||||
// Mock the mapper to return DTOs (only for the books that will be used)
|
||||
for (int i = 0; i < 20; i++) {
|
||||
|
||||
+6
-1
@@ -6,6 +6,7 @@ import org.booklore.model.entity.BookEntity;
|
||||
import org.booklore.model.entity.LibraryEntity;
|
||||
import org.booklore.model.entity.LibraryPathEntity;
|
||||
import org.booklore.repository.BookAdditionalFileRepository;
|
||||
import org.booklore.repository.BookRepository;
|
||||
import org.booklore.repository.LibraryRepository;
|
||||
import org.booklore.service.NotificationService;
|
||||
import org.booklore.task.options.RescanLibraryContext;
|
||||
@@ -32,6 +33,8 @@ class LibraryProcessingServiceRegressionTest {
|
||||
@Mock
|
||||
private LibraryRepository libraryRepository;
|
||||
@Mock
|
||||
private BookRepository bookRepository;
|
||||
@Mock
|
||||
private NotificationService notificationService;
|
||||
@Mock
|
||||
private BookAdditionalFileRepository bookAdditionalFileRepository;
|
||||
@@ -54,6 +57,7 @@ class LibraryProcessingServiceRegressionTest {
|
||||
void setUp() {
|
||||
libraryProcessingService = new LibraryProcessingService(
|
||||
libraryRepository,
|
||||
bookRepository,
|
||||
notificationService,
|
||||
bookAdditionalFileRepository,
|
||||
fileAsBookProcessor,
|
||||
@@ -88,7 +92,8 @@ class LibraryProcessingServiceRegressionTest {
|
||||
|
||||
libraryEntity.setBookEntities(List.of(filelessBook));
|
||||
|
||||
when(libraryRepository.findByIdWithBooks(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||
when(libraryRepository.findByIdWithPaths(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||
when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(List.of(filelessBook));
|
||||
when(libraryFileHelper.getAllLibraryFiles(libraryEntity)).thenReturn(List.of(
|
||||
LibraryFile.builder()
|
||||
.libraryPathEntity(pathEntity)
|
||||
|
||||
+26
-9
@@ -8,6 +8,7 @@ import org.booklore.model.entity.BookFileEntity;
|
||||
import org.booklore.model.entity.LibraryEntity;
|
||||
import org.booklore.model.entity.LibraryPathEntity;
|
||||
import org.booklore.repository.BookAdditionalFileRepository;
|
||||
import org.booklore.repository.BookRepository;
|
||||
import org.booklore.repository.LibraryRepository;
|
||||
import org.booklore.service.NotificationService;
|
||||
import org.booklore.task.options.RescanLibraryContext;
|
||||
@@ -35,6 +36,8 @@ class LibraryProcessingServiceTest {
|
||||
@Mock
|
||||
private LibraryRepository libraryRepository;
|
||||
@Mock
|
||||
private BookRepository bookRepository;
|
||||
@Mock
|
||||
private NotificationService notificationService;
|
||||
@Mock
|
||||
private BookAdditionalFileRepository bookAdditionalFileRepository;
|
||||
@@ -57,6 +60,7 @@ class LibraryProcessingServiceTest {
|
||||
void setUp() {
|
||||
libraryProcessingService = new LibraryProcessingService(
|
||||
libraryRepository,
|
||||
bookRepository,
|
||||
notificationService,
|
||||
bookAdditionalFileRepository,
|
||||
fileAsBookProcessor,
|
||||
@@ -89,6 +93,7 @@ class LibraryProcessingServiceTest {
|
||||
libraryEntity.setBookEntities(List.of(existingBook));
|
||||
|
||||
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||
when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(List.of(existingBook));
|
||||
|
||||
LibraryFile existingFile = LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
@@ -150,6 +155,7 @@ class LibraryProcessingServiceTest {
|
||||
libraryEntity.setBookEntities(List.of(existingBook));
|
||||
|
||||
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||
when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(List.of(existingBook));
|
||||
|
||||
LibraryFile existingFile = LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
@@ -183,6 +189,7 @@ class LibraryProcessingServiceTest {
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||
when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(Collections.emptyList());
|
||||
|
||||
LibraryFile newFile1 = LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
@@ -230,6 +237,7 @@ class LibraryProcessingServiceTest {
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||
when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(Collections.emptyList());
|
||||
|
||||
LibraryFile newFileInSub = LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
@@ -274,6 +282,7 @@ class LibraryProcessingServiceTest {
|
||||
pathEntity.setPath("/library");
|
||||
|
||||
when(libraryRepository.findById(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||
when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(Collections.emptyList());
|
||||
|
||||
LibraryFile additionalFileAsLibraryFile = LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
@@ -346,7 +355,8 @@ class LibraryProcessingServiceTest {
|
||||
book.setBookFiles(List.of(epub, pdf, image));
|
||||
libraryEntity.setBookEntities(List.of(book));
|
||||
|
||||
when(libraryRepository.findByIdWithBooks(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||
when(libraryRepository.findByIdWithPaths(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||
when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(List.of(book));
|
||||
|
||||
// Only epub exists on disk, pdf was removed
|
||||
LibraryFile epubOnDisk = LibraryFile.builder()
|
||||
@@ -385,7 +395,7 @@ class LibraryProcessingServiceTest {
|
||||
libraryEntity.setLibraryPaths(List.of(pathEntity));
|
||||
libraryEntity.setBookEntities(Collections.emptyList());
|
||||
|
||||
when(libraryRepository.findByIdWithBooks(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||
when(libraryRepository.findByIdWithPaths(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||
|
||||
RescanLibraryContext context = RescanLibraryContext.builder().libraryId(libraryId).build();
|
||||
|
||||
@@ -422,7 +432,8 @@ class LibraryProcessingServiceTest {
|
||||
existingBook.getPrimaryBookFile().setFileName("book1.epub");
|
||||
libraryEntity.setBookEntities(List.of(existingBook));
|
||||
|
||||
when(libraryRepository.findByIdWithBooks(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||
when(libraryRepository.findByIdWithPaths(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||
when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(List.of(existingBook));
|
||||
when(libraryFileHelper.getAllLibraryFiles(libraryEntity)).thenReturn(Collections.emptyList());
|
||||
|
||||
RescanLibraryContext context = RescanLibraryContext.builder().libraryId(libraryId).build();
|
||||
@@ -467,11 +478,12 @@ class LibraryProcessingServiceTest {
|
||||
.fileName("book1.epub")
|
||||
.build();
|
||||
|
||||
when(libraryRepository.findByIdWithBooks(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||
when(libraryRepository.findByIdWithPaths(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||
when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(List.of(existingBook));
|
||||
when(libraryFileHelper.getAllLibraryFiles(libraryEntity)).thenReturn(List.of(fileOnDisk));
|
||||
when(libraryFileHelper.filterByAllowedFormats(anyList(), any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList());
|
||||
when(bookGroupingService.groupForRescan(anyList(), eq(libraryEntity)))
|
||||
when(bookGroupingService.groupForRescan(anyList(), any(LibraryEntity.class)))
|
||||
.thenReturn(new BookGroupingService.GroupingResult(Collections.emptyMap(), Collections.emptyMap()));
|
||||
|
||||
RescanLibraryContext context = RescanLibraryContext.builder().libraryId(libraryId).build();
|
||||
@@ -497,11 +509,12 @@ class LibraryProcessingServiceTest {
|
||||
libraryEntity.setLibraryPaths(List.of(pathEntity));
|
||||
libraryEntity.setBookEntities(Collections.emptyList());
|
||||
|
||||
when(libraryRepository.findByIdWithBooks(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||
when(libraryRepository.findByIdWithPaths(libraryId)).thenReturn(Optional.of(libraryEntity));
|
||||
when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(Collections.emptyList());
|
||||
when(libraryFileHelper.getAllLibraryFiles(libraryEntity)).thenReturn(Collections.emptyList());
|
||||
when(libraryFileHelper.filterByAllowedFormats(anyList(), any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList());
|
||||
when(bookGroupingService.groupForRescan(anyList(), eq(libraryEntity)))
|
||||
when(bookGroupingService.groupForRescan(anyList(), any(LibraryEntity.class)))
|
||||
.thenReturn(new BookGroupingService.GroupingResult(Collections.emptyMap(), Collections.emptyMap()));
|
||||
|
||||
RescanLibraryContext context = RescanLibraryContext.builder().libraryId(libraryId).build();
|
||||
@@ -551,9 +564,12 @@ class LibraryProcessingServiceTest {
|
||||
.fileName("book (with parens).epub")
|
||||
.build();
|
||||
|
||||
when(libraryRepository.findByIdWithBooks(libraryId))
|
||||
when(libraryRepository.findByIdWithPaths(libraryId))
|
||||
.thenReturn(Optional.of(libraryEntity))
|
||||
.thenReturn(Optional.of(freshLibraryEntity)); // Second call returns fresh entity
|
||||
when(bookRepository.findAllByLibraryIdForRescan(libraryId))
|
||||
.thenReturn(new ArrayList<>(List.of(existingBook)))
|
||||
.thenReturn(new ArrayList<>(List.of(existingBook)));
|
||||
when(libraryFileHelper.getAllLibraryFiles(any(LibraryEntity.class))).thenReturn(List.of(fileOnDisk));
|
||||
when(libraryFileHelper.filterByAllowedFormats(anyList(), any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList());
|
||||
@@ -564,7 +580,8 @@ class LibraryProcessingServiceTest {
|
||||
|
||||
libraryProcessingService.rescanLibrary(context);
|
||||
|
||||
verify(libraryRepository, times(2)).findByIdWithBooks(libraryId);
|
||||
verify(libraryRepository, times(2)).findByIdWithPaths(libraryId);
|
||||
verify(bookRepository, times(2)).findAllByLibraryIdForRescan(libraryId);
|
||||
|
||||
verify(bookGroupingService).groupForRescan(eq(Collections.emptyList()), any(LibraryEntity.class));
|
||||
}
|
||||
|
||||
+1
-1
@@ -68,7 +68,7 @@ class LibraryFileEventProcessorTest {
|
||||
.organizationMode(LibraryOrganizationMode.AUTO_DETECT)
|
||||
.build();
|
||||
|
||||
when(libraryRepository.findById(1L)).thenReturn(Optional.of(library));
|
||||
when(libraryRepository.findByIdWithPaths(1L)).thenReturn(Optional.of(library));
|
||||
when(bookFilePersistenceService.findMatchingLibraryPath(eq(library), any(Path.class)))
|
||||
.thenReturn(tempDir.toString());
|
||||
when(bookFilePersistenceService.getLibraryPathEntityForFile(eq(library), eq(tempDir.toString())))
|
||||
|
||||
+37
-25
@@ -2,6 +2,7 @@ package org.booklore.task.tasks;
|
||||
|
||||
import org.booklore.exception.APIException;
|
||||
import org.booklore.model.dto.BookLoreUser;
|
||||
import org.booklore.model.dto.BookRecommendationLite;
|
||||
import org.booklore.model.dto.request.TaskCreateRequest;
|
||||
import org.booklore.model.dto.response.TaskCreateResponse;
|
||||
import org.booklore.model.entity.BookEntity;
|
||||
@@ -15,13 +16,13 @@ import org.booklore.task.TaskStatus;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Captor;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.*;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
@@ -40,6 +41,9 @@ class BookRecommendationUpdaterTaskTest {
|
||||
@InjectMocks
|
||||
private BookRecommendationUpdaterTask task;
|
||||
|
||||
@Captor
|
||||
private ArgumentCaptor<Map<Long, Set<BookRecommendationLite>>> recommendationsCaptor;
|
||||
|
||||
private BookLoreUser user;
|
||||
private TaskCreateRequest request;
|
||||
|
||||
@@ -60,13 +64,15 @@ class BookRecommendationUpdaterTaskTest {
|
||||
|
||||
@Test
|
||||
void execute_shouldHandleEmptyBookList() {
|
||||
when(bookQueryService.getAllFullBookEntities()).thenReturn(Collections.emptyList());
|
||||
when(bookQueryService.countAllNonDeleted()).thenReturn(0L);
|
||||
when(bookQueryService.getAllFullBookEntitiesBatch(any())).thenReturn(Collections.emptyList());
|
||||
|
||||
TaskCreateResponse response = task.execute(request);
|
||||
|
||||
assertEquals(TaskType.UPDATE_BOOK_RECOMMENDATIONS, response.getTaskType());
|
||||
verify(bookQueryService).getAllFullBookEntities();
|
||||
verify(bookQueryService).saveAll(anyList()); // Should be called with empty list
|
||||
verify(bookQueryService).countAllNonDeleted();
|
||||
verify(bookQueryService).getAllFullBookEntitiesBatch(any());
|
||||
verify(bookQueryService).saveRecommendationsInBatches(eq(Collections.emptyMap()), anyInt());
|
||||
verify(notificationService, atLeastOnce()).sendMessage(eq(Topic.TASK_PROGRESS), any());
|
||||
}
|
||||
|
||||
@@ -76,32 +82,41 @@ class BookRecommendationUpdaterTaskTest {
|
||||
BookEntity book2 = BookEntity.builder().id(2L).metadata(BookMetadataEntity.builder().title("B2").build()).build();
|
||||
List<BookEntity> books = List.of(book1, book2);
|
||||
|
||||
when(bookQueryService.getAllFullBookEntities()).thenReturn(books);
|
||||
when(bookQueryService.countAllNonDeleted()).thenReturn(2L);
|
||||
when(bookQueryService.getAllFullBookEntitiesBatch(any())).thenReturn(books).thenReturn(Collections.emptyList());
|
||||
when(vectorService.generateEmbedding(any())).thenReturn(new double[]{0.1, 0.2});
|
||||
when(vectorService.serializeVector(any())).thenReturn("[0.1, 0.2]");
|
||||
// Lenient stubs for similarity calculations
|
||||
lenient().when(vectorService.cosineSimilarity(any(), any())).thenReturn(0.9);
|
||||
lenient().when(vectorService.findTopKSimilar(any(), anyList(), anyInt())).thenReturn(new ArrayList<>());
|
||||
when(vectorService.cosineSimilarity(any(), any())).thenReturn(0.9);
|
||||
when(vectorService.findTopKSimilar(any(), anyList(), anyInt())).thenAnswer(invocation -> {
|
||||
List<BookVectorService.ScoredBook> candidates = invocation.getArgument(1);
|
||||
return candidates.isEmpty() ? new ArrayList<>() : List.of(candidates.getFirst());
|
||||
});
|
||||
|
||||
TaskCreateResponse response = task.execute(request);
|
||||
|
||||
assertEquals("task-123", response.getTaskId());
|
||||
assertEquals(TaskStatus.COMPLETED, response.getStatus());
|
||||
|
||||
org.mockito.ArgumentCaptor<List<BookEntity>> captor = org.mockito.ArgumentCaptor.forClass(List.class);
|
||||
verify(bookQueryService).saveAll(captor.capture());
|
||||
|
||||
List<BookEntity> savedBooks = captor.getValue();
|
||||
assertEquals(2, savedBooks.size());
|
||||
// Verify embeddings were set
|
||||
assertNotNull(savedBooks.get(0).getMetadata().getEmbeddingVector());
|
||||
verify(bookQueryService).compareAndSaveEmbeddings(any());
|
||||
verify(vectorService, times(2)).generateEmbedding(any());
|
||||
verify(bookQueryService).saveRecommendationsInBatches(recommendationsCaptor.capture(), anyInt());
|
||||
|
||||
Map<Long, Set<BookRecommendationLite>> recommendations = recommendationsCaptor.getValue();
|
||||
assertNotNull(recommendations);
|
||||
assertEquals(2, recommendations.size(), "Should have recommendations for both books");
|
||||
assertTrue(recommendations.containsKey(1L), "Should have recommendations for book 1");
|
||||
assertTrue(recommendations.containsKey(2L), "Should have recommendations for book 2");
|
||||
// Each book should recommend the other
|
||||
recommendations.values().forEach(recs ->
|
||||
assertFalse(recs.isEmpty(), "Each book should have at least one recommendation"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void execute_shouldFail_whenEmbeddingGenerationThrows() {
|
||||
BookEntity book1 = BookEntity.builder().id(1L).build();
|
||||
when(bookQueryService.getAllFullBookEntities()).thenReturn(List.of(book1));
|
||||
BookEntity book1 = BookEntity.builder().id(1L).metadata(BookMetadataEntity.builder().title("B1").build()).build();
|
||||
|
||||
when(bookQueryService.countAllNonDeleted()).thenReturn(1L);
|
||||
when(bookQueryService.getAllFullBookEntitiesBatch(any())).thenReturn(List.of(book1));
|
||||
when(vectorService.generateEmbedding(any())).thenThrow(new RuntimeException("Embedding failed"));
|
||||
|
||||
assertThrows(RuntimeException.class, () -> task.execute(request));
|
||||
@@ -113,18 +128,15 @@ class BookRecommendationUpdaterTaskTest {
|
||||
BookEntity book2 = BookEntity.builder().id(2L).metadata(BookMetadataEntity.builder().title("B2").build()).build();
|
||||
List<BookEntity> books = List.of(book1, book2);
|
||||
|
||||
when(bookQueryService.getAllFullBookEntities()).thenReturn(books);
|
||||
when(bookQueryService.countAllNonDeleted()).thenReturn(2L);
|
||||
when(bookQueryService.getAllFullBookEntitiesBatch(any())).thenReturn(books).thenReturn(Collections.emptyList());
|
||||
when(vectorService.generateEmbedding(any())).thenReturn(new double[]{0.1});
|
||||
when(vectorService.serializeVector(any())).thenReturn("[0.1]");
|
||||
|
||||
// Mock similarity to throw for first book, pass for second (actually it iterates as target)
|
||||
// target=book1, candidate=book2.
|
||||
when(vectorService.cosineSimilarity(any(), any())).thenThrow(new RuntimeException("Math error"));
|
||||
|
||||
TaskCreateResponse response = task.execute(request);
|
||||
|
||||
assertEquals(TaskStatus.COMPLETED, response.getStatus());
|
||||
// Should still try to save updates (even if empty list added)
|
||||
verify(bookQueryService).saveAll(anyList());
|
||||
verify(bookQueryService).saveRecommendationsInBatches(any(Map.class), anyInt());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,10 @@ spring:
|
||||
properties:
|
||||
hibernate:
|
||||
format_sql: true
|
||||
query:
|
||||
fail_on_pagination_over_collection_fetch: true
|
||||
connection:
|
||||
provider_disables_autocommit: false
|
||||
flyway:
|
||||
enabled: false
|
||||
app:
|
||||
|
||||
@@ -16,6 +16,7 @@ services:
|
||||
- DATABASE_PASSWORD=grimmory
|
||||
- REMOTE_DEBUG_ENABLED=true
|
||||
- ALLOWED_ORIGINS=http://localhost:4200
|
||||
- JAVA_TOOL_OPTIONS=-XX:+UseShenandoahGC -XX:ShenandoahGCHeuristics=compact -XX:+UseCompactObjectHeaders -XX:MaxRAMPercentage=60.0 -XX:InitialRAMPercentage=8.0 -XX:+ExitOnOutOfMemoryError -XX:MaxMetaspaceSize=192m -XX:ReservedCodeCacheSize=64m -Xss512k -XX:CICompilerCount=2 -XX:+UnlockExperimentalVMOptions -XX:ShenandoahUncommitDelay=5000 -XX:ShenandoahGuaranteedGCInterval=30000
|
||||
stdin_open: true
|
||||
tty: true
|
||||
restart: unless-stopped
|
||||
|
||||
@@ -101,7 +101,8 @@ export class BookService {
|
||||
private getBooksQueryOptions() {
|
||||
return queryOptions({
|
||||
queryKey: BOOKS_QUERY_KEY,
|
||||
queryFn: () => lastValueFrom(this.http.get<Book[]>(this.url, {params: {stripForListView: false}}))
|
||||
queryFn: () => lastValueFrom(this.http.get<Book[]>(this.url, {params: {stripForListView: false}})),
|
||||
staleTime: 30_000,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user