JPA,继承和instanceof [英] JPA, inheritance and instanceof

查看:132
本文介绍了JPA,继承和instanceof的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用JPA继承和JOIN策略(JPA2 / Hibernate)。我有一个抽象的一般事件实体,包含共享字段(日期,时间,地点等)及其子项,比如说OutdoorEvent,ClassicalMusicEvent等,每种类型都有特定的字段。我搜索了所有事件,获得了我显示的列表<事件> 。但是每个事件类型的处理都不同,所以我需要弄清楚每个Event对象的事件类型。现在这是问题所在。我想出了两个解决方案。首先, instanceof 关键字:

I use JPA inheritance with JOIN strategy (JPA2/Hibernate). I have an abstract general Event entity with shared fields (date, time, place etc), and its children, let's say OutdoorEvent, ClassicalMusicEvent etc. with specific fields for each type. I make a search over all Event's, getting a List<Event> which I display. The processing for each event type is different though, so I need to figure out the type of event for each Event object. Now here's the problem. I came up with two solutions. First, the instanceof keyword:

if (event instanceof OutdoorEvent) {
   ...
} else if (event instanceof OtherKindOfEvent) {
   ...
} etc.

其次,我向Event实体添加一个临时枚举字段,并在每个子类型的构造函数中设置此字段。然后我可以这样做:

Second, I add a transient enum field to the Event entity and set this field in every children type's constructor. Then I could do:

if (event.getType() == EventType.OutdoorEvent) {
   ...
} else if (event.getType() == EventType.OtherKindOfEvent) {
   ...
} etc.

哪种解决方案更好,或者更多OOP?还有其他解决办法吗?

Which solution is better, or more OOP? Is there any other solution to this?

推荐答案

这是一个很好的问题,因为最佳的OOP解决方案是使用多态。在您的抽象Event类中添加一个抽象的'process'方法,然后在您的子类中实现所需的处理。然后你可以调用 process()并且不关心它是什么类型的子类。

This is a good question because the optimal OOP solution would be to use polymorphism. On your abstract Event class add an abstract 'process' method and then in your subclasses implement the required processing. Then you can just call process() and don't care what the type of subclass it is.

但是,你可能希望保持你的事件(即数据)类与逻辑分离,这样你可能最终会做 instanceof 或类似你的枚举。

However, you probably want to keep your Event (i.e. data) classes decoupled from the logic so somewhere you're probably going to end up doing instanceof or something like your enum.

我没有偏好哪一个,有可能一个比另一个快,我可能会用enum而不是instanceof来获取速度(热衷于听到是否有人有洞察力)。

I have no preference which, it is possible that one is faster than the other and I would probably go with the enum rather than instanceof for speed (keen to hear if anyone has insight on that).

如果你确实选择枚举在你的事件示例中,你应该使用一个开关而不是if..else。

If you do go with the enum In your example with the events, you should use a switch instead of if..else.

这篇关于JPA,继承和instanceof的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆