如何使用参数数据成员进行本机查询?

问题描述 投票:0回答:1

我正在尝试在

CrudRepository<>
中创建一个 upsert 查询,其中包含 PostgresSQL 查询,但需要从对象的属性中填充值。我尝试使用预期与 JPQL 配合使用的语法,但每当我尝试运行应用程序时,都会收到错误
Reason: The query is not a valid SQL query

如何在 Spring 中创建一个本机查询,它允许我访问传递对象的数据成员?

import java.util.Optional;
import java.util.UUID;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

@Repository
public interface AuthorRepo extends JpaRepository<AuthorEntity, UUID> {
    
    @Query(
            value = """
                    INSERT
                    INTO author
                    VALUES (
                        :authorEntity.getId(),
                        :authorEntity.getName()
                    )
                    RETURNING *
                    ON CONFLICT (name)
                    DO UPDATE
                    """,
            nativeQuery = true
    )
    AuthorEntity saveByName(@Param("authorEntity") AuthorEntity authorEntity);

    Optional<AuthorEntity> findByName(String name);
    
}

spring spring-boot jpa jdbc spring-data
1个回答
0
投票

您可以查看以下版本吗

@Query(
        value = "INSERT INTO author (id, name) VALUES (:#{#authorEntity.id}, :#{#authorEntity.name})" +
                " ON CONFLICT (name) DO UPDATE SET name = :#{#authorEntity.name} RETURNING *",
        nativeQuery = true
)
AuthorEntity saveByName(@Param("authorEntity") AuthorEntity authorEntity);
© www.soinside.com 2019 - 2024. All rights reserved.