如何制作通用的jpa存储库?我应该这样做吗?为什么?

2024-04-25

我是堆栈溢出的新手,并且正在使用 hibernate 和 mysql 处理 spring jpa 数据。我为每个实体类创建了一个 JpaRepository。但现在我觉得我应该对所有实体使用一个存储库,因为我所有的存储库都有通用的 CRUD 操作方法。

  1. 节省()

  2. 更新()

  3. delete()

  4. 找一个()

  5. 找到所有()

除了上述方法之外,我的应用程序中还有其他自定义方法。

我的目标是实现 GenericRepo ,例如

public interface MyGenericRepo extends JpaRepository<GenericEntity,Integer>
{

}

我的实体将是这样的:

class Place extends GenericEntity
{
    private Event event;
}

class Event extends GenericEntity
{  

}

class Offer extends GenericEntity
{
     private Place place;
}

class User  extends GenericEntity
{
     private Place place;
}

当我打电话时:

    MyGenericRepo myRepo;

    GenericEntity place=new Place();

    myRepo.save(place);

应该可以节省地方。

[http://openjpa.apache.org/builds/1.0.2/apache-openjpa-1.0.2/docs/manual/jpa_overview_mapping_inher.html#jpa_overview_mapping_inher_joined][1]

我已经提到了上面的链接,我发现 Jpa Inheritance with Joined 和 Table-Per-Class 策略与我正在寻找的类似,但这些都有一定的限制。所以请告诉我应该尝试实现这个通用的东西。如果如果我得到任何演示代码,我将非常感激......

Thanks..

如何制作通用的jpa存储库?我应该这样做吗?为什么?


如果您想创建自己的存储库(而不是为您做一些工作的 spring data),您的示例还不错,我在一个应用程序中使用了类似的策略。

这里有一些改进通用方法的想法: 我已在由所有域对象实现的基本域中添加了 ID 信息:

public interface UniqueIdentifyable<T extends Number> {
    T getId();
    void setId(T id);
}

在下一步中,我创建了一个通用 CRUDRepo:

public interface CRUDRepository<ID extends Number, T extends UniqueIdentifyable<ID>>{
   ID insert(T entity);
   void delete(T entity);
   ....
} 

我正在为 CRUDRepo 使用一个抽象类:

public abstract class AbstractCRUDRepo<ID extends Number, T extends UniqueIdentifyable<ID>> implements CRUDRepo<ID, T>, {...}

域存储库 api 现在如下所示:

public interface UserRepo extends CRUDRepo<Integer, User > {
   User mySpecificQuery(..);
} 

最后你可以通过以下方式实现你的存储库:

public class UserRepoImpl extends AbstractCRUDRepo<Integer, User > implements UserRepo {
   public User mySpecificQuery(..){..}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何制作通用的jpa存储库?我应该这样做吗?为什么? 的相关文章

随机推荐