不能使用hibernate给combobox赋值。

问题描述 投票:0回答:1

我正在重写我的java应用程序,以达到学习的目的,并且因为我也优化了我的db。我遇到了一些奇怪的事情。我在当前项目中使用的代码和我之前的项目中的很多情况完全一样。好吧,这是我的代码和错误。我将发布任何我觉得它的相关。请帮助我,我卡在5个小时以上。

这里是查询。

    @Override
    public List<UserEntity> readTest() {
        session = sessionFactory.openSession();
        Query query;
        query = session.createQuery("SELECT ue.userId FROM UserEntity ue JOIN UserIsWorkerEntity uwe ON ue.userId = uwe.workerId JOIN WorkerHasRolesEntity wre ON uwe.workerId = wre.workerId JOIN RoleEntity re ON wre.roleId = re.roleId WHERE re.roleId = 'ISORol101'");
        List<UserEntity> tableList;
        tableList = query.list();
        session.close();

        return tableList;
    }

这是我的实体类。

@Entity
@Table(name = "user", schema = "walker", catalog = "")
public class UserEntity {
    private String userId;
    private String name;
    private String surname;
    private Date birthday;
    private UserIsShopkeeperEntity userIsShopkeeperByUserId;
    private UserIsWorkerEntity userIsWorkerByUserId;

    @Id
    @Column(name = "UserID", nullable = false, length = 20)
    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    @Basic
    @Column(name = "Name", nullable = true, length = 35)
    public String getName() {
        return name;
    }
}

Here is some code from the controller (of the fxml)

@FXML
private ComboBox<UserEntity> cbSaleman;

        cbSaleman.getItems().clear();
        List<UserEntity> userEntityList = userIM.readTest();
        for (UserEntity userEntity : userEntityList) {
            userList.add(userEntity);
        }
        cbSaleman.getItems().addAll(userList);

错误如下:

Caused by: java.lang.ClassCastException: class java.lang.String cannot be cast to class Entities.UserEntity (java.lang.String is in module java.base of loader 'bootstrap'; Entities.UserEntity is in unnamed module of loader 'app')

并指向行中。

        for (UserEntity userEntity : userEntityList) {

请帮助我。先谢谢你!我真的很绝望......。我在做圈圈。

hibernate javafx combobox fxml
1个回答
1
投票

你的JPQLHQL查询

SELECT ue.userId FROM UserEntity ue JOIN UserIsWorkerEntity ...

只选择 userId 字段 UserEntity;该 userId 当然是字符串。Java编译器不能确定你的查询所返回的类型(因为它们是由JPQL字符串定义的),所以在你的 readTest() 方法失败,而 List 返回的内容是由 String的,不是 UserEntity 实例。

之后,当你尝试迭代返回的列表时(userEntityList),你隐含地试图将每个元素降频为一个 UserEntity导致 ClassCastException.

你需要的是你的 Query 归还 UserEntity 实例本身,而不仅仅是它们的id。

SELECT ue FROM UserEntity ue JOIN UserIsWorkerEntity ...
© www.soinside.com 2019 - 2024. All rights reserved.