Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search on subclass attribute with a JPA CriteriaQuery?

I am trying to write a query to search a subclass attribute that is not in its superclass and return all objects of the superclass. Currently I am getting a NullPointerException when I try and do person.get("specialAttribute").

@Inheritance(strategy = InheritanceType.JOINED)
@Entity
public abstract class Person {
    public String searchableAttribute;
}

@Entity
@Table( name = "normal_person" )
public class NormalPerson extends Person {

}

@Entity
@Table( name = "special_person" )
public class SpecialPerson extends Person {
    @Column(nullable = false, unique = true)
    public String specialAttribute;
}

// Controller method

    Root<Person> person = query.from(Person.class);
    query.where(
            builder.or(
                    builder.like(person.<String>get("specialAttribute"), "foo"),
                    builder.like(person.<String>get("searchableAttribute"), "foo")
            )
    );
like image 617
Ransom Briggs Avatar asked Mar 26 '12 16:03

Ransom Briggs


1 Answers

Solved my own problem following a hint provided here.

Root<Person> person = query.from(Person.class);

Subquery<SpecialPerson> subQuery = query.subquery(SpecialPerson.class);
Root<SpecialPerson> specialPersonRoot = subQuery.from(SpecialPerson.class);

subQuery.select(specialPersonRoot);
subQuery.where(builder.like(specialPersonRoot.<String>get("specialAttribute"), "foo"));

query.where(
        builder.or(
                builder.in(person).value(subQuery)
                builder.like(person.<String>get("searchableAttribute"), "foo")
        )
);
like image 90
Ransom Briggs Avatar answered Nov 15 '22 08:11

Ransom Briggs