springhibernatejpasingle-table-inheritancediscriminator

Fetch JPA entities by discriminator column


I'm using single table inheritance and trying to fetch entities by their discriminator column but I'm getting errors ... I don't have the discriminator value as a field in the class.

Here's my code :

User Class

@Entity
@Table(name = "MT_User")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "userType", discriminatorType = DiscriminatorType.STRING)
@DiscriminatorValue("CLASSIC")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int uid;

    public String imageFileName;

    private String pseudo;

    private String email;

    private String password;

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "MT_User_Playlist", joinColumns = @JoinColumn(name = "uid"), inverseJoinColumns = @JoinColumn(name = "tlid"))
    private List<Playlist> playlists;

...

}

Admin Class

@Entity
@DiscriminatorValue("ADMIN")
public class Admin extends User implements SuperUser {

//no fields

...

}

User Repository

public interface UserRepository extends CrudRepository<User, Integer> {

    User findByPseudo(String pseudo);

    User findByEmail(String email);

    void deleteByPseudo(String pseudo);

    void deleteByEmail(String email);

    List<User> findByUserType(String userType);

    @Query("from mt_user where user_type=ADMIN")
    List<User> findAdmins();

    @Query("from mt_user where user_type=ADMIN and pseudo=?1")
    User findAdminByPseudo(String pseudo);
}

Here are the errors I get :

Caused by: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: mt_user is not mapped [from mt_user where user_type=ADMIN and pseudo=?1]

Caused by: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: mt_user is not mapped [from mt_user where user_type=ADMIN]

Caused by: java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.List org.ThePouil.projects.mytunes.DAO.UserRepository.findByUserType(java.lang.String)! No property userType found for type User!

Thanks for your help !

:: EDIT ::

This solved my problems :

    @Query("from User")
    List<User> findUsers();

    @Query("from Admin")
    List<User> findAdmins();

    @Query("from Admin where pseudo=?1")
    User findAdminByPseudo(String pseudo);

Solution

  • You should use class name of your @Entity and not tables names in your queries. It should be from Admin or from User.