当前位置: 首页 > 知识库问答 >
问题:

Spring JPA在Distinct查询上返回空列表

梁丘远航
2023-03-14

我有一个奇怪的怪癖,当我运行一个nativeQuery调用单个列中的所有不同值时,我没有得到任何结果。然而,当我从查询中删除“distinct”操作符时,它的工作非常好,告诉我这不是数据库连接或内容问题。

控制器方法:

    @GetMapping("/getGenres")
    public ResponseEntity<Object> getGenres() {
        return ResponseEntity.ok(genreRepo.findDistinctGenre());
    }
    @Query(value = "SELECT DISTINCT genre FROM genres", nativeQuery = true)
    List<String> findDistinctGenre();
[]
    @Query(value = "SELECT genre FROM genres", nativeQuery = true)
    List<String> findDistinctGenre();
["2D","Survival","Battle Royal","Builder","Shooter","RPG"]

显然,我可以编写一个“distinct”方法来遍历这个列表,但对我来说,查询不起作用似乎很奇怪

编辑:在备注中请求的存储库和实体类中添加

资源库接口:

@Repository
public interface GenreRepository extends CrudRepository<Genre, Integer> {
    @Query(value = "SELECT DISTINCT genre FROM genres", nativeQuery = true)
    List<String> findDistinctGenre();
}
@Entity
@Table(name = "genres")
@IdClass(GenreId.class)
public class Genre{

    @Id
    @Column(name = "game_id", nullable = false)
    private int gameId;

    @Id
    @Column(name = "genre", nullable = false)
    private String genre;

    public int getGameId() {
        return gameId;
    }

    public void setGameId(int gameId) {
        this.gameId = gameId;
    }

    public String getGenre() {
        return genre;
    }

    public void setGenre(String genre) {
        this.genre = genre;
    }
}
public class GenreId implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    private int gameId;

    private int genre;

    public UsersInGroupId() {

    }

    public UsersInGroupId(int gameId, String genre) {
        this.gameId= gameId;
        this.genre= genre;
    }

    public int getGameId() {
        return gameId;
    }

    public void setGameId(int gameId) {
        this.gameId = gameId;
    }

    public String getGenre() {
        return genre;
    }

    public void setGenre(String genre) {
        this.genre = genre;
    }

    public boolean equals(Object o) {
        if (!(o instanceof GenreId)) {
            return false;
        }

        GenreId id = (GenreId) o;

        return id.gameId == this.gameId && id.genre.equals(this.genre);
    }
}

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.2.RELEASE)

2020-11-20 17:52:19.853  INFO 13112 --- [           main] edu.edgewood.ApplicationRuntime          : Starting ApplicationRuntime on LAPTOP-V9B5V6E5 with PID 13112 (C:\Users\logan\eclipse-workspace\final-project\target\classes started by logan in C:\Users\logan\eclipse-workspace\final-project)
2020-11-20 17:52:19.856  INFO 13112 --- [           main] edu.edgewood.ApplicationRuntime          : No active profile set, falling back to default profiles: default
2020-11-20 17:52:20.846  INFO 13112 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFERRED mode.
2020-11-20 17:52:20.929  INFO 13112 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 73ms. Found 6 JPA repository interfaces.
2020-11-20 17:52:22.060  INFO 13112 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2020-11-20 17:52:22.072  INFO 13112 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-11-20 17:52:22.073  INFO 13112 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.37]
2020-11-20 17:52:22.191  INFO 13112 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2020-11-20 17:52:22.192  INFO 13112 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2272 ms
2020-11-20 17:52:22.640  INFO 13112 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-11-20 17:52:22.706  INFO 13112 --- [         task-1] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-11-20 17:52:22.752  WARN 13112 --- [           main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2020-11-20 17:52:22.784  INFO 13112 --- [         task-1] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 5.4.18.Final
2020-11-20 17:52:23.052  INFO 13112 --- [         task-1] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-11-20 17:52:23.266  INFO 13112 --- [         task-1] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2020-11-20 17:52:24.214  INFO 13112 --- [         task-1] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2020-11-20 17:52:24.255  INFO 13112 --- [         task-1] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
2020-11-20 17:52:24.593  WARN 13112 --- [         task-1] org.hibernate.mapping.RootClass          : HHH000039: Composite-id class does not override hashCode(): edu.edgewood.data.UsersInGroupId
2020-11-20 17:52:25.157  INFO 13112 --- [         task-1] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-11-20 17:52:25.168  INFO 13112 --- [         task-1] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-11-20 17:52:25.230  INFO 13112 --- [           main] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 2 endpoint(s) beneath base path '/actuator'
2020-11-20 17:52:25.298  INFO 13112 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2020-11-20 17:52:25.300  INFO 13112 --- [           main] DeferredRepositoryInitializationListener : Triggering deferred initialization of Spring Data repositories…
2020-11-20 17:52:26.029  INFO 13112 --- [           main] DeferredRepositoryInitializationListener : Spring Data repositories initialized!
2020-11-20 17:52:26.039  INFO 13112 --- [           main] edu.edgewood.ApplicationRuntime          : Started ApplicationRuntime in 6.627 seconds (JVM running for 7.162)
2020-11-20 17:52:31.094  INFO 13112 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-11-20 17:52:31.094  INFO 13112 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2020-11-20 17:52:31.102  INFO 13112 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 8 ms
Hibernate: select distinct(c.genre) from genres c

创建和修改表的SQL

CREATE TABLE `genres` (
  `game_id` int(8) NOT NULL,
  `genre` varchar(25) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

INSERT INTO `genres` (`game_id`, `genre`) VALUES
(1, 'Survival'),
(1, '2D'),
(2, 'Shooter'),
(2, 'Battle Royal'),
(2, 'Builder'),
(3, 'RPG');

ALTER TABLE `genres`
  ADD PRIMARY KEY (`game_id`,`genre`),
  ADD KEY `genres_ibfk1` (`game_id`),
  ADD FULLTEXT(`genre`);

ALTER TABLE `genres`
  ADD CONSTRAINT `genres_ibfk_1` FOREIGN KEY (`game_id`) REFERENCES `games` (`game_id`) ON DELETE NO ACTION ON UPDATE NO ACTION;

共有1个答案

葛宪
2023-03-14

在使用ADD FULLTEXT(genre)更改表后,会出现一个区别;

 类似资料:
  • 我如何告诉Panache查询的结果将是而不是? 谢谢你的回答 编辑:回购代码:

  • 我正在尝试从我的应用打开Gmail(点击按钮)。我只在Android11中面临这个问题。这不是打开Gmail。在本例中,QueryInputActivities返回空列表。 请帮助我解决android 11的这个问题。下面是我正在使用的代码。。

  • 问题内容: 我创建了一个Hive表,该表从文本文件加载数据。但是它对所有查询返回的空结果集。 我尝试了以下命令: 命令被执行,并且表被创建。但是,对于所有查询,始终返回0行,包括 样本数据: 单行输入数据: 1 | 155190 | 7706 | 1 | 17 | 21168.23 | 0.04 | 0.02 | N | O | 1996-03-13 | 1996-02-12 | 1996-03-

  • 问题内容: 我正在尝试编写一个查询,该查询从GPSReport表返回每个唯一设备的最新GPS位置。表中有50个设备,所以我只希望返回50行。 这是我到目前为止(无法正常工作) 这将返回50行,但不会为每个device_serial返回唯一的行。它返回第一个设备的所有报告,然后返回第二个设备的所有报告,依此类推。 我要在一个查询中执行的操作是否可行? 问题答案:

  • 设备:Emulator pixel 3a-Android11 代码: 使用时: listCam大小为0 当切换到: listCam大小是1-因为它应该是。 使用以下代码: 工作正常,并显示相机应用程序。 你知道为什么queryIntentActivities没有返回摄像机的意图吗? 谢谢!

  • 问题内容: 如何获取使用SQL Server的SQL查询返回的列数? 例如,如果我有如下查询: 它应该返回表A1中的总列数+表A2中的总列数。但是查询可能会更复杂。 问题答案: 这是一种方法: 您可以通过创建视图来执行类似的操作。