通过鉴别器列获取 JPA 实体

Fetch JPA entities by discriminator column

我正在使用单个 table 继承并尝试通过它们的鉴别器列获取实体,但我收到错误... class.

中没有作为字段的鉴别器值

这是我的代码:

用户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;

...

}

管理员Class

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

//no fields

...

}

用户存储库

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);
}

这是我得到的错误:

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!

感谢您的帮助!

:: 编辑::

这解决了我的问题:

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

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

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

您应该在查询中使用 class 您 @Entity 的名称,而不是表名称。应该是 from Adminfrom User.