views:

38

answers:

2

We have the following classes

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE) // optional annotation as this is default
@DiscriminatorColumn(name = "apType", discriminatorType = DiscriminatorType.STRING, length = 255)
@DiscriminatorValue("AP")
public class ApplicationProcess {
}

And this

@Entity
@DiscriminatorValue("APS")
public class ApplicationProcessScheme extends ApplicationProcess {
}

Now I need to know at runtime if the ApplicationProcess is of DiscriminatorValue AP or APS. Since this is automatically handled by jpa, I have no way of getting this value.

We are calling a method that takes an ApplicationProcess as parameter, and I want to avoid using instanceof to check what type it is. Would be cooler if I could do something like

applicationProcess.getApType().equals("AP");
+1  A: 

We are calling a method that takes an ApplicationProcess as parameter, and I want to avoid using instanceof to check what type it is. Would be cooler if I could do something like (...)

I don't think it would be cooler, this seems worse than calling instanceOf to me: if for whatever reason you change the discriminator value, it would break your code.

If you need to check the type, use instanceOf. A trick using the discriminator is not going to make things nicer, it would just make your code less robust.

Pascal Thivent
+1 I totally agree.Perhaps this refactoring my be applicable: http://www.c2.com/cgi/wiki?ReplaceConditionalWithPolymorphism
Ash Kim
But then I would have to do something like this: pseudo code: `if(not applicationProcess instanceof ApplicationProcessScheme)`, because I cannot check against ApplicationProcess since ApplicationProcessScheme would also match thatSo the code would be `if(obj instanceof ApplicationProcessScheme) {//because there is no !instanceof} else { //We have a child!}`
Shervin
@Shervin: Yes, you would have to do that. I'm not saying it's ideal, I'm saying relying on metadata would be worse. Actually, I'd dig @Ash's suggestion.
Pascal Thivent
For those interested in ReplaceConditionalWithPolymorphism here's a better explaination: http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism
Ash Kim
+2  A: 

You can map your discriminator as a read-only property:

public class ApplicationProcess { 

    @Column(name = "apType", insertable = false, updateable = false)
    private String apType;

    ...
}
axtavt
I will try this
Shervin
@Shervin: You can, but it's not a good idea, your logic shouldn't rely on that.
Pascal Thivent
@Pascal: I think I have to. On the xhtml side I have no way in the EL expression to say `instanceof` (I think). So I might need this.
Shervin
@Shervin: I'm sorry to say so but it seems that you have a major flaw in your design, the **view** should NEVER have to rely on a discriminator value (this is true for business code but even more for the view).
Pascal Thivent
I ended up with this, and it works just fine.
Shervin