我有两个简单的表,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` }
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);
}
这是我的测试方法:
@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实体中,其String类型
对于不使用查询注释的Spring Data JPA,以下是解决方案:
Iterable<Content> findByContentTypeContentType(String contentType);
Spring数据参考Link
上面的方法适用于Repository类的ContentRepository。