spring data jpa - 参数值[Book]与预期类型[ContentType]不匹配

CVV*_*CVV 1 java spring jpa

我有两个简单的桌子contentcontentType

@Entity
@Table(name = "content")
public class Content implements Serializable {

public Content() {}

public Content(String title, String description) {
    this.title = title;
    this.description = description;
}

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id;

@ManyToOne
private ContentCategory contentCategory;

@ManyToOne
private ContentType contentType;

 // getter/setters
}

@Entity
@Table(name = "contentType")
public class ContentType implements Serializable {

public ContentType() {}

public ContentType(String contentType) {
    this.contentType = contentType;
}

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id;

@NotNull
private String contentType;

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "contentType")
private Set<Content> content;
`// getter/setters` }
Run Code Online (Sandbox Code Playgroud)

Each content has exactly one type, but many type might be exists in many contents

我要检索类型的内容Book

这是我的存储库”

public interface ContentRepository extends JpaRepository<Content, Long> {

    Iterable<Content> findByContentType(String contentType);
}
Run Code Online (Sandbox Code Playgroud)

这是我的测试方法:

@Test
public void retrieve_content_based_on_type() {

    // create and insert a sample content type, i.e. a Book

    ContentType contentType1 = new ContentType("Book");
    contentTypeRepository.save(contentType1);

    //create and insert two contents corresponding to this type
    Content cont1 = new Content("t1", "d1");
    cont1.setContentType(contentType1);
    contentRepository.save(cont1);

    Content cont2 = new Content("t2", "d2");
    cont2.setContentType(contentType1);
    contentRepository.save(cont2);


    //retrieve all contents which their type is Book

    Iterable<Content> allBooks = contentRepository.findByContentType("Book");
    for (Content eachBook : allBooks) {
        System.out.println(eachBook);
    }
}
Run Code Online (Sandbox Code Playgroud)

我得到了这个例外:

org.springframework.dao.InvalidDataAccessApiUsageException: Parameter value [Book] did not match expected type [com.aa.bb.domain.ContentType (n/a)]; 

nested exception is java.lang.IllegalArgumentException: Parameter value [Book] did not match expected type [com.aa.bb.domain.ContentType (n/a)]
Run Code Online (Sandbox Code Playgroud)

pre*_*mar 6

您可以将当前方法修改为:

@Query("select c from Content c where c.contentType.contentType = :contentType")
Iterable<Content> findByContentType(String contentType);
Run Code Online (Sandbox Code Playgroud)

原因:Content 实体中的 contentType 是 ContentType 类型,而 ContentType 实体中的 contentType 是 String 类型

对于不使用查询注释的 Spring Data JPA 而言,解决方案如下:

Iterable<Content> findByContentTypeContentType(String contentType);
Run Code Online (Sandbox Code Playgroud)

Spring数据参考链接

以上方法适用于Repository类ContentRepository。