java – DiscriminatorFormula

If I have a table and I need multiple columns as discriminators, my only solution is to use @ discriminatorformula?

I asked because some prototypes gave us results I couldn't explain

Failed prototype: initially, we prototype a 3-deep class hierarchy with a @ discriminatorcolumn on the superclass, and include a second @ discriminatorcolumn on the subclass Of course, we got this warning:

We found that the update was valid, but the insert did not So we abandoned the idea

successful? Prototype: then we tried the following seemingly effective method: omit the second @ discriminatorcolumn on the subclass and only include @ joincolumn on the foreign key (we need it anyway) Perhaps, because the connection is for different types of objects, hibernate / JPA seems to be able to find out which subclass is correct Who can explain?

Should we discard it and just use @ discriminatorformula to get the explicit relationship defined on the 2 discriminator columns?

Solution

Discriminatorformula is a substitute for discriminatorcolumn You use one of the annotation superclasses (mapping the actual table to the default value)

@Entity
@Table(name = "features")
@DiscriminatorColumn
public class Features{
    //valid code
}

Discriminatorforformula allows you to check the contents of database rows and "select" subclasses through discriminator values No other ("dtype") columns were created In the main class, you can annotate superclasses with formulas, such as:

@Entity
@Table(name = "features")
@DiscriminatorFormula(
        "CASE WHEN num_value IS NOT NULL THEN 'NUMERIC' " +
        " WHEN txt_value IS NOT NULL THEN 'TEXT' end"
)
public class Features{
    //valid code
}

In discriminator formula, you only need some pure SQL to do what you need

You can choose one of these two options, and the subclasses are identical in both cases In subclasses, you can specify discriminator values for the sample:

@Entity
@DiscriminatorValue('NUMERIC')
public class NumericFeatures extends Features {

    private Double numValue;

    public Double getNumValue() {
        return numValue;
    }

    public void setNumValue(Double numValue) {
        this.numValue = numValue;
    }

    //valid code
}

In the table named "features", you have two columns "num_value" and "txt_value", which contain the corresponding values With discriminatorcolumn, you can use "numeric" or "text" values in additional dtype columns, as well as "num_value" and "txt_value" columns

If no inheritance policy is specified, the default is "single_type" If it is the policy you selected, you can omit the following comments:

@Inheritance(strategy = InheritanceType.SINGLE_TABLE)

With or without this comment, you will get a table called "features"

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>