how to store PostgreSQL jsonb using SpringBoot + JPA?

后端 未结 4 1717
不知归路
不知归路 2021-02-01 10:23

I\'m working on a migration software that will consume unknown data from REST services.

I already think about use MongoDB but I decide to not use it and use PostgreSQL.<

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-01 10:43

    Tried this but understood nothing!

    To fully work with jsonb in Spring Data JPA (Hibernate) project with Vlad Mihalcea's hibernate-types lib you should just do the following:

    1) Add this lib to your project:

    
        com.vladmihalcea
        hibernate-types-52
        2.2.2
    
    

    2) Then use its types in your entities, for example:

    @Data
    @NoArgsConstructor
    @Entity
    @Table(name = "parents")
    @TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
    public class Parent implements Serializable {
    
        @Id
        @GeneratedValue(strategy = SEQUENCE)
        private Integer id;
    
        @Column(length = 32, nullable = false)
        private String name;
    
        @Type(type = "jsonb")
        @Column(columnDefinition = "jsonb")
        private List children;
    
        @Type(type = "jsonb")
        @Column(columnDefinition = "jsonb")
        private Bio bio;
    
        public Parent(String name, List children, Bio bio) {
            this.name = name;
            this.children = children;
            this.bio = bio;
        }
    }
    
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class Child implements Serializable {
        private String name;
    }
    
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class Bio implements Serializable {
        private String text;
    }

    Then you will be able to use, for example, a simple JpaRepository to work with your objects:

    public interface ParentRepo extends JpaRepository {
    }
    
    parentRepo.save(new Parent(
                         "parent1", 
                         asList(new Child("child1"), new Child("child2")), 
                         new Bio("bio1")
                    )
    );
    
    Parent result = parentRepo.findById(1);
    List children = result.getChildren();
    Bio bio = result.getBio();
    

提交回复
热议问题