2016-09-14 287 views
1

我是JPA和Spring Boot的新手,尝试编写一个自定义查询,该API在触发API时仅返回表中的一列。但是我收到了一个错误。如果有人能指导我以正确的方式编写这个自定义查询,那将会很有帮助。Spring JPA:从表中查询一列,但不包含where子句

// 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(); 

} 
+0

您是否期待结果列表? – Maroun

+0

“我收到一个错误”。你不想分享它是什么?! –

回答

2

我认为你的查询应该是这样的(如果你按照惯例):

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

对于此查询,您UserTestInstance应该是这样的:

public class UserTestInstance { 
    private String testName; 

    <getters and setters> 
} 

这是因为你正在使用JPQL,你应该查询你的对象和他们声明的变量。这是Spring的数据作业,可以转换为数据库特定的数据库查询。

Spring Data文档仅供参考。

1

这没关系,但你有两种选择:

  1. 你必须把你的名字类from子句@Query("SELECT ti.testName FROM UserTestInstance ti")
  2. 使用蒙山数据库@Query(value="SELECT ti.test_name FROM test_instance ti",nativeQuery=true)
0

我的真名本机查询为此目的使用JpaRepository

Controller类

@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