Search code examples
javainheritancespring-data-jpajpql

jpql querying inherited Entity


I have a database with a master and child tables where each child table has the same properties but of a different type (boolean, string, date).

This is the master entity

@Setter
@Getter
@Entity
@Table(name = "FIELDS_MASTER")
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class Master{
    @Id
    @GeneratedValue(generator = "uuid2")
    @GenericGenerator(name = "uuid2", strategy = "uuid2")
    private String id;
    @ManyToOne(cascade = CascadeType.MERGE)
    @JoinColumn(name = "document")
    private Document document;

    public abstract String getTypeName();

    public abstract Object getValue();

    public abstract void setValue(Object value);

}

This are 2 child entitys

@Setter
@Getter
@Entity
@Table(name = "FIELDS_STRING")
@PrimaryKeyJoinColumn(name = "id")
public class StringFieldValue extends FieldValue {
    private String value;

    @Override
    public String getTypeName() {
        return FieldEnum.STRING.name();
    }

    @Override
    public String getValue() {
        return value;
    }

    @Override
    public void setValue(Object value) {
        this.value = value.toString();
    }

}

@Setter
@Getter
@Entity
@Table(name = "FIELDS_BOOLEAN")
@PrimaryKeyJoinColumn(name = "id")
public class BooleanFieldValue extends FieldValue {
    private LocalDate value;

    @Override
    public String getTypeName() {
        return FieldEnum.BOOLEAN.name();
    }

    @Override
    public Boolean getValue() {
        return value;
    }

        @Override
    public void setValue(Object value) {
        this.value = Boolean.valueOf(waarde.toString());
    }

}

Here is my question, how can I make a jpql query that can access the field "value" of the child components. I would like to search in any child component where the value is equal to.

Example: The table FIELDS_BOOLEAN has a record where the value is false and the table FIELDS_STRING has a record with value "false", I want both of them.

This is what I would expect to work but does not:

@Query("SELECT m from FIELDS_MASTER WHERE m.getValue() = :searchTerm")
List<FieldsMaster> findByValue(String searchTerm);

Solution

  • I have found that it is not plausibel, the only solution is to acces the child table directly. Like this:

    @Query("SELECT m from FIELDS_STRING WHERE m.value = :searchTerm")
    List<FieldString> findByValue(String searchTerm);