【问题标题】:Spring JPA : Query one column from the table without where clauseSpring JPA:从没有where子句的表中查询一列
【发布时间】:2017-01-22 17:21:32
【问题描述】:

我是 JPA 和 Spring Boot 的新手,我正在尝试编写一个自定义查询,当 API 被触发时,它只返回表中的一列。但是我这样做会出错。如果有人可以指导我以正确的方式编写此自定义查询,那将很有帮助。

// Controller class
@Autowired
private UserTestInstanceDao usertestdao;

List<String> usertestinst = usertestdao.tempQuery();

// DAO class

public interface UserTestInstanceDao extends CrudRepository<UserTestInstance, Long> {

@Query("SELECT ti.test_name FROM test_instance ti")
public List<String> tempQuery();

}

【问题讨论】:

  • 您希望得到一个列表吗?
  • “我收到一个错误”。你不想分享它是什么?!

标签: java spring-boot spring-data-jpa jpql


【解决方案1】:

我认为您的查询应该如下所示(如果您遵循约定):

@Query("SELECT ti.testName FROM UserTestInstance ti")

对于此查询,您的 UserTestInstance 应如下所示:

public class UserTestInstance {
    private String testName;

    <getters and setters>
}

这是因为您使用的是 JPQL,并且您应该查询您的对象及其声明的变量。 Spring 的 Data 工作是转换为特定于数据库的 db 查询。

Spring Data 参考文档。

【讨论】:

    【解决方案2】:

    没关系,但你有两个选择:

    1. 你必须把你的名字类放在 from 子句@Query("SELECT ti.testName FROM UserTestInstance ti")
    2. 使用实名数据库@Query(value="SELECT ti.test_name FROM test_instance ti",nativeQuery=true)的本机查询

    【讨论】:

      【解决方案3】:

      我为此使用了 JpaRepository

      控制器类

      @Autowired
      private UserTestInstanceDao usertestdao;
      
      //in method
      List<String> usertestinst = usertestdao.tempQuery();
      

      DAO 类:

      public interface UserTestInstanceDao extends JpaRepository<UserTestInstance, Long> {
      
          @Query(value="SELECT test_name FROM ti", nativeQuery = true)
      
          public List<String> tempQuery();
      
      }
      

      这些都在我的 application.properties:

      # DATASOURCE
      spring.datasource.url=jdbc:mysql://localhost/test_instance 
      spring.datasource.username=root
      spring.datasource.password=password
      spring.datasource.driver-class-name=com.mysql.jdbc.Driver
      
      # JPA
      spring.jpa.properties.hibernate.globally_quoted_identifiers=true
      spring.jpa.hibernate.ddl-auto=update
      spring.jpa.show-sql=true
      spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy
      spring.data.jpa.repositories.enabled=true
      spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
      

      【讨论】:

        猜你喜欢
        • 2012-02-17
        • 2011-07-05
        • 2019-08-10
        • 1970-01-01
        • 2021-12-24
        • 2016-04-29
        • 2015-03-24
        • 2020-12-23
        • 1970-01-01
        相关资源
        最近更新 更多