单一 DAO 和通用 CRUD 方法(JPA/Hibernate + Spring)

发布于 2024-09-26 14:28:35 字数 284 浏览 3 评论 0原文

Following my previous question, DAO and Service layers (JPA/Hibernate + Spring), I decided to use just a single DAO for my data layer (at least at the beginning) in an application using JPA/Hibernate, Spring and Wicket. The use of generic CRUD methods was proposed, but I'm not very sure how to implement this using JPA. Could you please give me an example or share a link regarding this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

哥,最终变帅啦 2024-10-03 14:28:35

这是一个示例接口:

public interface GenericDao<T, PK extends Serializable> {
    T create(T t);
    T read(PK id);
    T update(T t);
    void delete(T t);
}

和一个实现:

public class GenericDaoJpaImpl<T, PK extends Serializable> 
    implements GenericDao<T, PK> {

    protected Class<T> entityClass;

    @PersistenceContext
    protected EntityManager entityManager;

    public GenericDaoJpaImpl() {
        ParameterizedType genericSuperclass = (ParameterizedType) getClass()
             .getGenericSuperclass();
        this.entityClass = (Class<T>) genericSuperclass
             .getActualTypeArguments()[0];
    }

    @Override
    public T create(T t) {
        this.entityManager.persist(t);
        return t;
    }

    @Override
    public T read(PK id) {
        return this.entityManager.find(entityClass, id);
    }

    @Override
    public T update(T t) {
        return this.entityManager.merge(t);
    }

    @Override
    public void delete(T t) {
        t = this.entityManager.merge(t);
        this.entityManager.remove(t);
    }
}

Here is an example interface:

public interface GenericDao<T, PK extends Serializable> {
    T create(T t);
    T read(PK id);
    T update(T t);
    void delete(T t);
}

And an implementation:

public class GenericDaoJpaImpl<T, PK extends Serializable> 
    implements GenericDao<T, PK> {

    protected Class<T> entityClass;

    @PersistenceContext
    protected EntityManager entityManager;

    public GenericDaoJpaImpl() {
        ParameterizedType genericSuperclass = (ParameterizedType) getClass()
             .getGenericSuperclass();
        this.entityClass = (Class<T>) genericSuperclass
             .getActualTypeArguments()[0];
    }

    @Override
    public T create(T t) {
        this.entityManager.persist(t);
        return t;
    }

    @Override
    public T read(PK id) {
        return this.entityManager.find(entityClass, id);
    }

    @Override
    public T update(T t) {
        return this.entityManager.merge(t);
    }

    @Override
    public void delete(T t) {
        t = this.entityManager.merge(t);
        this.entityManager.remove(t);
    }
}
淡写薰衣草的香 2024-10-03 14:28:35

根据文章 不要重复 DAO,我们使用了这种技术多年。当我们意识到自己犯了一个大错误之后,我们总是在与我们的模式问题作斗争。

通过使用 Hibernate 或 JPA 等 ORM 工具,您将不必单独考虑 DAO 和服务层。您可以在服务类中使用 EntityManager,因为您了解事务的生命周期以及实体类的逻辑。

如果您调用 myDao.saveEntity 而不是简单地调用 entityManager.saveEntity,您会节省一分钟吗?不会。您将拥有一个不必要的 dao 类,它不执行任何其他操作,只是作为 EntityManager 的包装器。不要害怕在 EntityManager(或 hibernate 中的会话)的帮助下在服务类中编写选择。

还有一点需要注意:您应该定义服务层的边界,并且不要让程序员返回或等待实体类。 UI 或 WS 层程序员根本不应该只了解 DTO-s 的实体类。实体对象具有大多数程序员不知道的生命周期。如果您将实体对象存储在会话数据中并尝试在几秒钟或几小时后将其更新回数据库,那么您将遇到非常严重的问题。好吧,您可能不会这样做,但知道服务层的参数类型和返回类型的 UI 程序员只会节省一些代码行。

Based on the article Don't repeat the DAO we used this kind of technique for many years. We always struggled with problems with our patterns after we realized that we made a big mistake.

By using an ORM tool such as Hibernate or JPA you will not have to think DAO and Service layer separately. You can use EntityManager from your service classes as you know the lifecycle of transactions and the logic of your entity classes there.

Do you save any minute if you call myDao.saveEntity instead of simply entityManager.saveEntity? No. You will have an unnecessary dao class that does nothing else but will be a wrapper around EntityManager. Do not afraid to write selects in your service classes with the help of EntityManager (or session in hibernate).

One more note: You should define the borders of your service layer and do not let programmers to return or wait for Entity classes. The UI or WS layer programmers should not know at all about entity classes only about DTO-s. Entity objects have lifecycles that most of the programmers do not know about. You will have really serious issues if you store an entity object in a session data and try to update it back to the database seconds or hours later. Well you may would not do it but a programmer of the UI who knows the parameter types and return types of your service layer only would do to save some lines of code.

软糖 2024-10-03 14:28:35

我一直在寻找同样的东西。我发现似乎正是这样 - SpringSource 提供的 Spring-Data JPA 项目。这是来自 Hades 的代码移植,现在(2011 年初)已被 Spring 和更好地集成。
它允许您使用静态创建的单个 dao (SimpleJpaRepository),或扩展 JpaRepository 基类以使用现成的 CRUD+ 方法创建任何对象特定的 dao。还允许像 grails 这样的查询,只需在接口中使用参数名称作为方法的名称(无需实现!)即 findByLastname(String lastName);
看起来非常有前途——成为 Spring 项目的一部分也肯定会确保它有一些未来。
我现在已经开始在我即将进行的项目中实现这一点。

I was looking for this same thing. I found what appears to be exactly that- the Spring-Data JPA project provided by SpringSource. This is a code port from Hades and has now (Early 2011) been swallowed by Spring and better integrated.
It allows you to use a single dao (SimpleJpaRepository) with a static create, or extend the base JpaRepository class to create any object specific dao with ready made CRUD+ methods. Also allows grails like queries just by using params names as the name of the method- in the interface (no implementation required!) i.e. findByLastname(String lastName);
Looks very promising- being part of Spring projects will certainly ensure some future for it too.
I have begun implementing this in my upcoming project now.

腹黑女流氓 2024-10-03 14:28:35

如果您正在寻找第三方实施,您可以检查
http://www.altuure.com/projects/yagdao/ 。它是一个基于注释的通用 DAO 框架,支持 JPA 和 hibernate

if you are looking for a third party implementation , you can check
http://www.altuure.com/projects/yagdao/ . it is a nnotation based generic DAO framework which supports JPA and hibernate

怀中猫帐中妖 2024-10-03 14:28:35

您还可以查看 http://codeblock.engio.net /data-persistence-and-the-dao-pattern/

相关代码可以在github上找到https: //github.com/bennidi/daoism

它与 Spring 集成以及 Hibernate 和 EclipseLink 的配置示例

You may also have a look at http://codeblock.engio.net/data-persistence-and-the-dao-pattern/

The related code can be found on github https://github.com/bennidi/daoism

It has integration with Spring and configuration examples for Hibernate and EclipseLink

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文