Why the Spring's @Query annotation returns Object type?Spring JPA selecting specific columnsSpring- How to remove a property from a list of Objects?Spring Data JPA: How can Query return Non- Entities Objects or List of Objects?Spring data JPA and parameters that can be nullspring-boot / spring-data-jpa custom query filtering by Date field returning results without filteringReturn custom Object using custom Query with Spring Data JPAHow to Return all instances of the type with the given ID in JPA SpringBoot?not able to execute between date jpa data with query annotation@Query annotation and named parameters in quoted stringsOptional param with query Spring-Boot jpa 1.5JPQL with specific column returning Object arraySpring Data and Oracle returns different result from query? Why?

how to find the equation of a circle given points of the circle

Is there an official tutorial for installing Ubuntu 18.04+ on a device with an SSD and an additional internal hard drive?

Is this homebrew Wind Wave spell balanced?

How would one muzzle a full grown polar bear in the 13th century?

Packing rectangles: Does rotation ever help?

Why do Computer Science majors learn Calculus?

Does a semiconductor follow Ohm's law?

How can Republicans who favour free markets, consistently express anger when they don't like the outcome of that choice?

Does a strong solution to a SDE imply lipschitz condition?

Rivers without rain

Seemingly unused edef prior to an ifx mysteriously affects the outcome of the ifx. Why?

How to make a pipeline wait for end-of-file or stop after an error?

How can I place the product on a social media post better?

Why other Westeros houses don't use wildfire?

What makes accurate emulation of old systems a difficult task?

Do I have an "anti-research" personality?

Is the claim "Employers won't employ people with no 'social media presence'" realistic?

Unexpected email from Yorkshire Bank

How to reduce LED flash rate (frequency)

French for 'It must be my imagination'?

A ​Note ​on ​N!

Is there really no use for MD5 anymore?

How did Captain America manage to do this?

Do I have to worry about players making “bad” choices on level up?



Why the Spring's @Query annotation returns Object type?


Spring JPA selecting specific columnsSpring- How to remove a property from a list of Objects?Spring Data JPA: How can Query return Non- Entities Objects or List of Objects?Spring data JPA and parameters that can be nullspring-boot / spring-data-jpa custom query filtering by Date field returning results without filteringReturn custom Object using custom Query with Spring Data JPAHow to Return all instances of the type with the given ID in JPA SpringBoot?not able to execute between date jpa data with query annotation@Query annotation and named parameters in quoted stringsOptional param with query Spring-Boot jpa 1.5JPQL with specific column returning Object arraySpring Data and Oracle returns different result from query? Why?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I have the below query to fetch specific columns of a entity/table from database



@Query("SELECT u.email, u.password FROM User u WHERE email = :email")
Optional<User> getCredentialsByEmail( @Param("email") String email);


But this gives the ClassCastException, and that's because the query return the Object type instead of User.



Whereas, if I select all the columns as below:



@Query("SELECT u FROM User u WHERE email = :email")
Optional<User> getCredentialsByEmail( @Param("email") String email);


the query return the correct class type i.e User. I don't understand why this difference is provided by the Spring framework.



Any suggestions please.










share|improve this question






















  • you may get answer from here stackoverflow.com/questions/22007341/…

    – Patel Romil
    Mar 23 at 5:14

















0















I have the below query to fetch specific columns of a entity/table from database



@Query("SELECT u.email, u.password FROM User u WHERE email = :email")
Optional<User> getCredentialsByEmail( @Param("email") String email);


But this gives the ClassCastException, and that's because the query return the Object type instead of User.



Whereas, if I select all the columns as below:



@Query("SELECT u FROM User u WHERE email = :email")
Optional<User> getCredentialsByEmail( @Param("email") String email);


the query return the correct class type i.e User. I don't understand why this difference is provided by the Spring framework.



Any suggestions please.










share|improve this question






















  • you may get answer from here stackoverflow.com/questions/22007341/…

    – Patel Romil
    Mar 23 at 5:14













0












0








0








I have the below query to fetch specific columns of a entity/table from database



@Query("SELECT u.email, u.password FROM User u WHERE email = :email")
Optional<User> getCredentialsByEmail( @Param("email") String email);


But this gives the ClassCastException, and that's because the query return the Object type instead of User.



Whereas, if I select all the columns as below:



@Query("SELECT u FROM User u WHERE email = :email")
Optional<User> getCredentialsByEmail( @Param("email") String email);


the query return the correct class type i.e User. I don't understand why this difference is provided by the Spring framework.



Any suggestions please.










share|improve this question














I have the below query to fetch specific columns of a entity/table from database



@Query("SELECT u.email, u.password FROM User u WHERE email = :email")
Optional<User> getCredentialsByEmail( @Param("email") String email);


But this gives the ClassCastException, and that's because the query return the Object type instead of User.



Whereas, if I select all the columns as below:



@Query("SELECT u FROM User u WHERE email = :email")
Optional<User> getCredentialsByEmail( @Param("email") String email);


the query return the correct class type i.e User. I don't understand why this difference is provided by the Spring framework.



Any suggestions please.







spring-boot spring-data-jpa






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 22 at 18:07









TheCoderTheCoder

506420




506420












  • you may get answer from here stackoverflow.com/questions/22007341/…

    – Patel Romil
    Mar 23 at 5:14

















  • you may get answer from here stackoverflow.com/questions/22007341/…

    – Patel Romil
    Mar 23 at 5:14
















you may get answer from here stackoverflow.com/questions/22007341/…

– Patel Romil
Mar 23 at 5:14





you may get answer from here stackoverflow.com/questions/22007341/…

– Patel Romil
Mar 23 at 5:14












2 Answers
2






active

oldest

votes


















0














If you required only couple of columns the you can use Object[] object array



@Query("SELECT u.email, u.password FROM User u WHERE email = :email")
Optional<Object[]> getCredentialsByEmail( @Param("email") String email);


From 0 position you can get the email



From 1 position you can get the password



If you like to make it much clear, use Interface



public interface Response 

public String getEmail();

public String getPAssword();




Query make sure column names and get names should match, if not you can use allies in query



@Query("SELECT u.email, u.password FROM User u WHERE email = :email")
Optional<Response> getCredentialsByEmail( @Param("email") String email);





share|improve this answer






























    0














    As commented your first query does not return User object but a Tuple containing the selected columns. Tuple is not necessarily tied to any specific entity but just a set of columns your query returns.



    There are at least following options how you can handle this:



    • make your repo method return a tuple object

    • make a DTO for selected columns and instantiate it with new operator

    • with new operator make a constructor for your user object that takes selected columns

    The last option would be like creating a constructor:



    public User(String email, String password ) 
    // set the field values



    and query like:



    @Query("SELECT NEW some.package.User(u.email u.password) FROM USER u WHERE email = :email")


    For more details see this question






    share|improve this answer

























    • I cannot use DTOs in the persistence layer. They are all created in Web layer for some reasons. Isn't there any other way(not Tuple)?

      – TheCoder
      Mar 22 at 18:30











    • @TheCoder see the last option I wrote, creatign User with new operator with a specific constructor. I'll edit the answer a bit.

      – pirho
      Mar 22 at 18:36











    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55305508%2fwhy-the-springs-query-annotation-returns-object-type%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    If you required only couple of columns the you can use Object[] object array



    @Query("SELECT u.email, u.password FROM User u WHERE email = :email")
    Optional<Object[]> getCredentialsByEmail( @Param("email") String email);


    From 0 position you can get the email



    From 1 position you can get the password



    If you like to make it much clear, use Interface



    public interface Response 

    public String getEmail();

    public String getPAssword();




    Query make sure column names and get names should match, if not you can use allies in query



    @Query("SELECT u.email, u.password FROM User u WHERE email = :email")
    Optional<Response> getCredentialsByEmail( @Param("email") String email);





    share|improve this answer



























      0














      If you required only couple of columns the you can use Object[] object array



      @Query("SELECT u.email, u.password FROM User u WHERE email = :email")
      Optional<Object[]> getCredentialsByEmail( @Param("email") String email);


      From 0 position you can get the email



      From 1 position you can get the password



      If you like to make it much clear, use Interface



      public interface Response 

      public String getEmail();

      public String getPAssword();




      Query make sure column names and get names should match, if not you can use allies in query



      @Query("SELECT u.email, u.password FROM User u WHERE email = :email")
      Optional<Response> getCredentialsByEmail( @Param("email") String email);





      share|improve this answer

























        0












        0








        0







        If you required only couple of columns the you can use Object[] object array



        @Query("SELECT u.email, u.password FROM User u WHERE email = :email")
        Optional<Object[]> getCredentialsByEmail( @Param("email") String email);


        From 0 position you can get the email



        From 1 position you can get the password



        If you like to make it much clear, use Interface



        public interface Response 

        public String getEmail();

        public String getPAssword();




        Query make sure column names and get names should match, if not you can use allies in query



        @Query("SELECT u.email, u.password FROM User u WHERE email = :email")
        Optional<Response> getCredentialsByEmail( @Param("email") String email);





        share|improve this answer













        If you required only couple of columns the you can use Object[] object array



        @Query("SELECT u.email, u.password FROM User u WHERE email = :email")
        Optional<Object[]> getCredentialsByEmail( @Param("email") String email);


        From 0 position you can get the email



        From 1 position you can get the password



        If you like to make it much clear, use Interface



        public interface Response 

        public String getEmail();

        public String getPAssword();




        Query make sure column names and get names should match, if not you can use allies in query



        @Query("SELECT u.email, u.password FROM User u WHERE email = :email")
        Optional<Response> getCredentialsByEmail( @Param("email") String email);






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 22 at 18:37









        DeadpoolDeadpool

        8,4222831




        8,4222831























            0














            As commented your first query does not return User object but a Tuple containing the selected columns. Tuple is not necessarily tied to any specific entity but just a set of columns your query returns.



            There are at least following options how you can handle this:



            • make your repo method return a tuple object

            • make a DTO for selected columns and instantiate it with new operator

            • with new operator make a constructor for your user object that takes selected columns

            The last option would be like creating a constructor:



            public User(String email, String password ) 
            // set the field values



            and query like:



            @Query("SELECT NEW some.package.User(u.email u.password) FROM USER u WHERE email = :email")


            For more details see this question






            share|improve this answer

























            • I cannot use DTOs in the persistence layer. They are all created in Web layer for some reasons. Isn't there any other way(not Tuple)?

              – TheCoder
              Mar 22 at 18:30











            • @TheCoder see the last option I wrote, creatign User with new operator with a specific constructor. I'll edit the answer a bit.

              – pirho
              Mar 22 at 18:36















            0














            As commented your first query does not return User object but a Tuple containing the selected columns. Tuple is not necessarily tied to any specific entity but just a set of columns your query returns.



            There are at least following options how you can handle this:



            • make your repo method return a tuple object

            • make a DTO for selected columns and instantiate it with new operator

            • with new operator make a constructor for your user object that takes selected columns

            The last option would be like creating a constructor:



            public User(String email, String password ) 
            // set the field values



            and query like:



            @Query("SELECT NEW some.package.User(u.email u.password) FROM USER u WHERE email = :email")


            For more details see this question






            share|improve this answer

























            • I cannot use DTOs in the persistence layer. They are all created in Web layer for some reasons. Isn't there any other way(not Tuple)?

              – TheCoder
              Mar 22 at 18:30











            • @TheCoder see the last option I wrote, creatign User with new operator with a specific constructor. I'll edit the answer a bit.

              – pirho
              Mar 22 at 18:36













            0












            0








            0







            As commented your first query does not return User object but a Tuple containing the selected columns. Tuple is not necessarily tied to any specific entity but just a set of columns your query returns.



            There are at least following options how you can handle this:



            • make your repo method return a tuple object

            • make a DTO for selected columns and instantiate it with new operator

            • with new operator make a constructor for your user object that takes selected columns

            The last option would be like creating a constructor:



            public User(String email, String password ) 
            // set the field values



            and query like:



            @Query("SELECT NEW some.package.User(u.email u.password) FROM USER u WHERE email = :email")


            For more details see this question






            share|improve this answer















            As commented your first query does not return User object but a Tuple containing the selected columns. Tuple is not necessarily tied to any specific entity but just a set of columns your query returns.



            There are at least following options how you can handle this:



            • make your repo method return a tuple object

            • make a DTO for selected columns and instantiate it with new operator

            • with new operator make a constructor for your user object that takes selected columns

            The last option would be like creating a constructor:



            public User(String email, String password ) 
            // set the field values



            and query like:



            @Query("SELECT NEW some.package.User(u.email u.password) FROM USER u WHERE email = :email")


            For more details see this question







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 22 at 18:40

























            answered Mar 22 at 18:21









            pirhopirho

            5,164121932




            5,164121932












            • I cannot use DTOs in the persistence layer. They are all created in Web layer for some reasons. Isn't there any other way(not Tuple)?

              – TheCoder
              Mar 22 at 18:30











            • @TheCoder see the last option I wrote, creatign User with new operator with a specific constructor. I'll edit the answer a bit.

              – pirho
              Mar 22 at 18:36

















            • I cannot use DTOs in the persistence layer. They are all created in Web layer for some reasons. Isn't there any other way(not Tuple)?

              – TheCoder
              Mar 22 at 18:30











            • @TheCoder see the last option I wrote, creatign User with new operator with a specific constructor. I'll edit the answer a bit.

              – pirho
              Mar 22 at 18:36
















            I cannot use DTOs in the persistence layer. They are all created in Web layer for some reasons. Isn't there any other way(not Tuple)?

            – TheCoder
            Mar 22 at 18:30





            I cannot use DTOs in the persistence layer. They are all created in Web layer for some reasons. Isn't there any other way(not Tuple)?

            – TheCoder
            Mar 22 at 18:30













            @TheCoder see the last option I wrote, creatign User with new operator with a specific constructor. I'll edit the answer a bit.

            – pirho
            Mar 22 at 18:36





            @TheCoder see the last option I wrote, creatign User with new operator with a specific constructor. I'll edit the answer a bit.

            – pirho
            Mar 22 at 18:36

















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55305508%2fwhy-the-springs-query-annotation-returns-object-type%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

            155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해