开发者

Typed generic DAO and Entity

开发者 https://www.devze.com 2023-04-10 05:42 出处:网络
currently I\'m trying to implement a typed generic DAO. Ido not even get to compile anything, since NetBeans complains about UserDAOHibernate

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 UserDAOHiberna开发者_运维技巧te 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> {
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号