我有两个简单的表,content
和 contentType
@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` }
每个内容只有一种类型,但许多内容中可能存在多种类型
我要检索 Book
类型的内容
这是我的存储库”
public interface ContentRepository extends JpaRepository<Content, Long> {
Iterable<Content> findByContentType(String contentType);
}
这是我的测试方法:
@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);
}
}
我遇到了这个异常:
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)]
最佳答案
您可以将当前方法修改为:
@Query("select c from Content c where c.contentType.contentType = :contentType")
Iterable<Content> findByContentType(String contentType);
原因:Content 实体中的 contentType 是 ContentType 类型,而 ContentType 实体中的 contentType 是 String 类型
对于不使用查询注释的Spring Data JPA,解决方案如下:
Iterable<Content> findByContentTypeContentType(String contentType);
Spring 数据引用 Link
以上方法适用于 Repository 类 ContentRepository。
关于java - spring data jpa - 参数值[Book]与预期类型[ContentType]不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34128108/