错误:无法为具有多个返回的查询创建 TypedQuery [英] Error: Cannot create TypedQuery for query with more than one return
问题描述
我尝试使用 java 和 jpa 来实现 searchBook 功能.我有 2 个课程,即媒体和书籍.本书扩展了媒体.我将数据保存在不同的表中.我尝试从以下查询中选择数据:
I try to do the function searchBook with java and jpa. I have 2 classes which are Media and Book. Book extends Media. And I keep the data in the different table. I try to select the data from the query below:
TypedQuery<Media> query = em.createQuery(
"SELECT m.title, b.isbn, b.authors"
+ " FROM Book b, Media m" + " WHERE b.isbn = :isbn"
+ " OR lower(m.title) LIKE :title"
+ " OR b.authors LIKE :authors", Media.class);
query.setParameter("isbn", book.getisbn());
query.setParameter("title", "%" + book.getTitle().toLowerCase()
+ "%");
query.setParameter("authors", "%" + book.getAuthors() + "%");
bookList = query.getResultList();
但是我得到了错误:
java.lang.IllegalArgumentException:无法为查询创建 TypedQuery多次返回
java.lang.IllegalArgumentException: Cannot create TypedQuery for query with more than one return
这是我第一次使用 JPA.我找不到错误.
This is the first time I use JPA. I can't find the the mistake.
推荐答案
没有详细说明 Media
和 Book
应该如何建模,我至少会解释为什么你得到这个例外.
Without goind into details about how Media
and Book
should be modeled, I will at least explain why you get this exception.
你在做什么:
em.createQuery(someJPQL, Media.class);
这意味着:使用 someJPQL
创建一个查询,该查询将返回 Media
实体的实例.
This means: create a query using someJPQL
, and this query will return instances of the Media
entity.
但是你的 JPQL
是:
SELECT m.title, b.isbn, b.authors ...
因此查询不会返回媒体类型的实体.它从两个不同的实体返回三个字段.您的 JPA 引擎无法从这 3 列神奇地创建 Media 实例.如果它看起来像这样,查询将返回 Media 的实例:
So the query does not return entities of type Media. It returns three fields, from two different entities. There is no way your JPA engine could magically create instances of Media from these 3 columns. A query would return instances of Media if it looked like this:
select m from Media m ...
这篇关于错误:无法为具有多个返回的查询创建 TypedQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!