How do I use spring data jpa to query jsonb column?

后端 未结 5 1981
小蘑菇
小蘑菇 2020-12-29 12:11

I\'m having a problem getting this native query right against a postgres 9.4 instance.

My repository has a method:

 @Query(value = \"SELECT t.* \" +
         


        
5条回答
  •  忘掉有多难
    2020-12-29 12:50

    I suggest not following this way, I prefer to follow generic CRUD way (also working on advanced auto generated DAO methods in way of StrongLoop Loopback does, for Spring Data Rest maven plugin, but it is experimental in the moment only). But with this JSON, now what to do... I am looking for something similar to MongoDB JSON processing in Spring Data via @Document annotation, however this is not yet available. But there are other ways :-)

    In general it is about implementing your JSON user type (UserType interface):

    public class YourJSONBType implements UserType {
    

    Finally you need to enhance your JPA classes with specification of your implemented user type:

    @Entity
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @TypeDef(name = "JsonbType", typeClass = YourJSONBType.class)
    public class Person {
        @Id
        @GeneratedValue
        private Long id;
    
        @Column(columnDefinition = "jsonb")
        @Type(type = "JsonbType")
        private Map info;
    }
    

    look at another related articles here: Mapping PostgreSQL JSON column to Hibernate value type

    The full implementation example is available here:

    • https://github.com/nzhong/spring-data-jpa-postgresql-json
    • https://github.com/mariusneo/postgres-json-jpa

    Similar, but little different example is available here: http://www.wisely.top/2017/06/27/spring-data-jpa-postgresql-jsonb/?d=1

提交回复
热议问题