Spring JPA with native query and data projection mapping the wrong columns into the projected interface

前端 未结 3 2016
夕颜
夕颜 2021-02-13 16:16

I\'ve got a bit of a bizarre problem that I can\'t figure out why it\'s happening. I\'m sure I did something wrong, because this is my first time using a data projection and I\'

相关标签:
3条回答
  • 2021-02-13 16:57

    I had the same problem and i solved by odering the query columns alphabetically.

    In you case:

    public interface OrderTrackingRepository extends JpaRepository<Account, UUID> {
      @Query( nativeQuery = true,
              value = "SELECT a.accountnumber, o.date_of_order, t.tracking_id " +
                      "FROM account as a " +
                      "INNER JOIN orders as o USING (account_id) " +
                      "INNER JOIN tracking as t USING (tracking_id) " +
                      "WHERE a.accountnumber = :acctnum")
      <T> Collection<T> findOrderInfoForAccount(@Param("acctnum") acctNumber, Class<T> type);
    }
    

    So you will get:

    getAccountNumber() -> accountnumber getDateOfOrder() -> date_of_order getTrackingId() -> tracking_id

    0 讨论(0)
  • 2021-02-13 16:58

    Not sure if this is the correct solution because it only fits 80% of the description. But it is too long for a comment. So here we go.

    I think you misunderstood @osamayaccoub or the documentation. Your property name is fine. But the columns in your select should match the java convention.

    So the first attempt to fix that would be

    value = "SELECT o.date_of_order as dateOfOrder, a.accountnumber as accountNumber, t.tracking_id as trackingId "
    

    Note: This might actually work, but might break later, so read on, even if it does work

    But Postgres converts everything that isn't double quoted into lower case (Oracle and MySql do similar stuff though details vary, don't know about other DBs yet). So you really should use:

    value = "SELECT o.date_of_order as \"dateOfOrder\", a.accountnumber as \"accountNumber\", t.tracking_id as \"trackingId\" "
    

    This probably doesn't work, because the Hibernate version you are using has a bug in that it converted everything to lower case.

    So you should upgrade to the latest Hibernate version 5.3.13 which has the issue fixed.

    This bug fix interestingly might break the version without the double quotes. But it should work again with this PR for this Spring Data JPA issue.

    The part I don't understand is, why stuff gets assigned using the column order.

    0 讨论(0)
  • 2021-02-13 17:04

    Hibernate sorts the query in alphabetic order so you have to change the select to: "SELECT a.accountnumber, o.date_of_order, t.tracking_id ..." and the interface's getters should follow the same alphabetic order.

    0 讨论(0)
提交回复
热议问题