I'm writing a generic Dao interface and I have encountered some problems.
I have the following generic Entity interface
public interface Entity<T> {
T getId();
//more code
}
So the generic parameter is supposed to represent the id of the entity. And now I want to write a generic Dao initerface like this
public interface Dao<T extends Entity<E>> {
//more code
T find(E id);
}
To be able to call
T find(E id)
Instead of having to call
T find(Object id)
which isn't typesafe.
Unfortunately the compiler doesn't seem to be able to resolve the E in
Dao<T extends Entity<E>>
Do any of you know if there is a workaround to this problem, or is it just impossible to do in Java?
You have to pass the primary key as parameter too:
public interface Dao<K, T extends Entity<K>>
The pk usually is serializable, so you can improve the above signature:
public interface Dao<K extends Serializable, T extends Entity<K>>
And:
public interface Entity<K extends Serializable>
Then:
public class UserDao implements Dao<Integer, User> {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With