i am rewriting my java application for learning purposes and because i optimized my db as well. I fell into something weird. I'm using exact the same code i'm using in many situations in the current project as in my previous one. Well, here is my code and the error. I will post anything i feel it's related. Please help me i'm stuck in more that 5 hours :/
Here is the query:
@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;
}
Here is my entity class:
@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);
The error is the following:
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')
and is pointing in the row:
for (UserEntity userEntity : userEntityList) {
Please help. Thank you in advance! I'm really desperate.. I am doing circles.
Your JPQL/HQL query
SELECT ue.userId FROM UserEntity ue JOIN UserIsWorkerEntity ...
selects just the userId
fields from the mathcing UserEntity
; the userId
are of course strings. The Java compiler can't determine the types returned by your query (since they're defined by the JPQL string), so compile-time type checking in your readTest()
method fails, and the List
that's returned is populated by String
s, not UserEntity
instances.
Later, when you try to iterate through the returned list (userEntityList
), you implicitly try to downcast each element to a UserEntity
, causing the ClassCastException
.
What you need instead is for your Query
to return the UserEntity
instances themselves, instead of just their ids:
SELECT ue FROM UserEntity ue JOIN UserIsWorkerEntity ...