如何在Hibernate中加载grandchild属性并相应地序列化

时间:2015-11-20 09:29:39

标签: hibernate jackson

我是Hibernate的新手。

用户与地址有一对多的关系,与检查点有一对多的关系。延迟加载已启用。

Hibernate Models:

public class user{
    long id;
    String name;
    Set<Address> addresses;
    //Getters and Stters
}

public class Address{
    long id;
    User user;
    String name;
    Set<Checkpoint> checkpoints;
    //Getters and Stters
}

public class Checkpoint{
    long id;
    Address address;
    String name;
    //Getters and Stters
}

要求是有时我需要只加载用户及其地址,有时我也需要加载地址检查点。

结果还需要相应地序列化为json。目前我使用的JsonIgnore不能达到目的。

1 个答案:

答案 0 :(得分:0)

您可以根据需要使用@JsonView注释:

// View definitions:
class Views {
    static class Public { }
    static class ExtendedPublic extends PublicView { }
    static class Internal extends ExtendedPublicView { }
}

public class User{

    @JsonView(Views.Public.class)    
    long id;

    @JsonView(Views.Public.class)
    String name;

    @JsonView(Views.ExtendedPublic.class)
    Set<Address> addresses;
    //Getters and Stters
}

public class Address{
    @JsonView(Views.ExtendedPublic.class)
    long id;

    @JsonView(Views.ExtendedPublic.class)
    User user;

    @JsonView(Views.ExtendedPublic.class)
    String name;

    @JsonView(Views.Internal.class)
    Set<Checkpoint> checkpoints;
    //Getters and Stters
}

public class Checkpoint{
    @JsonView(Views.Internal.class)
    long id;

    @JsonView(Views.Internal.class)
    Address address;

    @JsonView(Views.Internal.class)
    String name;
    //Getters and Stters
}

// prints only Views.Public.class annotated properties
objectMapper.writeValueUsingView(out, userInstance, Views.Public.class);

// prints Views.Public.class + Views.ExtendedPublic.class annotated properties
objectMapper.writeValueUsingView(out, userInstance, Views.ExtendedPublic.class);

// prints Views.Public.class + Views.ExtendedPublic.class + Views.Internal.class annotated properties
objectMapper.writeValueUsingView(out, userInstance, Views.Internal.class);