gpt4 book ai didi

spring-boot - Spring 启动 : Custome @Query with 2 consecutive brackets cause that one pair is ignored

转载 作者:行者123 更新时间:2023-12-05 05:19:42 25 4
gpt4 key购买 nike

在我的 JpaRepository 中,我有以下 @Query:

@Query("SELECT m FROM Msg m WHERE ((m.from = ?1 AND m.to = ?2) OR (m.from = ?2 AND m.to = ?1))  AND m.time = ?3")
Msg find(String firstId, String secondId, long lastAccess);

但是在日志控制台中记录的查询没有大括号,而且似乎是这样执行的:

SELECT m FROM Msg m WHERE (m.from = ?1 AND m.to = ?2) OR (m.from = ?2 AND m.to = ?1)  AND m.time = ?3

那么如何正确添加多个连续的括号呢?


我使用:

Derby 战

Spring Boot 1.4.3.RELEASE

最佳答案

我使用具有两个依赖项的 Spring Boot 1.4.3-RELEASE1.5.4-RELEASE 做了一些小调查:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>

我模仿了你的 JpaRespository:

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

interface PersonRepository extends JpaRepository<Person, Long> {

@Query("SELECT p FROM Person p WHERE ((p.firstName = :firstName AND p.lastName = :lastName) OR (p.firstName = :lastName AND p.lastName = :firstName)) AND p.age = :age")
Person findWithCustomQuery(@Param("firstName") String firstName, @Param("lastName") String lastName, @Param("age") Integer age);
}

这是 Person 类的样子:

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
@Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Person {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

private String firstName;

private String lastName;

private Integer age;
}

Here is full source code: https://github.com/wololock/stackoverflow-answers/tree/master/45629734

我看到执行的 SQL 查询如下:

select person0_.id as id1_0_, person0_.age as age2_0_, person0_.first_name as first_na3_0_, person0_.last_name as last_nam4_0_ from person person0_ where (person0_.first_name=? and person0_.last_name=? or person0_.first_name=? and person0_.last_name=?) and person0_.age=?

如你所见,括号简化为

(person0_.first_name=? and person0_.last_name=? or person0_.first_name=? and person0_.last_name=?)

但它仍然是正确的,因为 and 运算符的优先级高于 or 运算符。

需要更多信息

我很想帮助您找到问题的解决方案,但我需要更多信息,例如

  • 你使用什么数据库(我在这个例子中使用了 H2,很明显不同的 SQL 方言可能会生成不同的查询)
  • 您使用哪个版本的 Spring Boot?
  • 您使用哪个版本的 Spring Data?

关于spring-boot - Spring 启动 : Custome @Query with 2 consecutive brackets cause that one pair is ignored,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45629734/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com