猿问

将 SQL 查询放入 CrudRepository 中以限制列(以及此后的进一步 SQL 查询)

我正在开发一个 Spring 应用程序,它记录用户请求响应(将其发送到数据库并检索它)。获取记录代码是这样的(控制器):


/**

     * this method fetches all userrequest response records from user_request_response table

     * @return

     */

    @CrossOrigin(origins = "*")

    @GetMapping(path="/all")

    public @ResponseBody Iterable<UserRequestResponse> getAllRequestResponseRecords() {

        return userRequestResponseRepository.findAll();

    }

Dao code:


import org.springframework.data.jpa.repository.Query;

import org.springframework.data.repository.CrudRepository;


import com.abc.datacollection.entity.UserProjection;

import com.abc.datacollection.entity.UserRequestResponse;


public interface UserRequestResponseRepository extends CrudRepository<UserRequestResponse, Integer> {



public static final String FIND_QUERY = 

            "select new com.abc.datacollection.entity.UserRequestResponse(user.u_httpstatus ,user.u_queryparam) from UserRequestResponse user";

    @Query(value = FIND_QUERY)

    List<UserProjection> getAllRequestResponseRecords();


}

具有 getter 和 setter 的类:(删除了一些变量及其 getter 和 setter)


import java.sql.Date;


import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;


@Entity // This tells Hibernate to make a table out of this class

public class UserRequestResponse {

    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)


    private String u_httpstatus;


    private String u_error_message;


    private String u_queryparam;



public UserRequestResponse(String u_httpstatus, String u_queryparam) {

        this.u_httpstatus = u_httpstatus;

        this.u_queryparam = u_queryparam;

    }

    public int getSys_id() {

        return sys_id;

    }

public String getU_httpstatus() {

            return u_httpstatus;

        }



MySQL查询示例(我试图将查询放入CrudRepository中的java代码中,InternSearchAnalytics.user_request_response是表的名称):


select u_httpstatus, u_queryparam from InternSearchAnalytics.user_request_response

但是,当我运行 java 代码并点击生成的端点时,我得到了所有字段。有人可以帮我吗?我已经被这个问题困扰了两天了。


沧海一幻觉
浏览 80回答 1
1回答

烙印99

您可以使用类中的新构造函数从查询中获取选定的字段,UserRequestResponse例如public UserRequestResponse(String u_httpstatus, String u_queryparam) {&nbsp; &nbsp; this.u_httpstatus = u_httpstatus;&nbsp; &nbsp; this.u_queryparam = u_queryparam;}对于查询,您应该使用构造函数更改它public static final String FIND_QUERY =&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "select new com.your.package.name.UserRequestResponse(user.u_httpstatus ,user.u_queryparam) from UserRequestResponse user";一点是您需要使用具有完全限定名称的构造函数。希望这可以帮助。
随时随地看视频慕课网APP

相关分类

Java
我要回答