【问题标题】:Hibernate join inheritance wrong type on query result查询结果上的休眠连接继承类型错误
【发布时间】:2017-12-04 21:16:39
【问题描述】:

我是 spring/hibernate 的新手。我编写了一个 web 服务,它应该返回完整的对象,有时还会返回缩减的对象。例如,我有一个从 MemberBase 类继承的 Member 类:

...

**
 * MemberBase
 */

@Entity
@Table(name = "MemberBase")
@Inheritance(strategy = InheritanceType.JOINED)
@SequenceGenerator(name = "idgen", sequenceName = "seq_Member")
public class MemberBase extends BasePojo {

    @Column(name = "alias")
    private String alias = null;
    @Column(name = "firstName")
    private String firstName = null;

    @Column(name = "gender")
    @Enumerated(EnumType.STRING)
    private Gender gender = null;

    @Transient
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "creator")
    @ElementCollection(targetClass=OutingBase.class)
    private Set<OutingBase> outings = null;

...
}

和会员:

...

/**
 * Member
 */
@Entity
@Table(name = "Member")
@SequenceGenerator(name = "idgen", sequenceName = "seq_Member")
public class Member extends MemberBase {


    @Enumerated(EnumType.STRING)
    private MaritalStatus maritalStatus = null;

    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDate")
    private LocalDate birthDate = null;

    private String locationName = null;

    private DateTime lastConnexion = null;

    private String description = null;

    private String videoMoodUrl = null;

    private String mood = null;

    private Boolean canCertify = null;

    private String fid = null;
    ...
}

在我的控制器中,我使用休眠来获取成员库列表:

public ResponseEntity<List<MemberBase>> membersGet() {
        Session session = HibernateUtils.getSessionFactory().openSession();
        session.beginTransaction();
        List<MemberBase> personList = session.createQuery("FROM " + MemberBase.class.getName(), MemberBase.class)
                .getResultList();

        session.close();
        return new ResponseEntity<List<MemberBase>>(personList, HttpStatus.OK);
    }

这是我创建会话工厂的方式:

private static SessionFactory buildSessionFactory() {
        try {
            Configuration configuration = new Configuration().configure();
            configuration.addAnnotatedClass(BasePojo.class);
            configuration.addAnnotatedClass(MemberBase.class);
            configuration.addAnnotatedClass(Member.class);
            configuration.addAnnotatedClass(OutingBase.class);
            configuration.addAnnotatedClass(Outing.class);

            StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
                    .applySettings(configuration.getProperties());
            return configuration.buildSessionFactory(builder.build());
        } catch (Throwable ex) {

            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

我的问题是,当我调用membersGet() 时,我检索到的是List&lt;Member&gt;,而不是List&lt;MemberBase&gt; 的列表。没有崩溃,但是我的序列化 Json 包含的字段太多。我实现了这种继承以避免获取所有Member 的字段。我做错了什么?

【问题讨论】:

    标签: spring hibernate inheritance


    【解决方案1】:

    我建议使用来自 FasterXML Jackson 的 JsonIgnore 注释。

    顾名思义,注释将导致在解析对象时忽略该属性。

    e。 G。

    @JsonIgnore    
    private String locationName = null;
    

    编辑:

    使用JsonView 指定应该为哪个视图显示/解析属性。 e. G。

    public class JsonView {
        public static class Base {
        } 
        public static class Extended extends Base {
        }
    }
    
    @JsonView(JsonView.Extended.class)
    private String locationName = null;
    
    @JsonView(JsonView.Base.class)
    private String alias = null;
    

    当你映射它时,你可以指定你想要的视图。

    ObjectMapper mapper = new ObjectMapper();
    
        String result = mapper
          .writerWithView(JsonView.Extended.class)
          .writeValueAsString(member);
    

    请看这里:http://www.baeldung.com/jackson-json-view-annotation

    【讨论】:

    • 好的,但在某些情况下,我需要获得完整的 Member,所以这不是解决方案 :)
    • 感谢您的编辑,现在我知道 JsonView 并阅读了您提供的链接中的文档。我没有使用映射器,但我的 spring 接口上的注释是这样的:` @JsonView(JsonView.Extended.class) @RequestMapping("/items/internal/{id}") public Item getItemInternal(@PathVariable int id) {返回 ItemManager.getById(id); } `
    • 很高兴能帮到你。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-14
    • 2013-09-15
    • 1970-01-01
    • 1970-01-01
    • 2014-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多