简体   繁体   中英

Spring JPA Returning Empty List On Distinct Query

I've got an odd quirk where when I run a nativeQuery that calls for all distinct values from a single column, I don't get any results. However, when I remove the "distinct" operator from the query, it works perfectly fine, telling me that it's not a database connectivity or content issue.

Controller Method:

    @GetMapping("/getGenres")
    public ResponseEntity<Object> getGenres() {
        return ResponseEntity.ok(genreRepo.findDistinctGenre());
    }

Repository Interface Method

    @Query(value = "SELECT DISTINCT genre FROM genres", nativeQuery = true)
    List<String> findDistinctGenre();

Results with this method

[]

"Working", but not distinct method

    @Query(value = "SELECT genre FROM genres", nativeQuery = true)
    List<String> findDistinctGenre();

Results from this method

["2D","Survival","Battle Royal","Builder","Shooter","RPG"]

I could obviously code a "distinct" method to go through this list, but it seems weird to me that the query is not working

Edit: Adding in the repository and entity classes since those were requested in the comments

Respository Interface:

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

Genre Entity Class:

@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;
    }
}

GenreId Class:

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);
    }
}

Logs (including the query being shown from spring.jpa.show-sql=true)


  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: 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 that created and modified the table

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;

使用 ADD FULLTEXT( genre ); 更改表格后会发生区别。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM