java.sql.SQLSyntaxErrorException: ORA-00923: 在预期的位置找不到 FROM 关键字

java.sql.SQLSyntaxErrorException: ORA-00923: FROM keyword not found where expected

我正在尝试将本机查询的结果转换为一个名为 Account 的对象。但是当我调用 API 时,它会抛出这个。有趣的是,如果在 sql 开发人员中复制粘贴查询,它会完美运行,而不会抛出“找不到 FROM 关键字......”错误。

org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
Caused by: java.sql.SQLSyntaxErrorException: ORA-00923: FROM keyword not found where expected

这是我的Foo.java

@Entity
@NamedNativeQuery(
        name = "findAllAccounts",
        query =
                "SELECT" +
                        "Q1.ACCOUNT_NAME AS accountName," +
                        "Q2.GROUP_NAME AS groupName" +
                        "FROM USERS_DEV Q1" +
                        "JOIN USERS_GROUPS Q2 ON Q1.ACCOUNT_NAME = Q2.ACCOUNT_NAME" +
                        "WHERE LOWER(Q1.ACCOUNT_NAME) = 'john.lenon'",
        resultSetMapping = "findAllAccountsMapping"
)
@SqlResultSetMapping(
        name = "findAllAccountsMapping",
        classes = @ConstructorResult(
                targetClass = Account.class,
                columns = {
                        @ColumnResult(name = "accountName"),
                        @ColumnResult(name = "groupName"),
                }
        )
)
@Table(name = "abc")
public class Foo {

    @Id
    @Column(name = "ID")
    private Long id;

    @Column(name = "NAME")
    private String name;

    @Column(name = "SOME_NUMBER")
    private String someNumber;
}

Account.java

public class Account {

    String accountName;

    String groupName;

    public Account(String accountName, String groupName) {
        this.accountName = accountName;
        this.groupName = groupName;
    }
}

FooRepository.java

@Repository
public interface FooRepository extends JpaRepository<Foo, Long> {

    @Query(name = "findAllAccounts", nativeQuery = true)
    List<Account> getAllAccounts();

连接字符串时,不同命令之间没有 space

YOUR VERSION

"SELECT" +
    "Q1.ACCOUNT_NAME AS accountName," +
    "Q2.GROUP_NAME AS groupName" +
    "FROM USERS_DEV Q1" +
    "JOIN USERS_GROUPS Q2 ON Q1.ACCOUNT_NAME = Q2.ACCOUNT_NAME" +
    "WHERE LOWER(Q1.ACCOUNT_NAME) = 'john.lenon'",

所以您的 SQL 被“粘”在一起,没有形成正确的 SQL(例如 SELECTQ1.ACCOUNT_NAME ... AS groupNameFROM USERS_DEV Q1

它应该如何

"SELECT" +
    " Q1.ACCOUNT_NAME AS accountName," +
    " Q2.GROUP_NAME AS groupName" +
    " FROM USERS_DEV Q1" +
    " JOIN USERS_GROUPS Q2 ON Q1.ACCOUNT_NAME = Q2.ACCOUNT_NAME" +
    " WHERE LOWER(Q1.ACCOUNT_NAME) = 'john.lenon'",

您需要在每个 SQL 行的末尾添加 spaces(当然也可以在开头)。