简体   繁体   中英

Typed generic DAO and Entity

currently I'm trying to implement a typed generic DAO .

I do not even get to compile anything, since NetBeans complains about UserDAOHibernate

interface expected here
type argument User is not within bounds of type-variable ENTITY

I'm afraid there is some obvious mistake in how I use inheritance/interfaces, since I'm rather new to Java.

Here's some stripped down code

public interface GenericEntity<ID extends Serializable> {
    public abstract ID getId();
    public abstract void setId(final ID id);
}

public abstract class LongEntity implements GenericEntity<Long> {
    protected Long id;
    public Long getId();
    public void setId(final Long id);
}

public class User extends LongEntity implements Serializable {
    private String name;
    private String password;
    private Customer customer;
}

public interface GenericDAO<ENTITY extends GenericEntity<ID>, ID extends Serializable> {
    public abstract ENTITY findById(ID id);
    public abstract List<ENTITY> findAll();
    public abstract ENTITY makePersistent(ENTITY entity);
    public abstract void makeTransient(ENTITY entity);
}

public abstract class GenericHibernateDAO<ENTITY extends GenericEntity<ID>, ID extends Serializable>
        implements GenericDAO<ENTITY, ID> {
}

public class UserDAOHibernate implements GenericHibernateDAO<User, LongEntity> {
}

Is it that LongEntity should extend GenericEntity<Long> ? If so, how would I do this with Java's single level or inheritance?

Is this layered approach a bad example to follow? All my entities need an id and this implementation could easily be reused lateron with different id types, so I thought I might use it.

The error comes from here:

public class UserDAOHibernate implements GenericHibernateDAO<User, LongEntity> {
}

You've specified that GenericHibernateDAO 's ID parameterized type is bounded by <ID extends Serializable> .

LongEntity extends GenericEntity , and hence, why you have a type mismatch.

Also, GenericHibernateDAO is an abstract class (and not an interface), so you'll need to extends instead of implements .

The correct solution should be:

public class UserDAOHibernate extends GenericHibernateDAO<User, Long> {
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM