6

In spring jpa doc, the example shows a way to sort by a sql function like Length(field).

public interface UserRepository extends JpaRepository<User, Long> {

  @Query("select u from User u where u.lastname like ?1%")
  List<User> findByAndSort(String lastname, Sort sort);

  @Query("select u.id, LENGTH(u.firstname) as fn_len from User u where u.lastname like ?1%")
  List<Object[]> findByAsArrayAndSort(String lastname, Sort sort);
}

repo.findByAndSort("targaryen", JpaSort.unsafe("LENGTH(firstname)")); 

So I try to sort a json field in postgres, the code is like

@Query("select u from User u where u.loginName like ?1%")
List<User> findByAndSort(String loginName, Sort sort);

repo.findAllAndSort("jack", JpaSort.unsafe("extra ->> 'info'"));

extra is the name of the field in postgres and it is a jsonb type.

Unluckily, it returns error :

org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: > near line 1, column 88 [select u from com.xx.user.model.User u where u.loginName like ?1 order by u.extra ->> 'info' asc]

it seems that error happens in process of hibernate.

following sql works, so I want to generate it through jpa.

SELECT * from tbl_user order by extra ->> 'info' desc;
5
  • What does "extra ->> 'info'" means? Commented Oct 22, 2019 at 5:10
  • 1
    that is how postgresql gets value with key from jsonb type. for example: "extra" is jsonb type and the value is {"info": "jsoncontext"}. "extra ->> 'info'" can return "jsoncontext". Commented Oct 22, 2019 at 5:39
  • 1
    Did you get any solution for this problem @Tttttsing Commented Jul 1, 2020 at 7:22
  • 1
    @MuhammadWaqasDilawar you can create a function used to extract value from json. and call the function instead of using ->> Commented Aug 7, 2020 at 8:03
  • 1
    @Tttttsing Would you mind sharing your solution? Commented Aug 7, 2020 at 8:20

1 Answer 1

2

I will put my solution here.

Hibernate just doesn't understand that the ->> is json/jsonb operator. We need to put the method name bound to the operator. We could get it in PSQL by the request:

select * from pg_operator where oprname = '->>'

For my PSQL 9.4, it shows that the method name is the json_array_element_text in the oprcode column.

So I just can replace it with the following:

JpaSort.unsafe("json_array_element_text(extra, 'info')")

It does work for me.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.