This is a follow up to: my previous question
My following line of code does not work:
IAccount account = (AccountModel) new AccountRepository().getByEmail(emailaddress);
The returntype of ...getByEmail(...)
is Model<Account>
, and AccountModel
extends Model<Account>
.
Yet I get a java.lang.ClassCastException: models.Model cannot be cast to models.AccountModel
when I test it. I know this is because every AccountModel
is a Model<Account>
, but not the other way around.
Is there any way how I can make sure that I can fix this (or work around it).
public class AccountRepository extends Repository<Account> {
public AccountRepository() {
super(Account.class);
}
public Model<Account> getByEmail(String emailAddress) {
return this.getCustomHqlSingle("FROM Account a WHERE a.emailAddress = '" + emailAddress + "'");
}
}
public abstract class Repository<T> implements Serializable {
protected final Model<T> getCustomHqlSingle(String hql) {
List<Model<T>> t = this.getCustomHqlList(hql);
if (t != null && !t.isEmpty()) {
return t.get(0);
} else {
return null;
}
}
protected final List<Model<T>> getCustomHqlList(String hql) {
Session session = SESSION_FACTORY.openSession();
try {
session.beginTransaction();
List<T> entities = session.createQuery(hql).getResultList();
List<Model<T>> result = new ArrayList<>();
for (T t : entities) {
result.add(this.getByEntity(t));
}
return result;
} finally {
session.close();
}
}
To the person that marked this question as duplicate, let me rephrase the following sentence from my question:
I know this is because every
AccountModel
is aModel<Account>
, but not the other way around.
To
I know this is because every
Dog
is anAnimal
, but not the other way around.