How to store JSON file as a JSON datatype in mysql using Hibernate / Spring boot?

后端 未结 1 485
我寻月下人不归
我寻月下人不归 2020-12-21 15:24

I\'ve tried several ways of storing a json file in a database but it ends up creating different columns for each entry.

I want to store it as a \"json\" type in a si

相关标签:
1条回答
  • 2020-12-21 16:23

    Your code reads json into list of User objects and persists to database. You need to write some custom logic to save it as json. There are multiple ways to do it.

    You can do something like

    1) Add another variable in User class say private String jsonData

    2) In @PrePersist method, write serialization logic

    3) Mark other attributes with @JsonInclude() - to include in Jackson @Transient - to ignore in the persistence in separate column. You might not want to add these annotations to id attribute as each json object will be stored against a specific id in database.

    So, new attribute would be something like

    @NonNull
    @Column(columnDefinition = "JSON") // Only if Database has JSON type else this line can be removed
    private String jsonData;
    

    PrePersist:

    @PrePersist
    public void prePersist() {
        try {
            this.setJsonData(new ObjectMapper().writeValueAsString(this));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
    

    EDIT: You might face issue with @Transient attributes being null in the @PrePersist method. In that case you can use a setter method. But you have to call this setter everytime any attribute is changed before the save call.

    public void setJsonData(String jsonData) {
        // Method parameter jsonData is simply ignored
        try {
            this.jsonData = new ObjectMapper().writeValueAsString(this);
        } catch (JsonProcessingException e) {
            log.error(e.getMessage());
        }
    }
    
    0 讨论(0)
提交回复
热议问题