简体   繁体   中英

Spring JPA : Query one column from the table without where clause

I am new to JPA and Spring Boot and trying to write a custom query which returns only one column from the table when the API is triggered. But I get an error doing so. It would be helpful if someone could guide me to a correct way of writing this custom query.

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

}

I think that your query should look like this (if you follow conventions):

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

For this query, you UserTestInstance should look like this:

public class UserTestInstance {
    private String testName;

    <getters and setters>
}

This is because you're using JPQL, and you should be querying your objects and their declared variables. It's Spring's Data job to translate to your database specific db query.

Spring Data documentation for reference.

It's ok but you have two options :

  1. You must put your name class in the from clause @Query("SELECT ti.testName FROM UserTestInstance ti")
  2. Use a native query whith the real name of Database @Query(value="SELECT ti.test_name FROM test_instance ti",nativeQuery=true)

I used JpaRepository for this purpose.

Controller class

@Autowired
private UserTestInstanceDao usertestdao;

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

DAO class:

public interface UserTestInstanceDao extends JpaRepository<UserTestInstance, Long> {

    @Query(value="SELECT test_name FROM ti", nativeQuery = true)

    public List<String> tempQuery();

}

And these are in my 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

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