You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring构造参数依赖注入失败及DynamoDB查询方法错误求助

问题排查与解决方案

错误根源

报错核心原因是Spring Data DynamoDB无法解析findByBookAndStatus查询方法:

No property 'book' found for type 'Lend' Did you mean 'bookId'

从代码逻辑(LibraryService中lend.setBookId(bookForId.get().getId()))可以看出,Lend实体实际存储的是书籍ID(bookId字段),而非Book对象,但你在LendRepository中定义的查询方法试图通过不存在的book属性过滤,导致框架无法生成正确的查询语句。

修复方案

1. 修改LendRepository的查询方法

将方法名改为对应Lend实体的bookId属性,参数类型调整为String(与bookId类型一致):

import org.socialsignin.spring.data.dynamodb.repository.EnableScan;
import com.restapi.model.Lend;
import com.restapi.model.LendStatus;

import org.springframework.data.repository.CrudRepository;

import java.util.Optional;

@EnableScan
public interface LendRepository extends CrudRepository<Lend, String> {
    // 改为通过bookId查询,参数为String类型的书籍ID
    Optional<Lend> findByBookIdAndStatus(String bookId, LendStatus status);
}

2. 修改LibraryService中的方法调用

循环中已经持有bookId变量,直接传入即可,无需传递Book对象:

public List<String> lendABook (BookLendRequest request) throws Exception {
        Optional<Member> memberForId = memberRepository.findById(request.getMemberId());
        if (!memberForId.isPresent()) {
            throw new Exception("Exception message");
        }
        Member member = memberForId.get();
        if (member.getStatus() != MemberStatus.ACTIVE) {
            throw new RuntimeException("User is not active to proceed a lending.");
        }
        List<String> booksApprovedToBurrow = new ArrayList<>();
        request.getBookIds().forEach(bookId -> {
            Optional<Book> bookForId = bookRepository.findById(bookId);
            if (!bookForId.isPresent()) {
                try {
                    throw new Exception("Exception message");
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
            // 改为传入bookId,而非Book对象
            Optional<Lend> burrowedBook = lendRepository.findByBookIdAndStatus(bookId, LendStatus.BURROWED);
            if (!burrowedBook.isPresent()) {
                booksApprovedToBurrow.add(bookForId.get().getName());
                Lend lend = new Lend();
                lend.setMemberId(memberForId.get().getId());
                lend.setBookId(bookForId.get().getId());
                lend.setStatus(LendStatus.BURROWED);
                lend.setStartOn(Instant.now().toString());
                lend.setDueOn(Instant.now().plus(30, ChronoUnit.DAYS).toString());
                lendRepository.save(lend);
            }
        });
        // 补充原代码缺失的返回语句
        return booksApprovedToBurrow;
}

关键说明

Spring Data的查询方法命名遵循属性匹配规则:方法名中的ByXXX部分必须严格对应实体类中的属性名。由于Lend实体仅包含bookId(String类型),而非book(Book类型),因此必须调整方法名和参数类型来匹配实际存储的字段。

内容的提问来源于stack exchange,提问作者ptratyou

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 21:15:30