我也有同样的情况。有两个实体:
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "book_id")
int id;
@Column(name = "book_name")
String name;
@ManyToOne
@JoinColumn(name = "book_author", referencedColumnName = "person_id")
Person author;
@ManyToOne
@JoinColumn(name = "book_reviewer", referencedColumnName = "person_id")
Person reviewer;
public Book(String name, Person author, Person reviewer) {
this.name = name;
this.author = author;
this.reviewer = reviewer;
}
public Book() {
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", name='" + name + '\'' +
", author=" + author +
", reviewer=" + reviewer +
'}';
}
}
和
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "person_id")
int id;
@Column(name = "person_name")
String name;
public Person(String name) {
this.name = name;
}
public Person() {
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
当我使用自定义查询创建 BookRepository
public interface BookRepository extends CrudRepository<Book, Integer> {
List<Book> findAll();
@Query("SELECT id, name, author, reviewer FROM Book")
List<Book> testQuery();
}
抛出异常
Caused by: org.hibernate.QueryException: No data type for node: org.hibernate.hql.internal.ast.tree.IdentNode
\-[IDENT] IdentNode: 'reviewer' {originalText=reviewer}
at org.hibernate.hql.internal.ast.tree.SelectClause.initializeExplicitSelectClause(SelectClause.java:161) ~[hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.hql.internal.ast.HqlSqlWalker.useSelectClause(HqlSqlWalker.java:1026) ~[hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.hql.internal.ast.HqlSqlWalker.processQuery(HqlSqlWalker.java:794) ~[hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:694) ~[hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:330) ~[hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:278) ~[hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:276) ~[hibernate-core-5.4.28.Final.jar:5.4.28.Final]
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:192) ~[hibernate-core-5.4.28.Final.jar:5.4.28.Final]
... 73 common frames omitted
但是如果我删除第二个引用列
@Query("SELECT id, name, author FROM Book")
List<Book> testQuery();
程序无异常启动。
问题通过更换解决
@Query("SELECT id, name, author, reviewer FROM Book")
和
@Query("SELECT id, name, b.author, b.reviewer FROM Book b")