开发者

Is there a way to make jackson jsonize only fetched lazily loaded objects

开发者 https://www.devze.com 2023-04-05 01:54 出处:网络
I know this must have been covered on many places. But I can\'t find a place where it is covered in a simple way.

I know this must have been covered on many places. But I can't find a place where it is covered in a simple way.

In the controller when I return the person object Jackson tries to serialize case. I don't need case table to be sent here. I could do person.setCase(null) but I think there must be a better way of doing this. Is there a way to tell Jackson not to serialize case if it hasn't been fetched?

I have a bunch of Pojos with one-to-many relations like these creat开发者_StackOverflowed by hbopojogen

@OneToMany( fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE         }, mappedBy = "person"  )
@org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE})
@Column( nullable = false  )
@JsonManagedReference
public Set<Case> getCase() {
    return this.case;

}

@ManyToOne( cascade = { CascadeType.PERSIST, CascadeType.MERGE }, fetch = FetchType.LAZY )
@org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE})
@JoinColumn(name = "PERSON_ID", nullable = true )
@JsonBackReference
public Person getPerson() {
    return this.person;

}

  public @ResponseBody Person searchPersonByCode(@RequestParam String codeString){

        int code = Integer.parseInt(codeString);
        Patient person = this.personDao.getByCode(code );

        return person;
    }

Thanks,


Have you checked out Jackson Hibernate module? Core jackson can not do much about lib/framework-specific features, but extension modules can -- and this one specifically supports concept of not resolving lazy references.


I won't answer your question directly. Instead I will try to convince you to change the way you think it may/should be done.
Your problem is that you want to prevent case being serialized when it was not fetched explicitly. I am guessing that you are getting LazyInitializationException when Jackson serializes your object. Instead of trying to avoid this problem please try to think is one of below two solutions isn't better:
Solution 1: Make "open session in view". Jackson will be able to serialize "case" always.
Solution 2: Annotate "case" with @JsonIgnore

Whatever you do try to be consistent and don't try to make your application work differently in special occasions. It will introduce nonobviousness into your design and make your application harder to maintain.

Cheers

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号