在Criteria Select中返回@OneToMany相关实体的List <e>

时间:2018-01-06 13:42:38

标签: java hibernate jpa criteria

我有三个类,如下例所示:

@Entity
public class Book {

  @Id
  private Long id;

  @ManyToOne
  private Author author;

  private String name;

  private LocalDate publishDate;

  private Long numberOfPages;

  // Getters and Setters
}

@Entity
public class Author {

    @Id
    private Long id;

    private String name;

    private String city;

    private LocalDate birthday;

    @OneToMany
    private List<Book> books;

    // Getters and Setters
}

public class BooksOfAuthor {

    private String authorName;
    private List<Book> books;

    public BooksOfAuthor(String authorName, List<Book> books) {
        this.authorName = authorName;
        this.books = books;
    }

    // Getters and Setters
}

BooksOfAuthor是Author和Book的简化表示。我尝试创建条件选择以填充此表示,如下所示:

public List<BooksOfAuthor> simplifiedSelect() {
    CriteriaBuilder builder = manager.getCriteriaBuilder();
    CriteriaQuery<BooksOfAuthor> criteria = builder.createQuery(BooksOfAuthor.class);
    Root<Author> root = criteria.from(Author.class);

    criteria.select(builder.construct(BooksOfAuthor.class, 
            root.get(Author_.name),
            root.get(Author_.books)));

    TypedQuery<BooksOfAuthor> query = manager.createQuery(criteria);

    return query.getResultList();
}

但这不起作用,我收到以下错误:

[dispatcherServlet] in context with path [] threw exception
  [Request processing failed; nested exception is
    org.springframework.dao.InvalidDataAccessApiUsageException:
      org.hibernate.hql.internal.ast.QuerySyntaxException:
        Unable to locate appropriate constructor on class
        [BooksOfAuthor]. Expected arguments are:
        String, java.util.Collection
        [select new BooksOfAuthor(generatedAlias0.name, generatedAlias0.books) from Author as generatedAlias0 where 1=1;

如何正确选择?

0 个答案:

没有答案