DAO与JPA的实施

时间:2015-07-30 16:51:02

标签: spring hibernate jpa orm spring-orm

我想知道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是舞蹈,Hibernate是舞者”的说法。但在我的具体情况下,我不完全明白为什么我的例子不是JPA。 MessageService是舞蹈和MessagesDAO的舞者(实现)。

正如@Kevin所说:

  

将JPA视为必须遵循的准则或界面,   而Hibernate的JPA实现是满足API的代码   由JPA规范定义并提供引擎盖   功能。

我知道我没有将我的服务定义为接口,但这仍然让我认为我的代码符合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数据jpa,我现在可以使用MySql并稍后将其更改为另一个数据库(Cassandra,MongoDb)吗?

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

感谢您的帮助

1 个答案:

答案 0 :(得分:2)

保留术语:在你的DAO中,你无法改变你的舞伴。

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