DAO 与 JPA 的实施

Implementation of DAO vs JPA

我想知道JPA和Hibernate的区别。我感兴趣地阅读了 @Anthony 发布的非常有趣的问题,但我仍然不明白全貌。

我已经在 Spring MVC 和 Hibernate 中实现了我的应用程序(见下文)。我的 DAO 是使用 HQL 查询构建的服务的实现。

@Service("messagesService")
public class MessagesService
{
    private MessagesDAO messagesDAO;

    @Autowired
    public void setMessagesDAO(MessagesDAO messagesDAO)
    {
        this.messagesDAO = messagesDAO;
    }

    public List<Message> getAllMessages()
    {
        return messagesDAO.getAllMessages();
    }
...
--------
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
@Transactional
@Component("messagesDAO")
public class MessagesDAO
{
    @Autowired
    private SessionFactory sessionFactory;

    public Session session()
    {
        return sessionFactory.getCurrentSession();
    }

    @SuppressWarnings("unchecked")
    public List<Message> getAllMessages()
    {
        Criteria crit = session().createCriteria(Message.class);
        crit.createAlias("usernameSender", "u").add(Restrictions.eq("u.enabled",true));
        return crit.list();
    }
    ...

我真的很喜欢 "JPA is the dance, Hibernate is the dancer." 这个说法,但在我的具体情况下,我不完全明白为什么我的示例不是 JPA。 MessageService 是舞蹈,MessagesDAO 是舞者(实现)。

正如@Kevin 所说:

Think of JPA as the guidelines that must be followed or an interface, while Hibernate's JPA implementation is code that meets the API as defined by the JPA specification and provides the under the hood functionality.

我知道我没有将我的服务定义为接口,但这仍然让我认为我的代码符合 JPA 规范要求。

现在出现了一个问题

我的例子和下面的宠物诊所例子有什么区别

package org.springframework.samples.petclinic.repository;

import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.samples.petclinic.model.BaseEntity;
import org.springframework.samples.petclinic.model.Pet;
import org.springframework.samples.petclinic.model.PetType;


public interface PetRepository {

    List<PetType> findPetTypes() throws DataAccessException;

-------
@Repository
public class JpaPetRepositoryImpl implements PetRepository {

    @PersistenceContext
    private EntityManager em;

    @Override
    @SuppressWarnings("unchecked")
    public List<PetType> findPetTypes() {
        return this.em.createQuery("SELECT ptype FROM PetType ptype ORDER BY ptype.name").getResultList();
    }

我问所有这些问题的原因是因为我在我的应用程序中使用了 MySql 并且我正在考虑在将来更改它。

因此,我正在尝试构建我的实现层以避免以后出现任何问题。

我正在查看 nosql 选项,我发现了 spring 集成层的数据 jpa。然后我开始学习更多关于 JPA 和 DAO 的知识,上面的问题突然出现了

如果我实现了spring data jpa,我可以暂时使用MySql,稍后再将其更改为另一个数据库(Cassandra,MongoDb)吗?

Spring数据JPA和Spring数据Mongodb有什么区别 (第一个是规范,第二个是实现?)

感谢您的帮助

为了保留术语:在你的 DAO 中你不能改变你的舞伴。

为什么?因为您明确引用了 Hibernate。如果有一天你想改变舞者,你将不得不改变你的整个实现。这就是为什么你通常只使用 类 的舞蹈 - JPASpring Data 在你的情况下。