为什么JPA中有这么多接口?
看看一些 JPA 代码,我发现:
public interface Dao<T extends DomainObject>
public interface EventDao extends Dao<Event> - nothing added to Dao<Event>
public abstract class AbstractDaoJPAImpl<T extends DomainObject> extends JpaDaoSupport implements Dao<T>
public class EventDaoJPAImp extends AbstractDaoJPAImpl<Event> implements EventDao
为什么需要这 2 个接口?为什么不简单地告诉我
public abstract class AbstractDao<T extends DomainObject> extends JpaDaoSupport
public class EventDao extends AbstractDaoJPAImpl<Event>
,我来自 Ruby on Rails 世界,那里的事情看起来更简单。我确信这种 Java 方法有很多优点。我经常能识别出何时应该使用接口,但有时我感觉 Java 开发人员对接口很着迷。
Having a look at some JPA code and I see:
public interface Dao<T extends DomainObject>
public interface EventDao extends Dao<Event> - nothing added to Dao<Event>
public abstract class AbstractDaoJPAImpl<T extends DomainObject> extends JpaDaoSupport implements Dao<T>
public class EventDaoJPAImp extends AbstractDaoJPAImpl<Event> implements EventDao
Why are these 2 interfaces needed? Why not have simply
public abstract class AbstractDao<T extends DomainObject> extends JpaDaoSupport
public class EventDao extends AbstractDaoJPAImpl<Event>
I'm coming from a Ruby on Rails world where things seem simpler. I'm positive this Java approach has many advantages. I can often recognize when an interface should be used, but sometimes I get the feeling Java devs go interface-crazy.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
JPA 不需要这些接口。
JPA 中唯一需要的是实体定义,包括映射到数据库的注释。就是这样。管理数据库连接和实体存储的 EntityManager 已经由 JPA 编写,您不需要所有这些接口和类。
它们可能是由开发人员编写的,他们认为这会分离数据库层(以及 JPA 为您提供的 EntityManager)和应用程序的任何其他层。
如果这是好事还是坏事那就是另一个话题了……
None of these interface is required by JPA.
The only thing you need to have in JPA is your entity definition, including annotations to map to the database. That's it. The EntityManager that manages the database connection and storage of your entities is already written by JPA and you don't need all those interfaces and classes.
They were probably written by a developer that thought it would dissociate the database layer (and the EntityManager given to you by JPA) and any other layer of the application.
If that's a good or bad thing is another topic...
使用接口可以定义契约。该契约在具体的 EventDao 类中实现。
使用此类 DAO 的业务服务通常会使用 EventDao 接口作为注入依赖项。这有几个好处:
声明
Using an interface allows defining the contract. This contract is implemented in the concrete EventDao class.
A business service using such a DAO will typically use the EventDao interface as an injected dependency. This has several benefits: