2012-04-10 55 views
1

我需要一些幫助來解決我在Spring中遇到的這個設計問題。我必須說我是Spring和Hibernate,JPA等的新手。如何在Spring中創建一個ABSTRACT持久層?

我們正在創建一個基於Spring的Web應用程序,它分爲不同的Maven模塊。這些模塊是(小箭頭 ' - >' 是指 「引用」):

  • [1]項目(該應用程序的頭; POM)(這裏JPA註釋)
  • [2]核心模型
  • [3]的核心業務邏輯( - >芯模型)
  • [4]的web應用( - >持久性, - >核心業務邏輯)
  • [5]的持久性抽象( - >芯模型)
  • [ 6]持久性impl關係數據庫( - >持久性摘要)
  • [7]持久IMPL xml文件( - >持久抽象)
  • [8]的持久性實現了一套...

通過[5]我們想要創建定義了一些類或抽象的一個抽象的持久層用於保持業務對象的服務(接口?)。

在[6]應該是使用Hibernate/JPA持久化業務對象的實現。就我所瞭解的Maven而言,可以在另一個Maven模塊中使用JPA註釋,在這裏[2]。此外,我們希望在[7]中有一個將業務對象持久化到xml文件或其他源中的實現,以後它可能會發生什麼。

你知道如何從Web應用程序模塊隱藏實際的持久性實現嗎?我必須在[4]和[5]中指定使用這樣的體系結構?

我們的目的是讓Web應用程序模塊只知道抽象持久性模塊,並在那裏有一個配置文件,其中需要使用哪種實際持久性類型或存儲源。

有沒有辦法在[6]中使用Spring Data JPA和[7]中的其他東西?

預先感謝您。

回答

2

好吧,經過一番閱讀和潛入設計模式的世界之後,我決定做以下事情並分享我的經驗(請參閱我的第一篇文章以解決參考文獻)。

對於持久層([5],[6],[7]等),我使用了策略模式,但是如果您想要將它稱爲DAOFactory-Pattern,與此相關的是我使用的GenericDAO-Pattern,這在「Java Persistence with Hibernate」一書中有很好的解釋。

策略模式基本上由一個接口組成,在我的情況下叫做PersistenceStrategy抽象實際的持久性實現。此外,我有一個服務PersistenceService它包裝該持續戰略。

public interface PersistenceStrategy { 
    public void persist(BaseEntity object); 
    ... 
} 

的PersistenceService:

public class PersistenceService { 

    private PersistenceStrategy persistenceStrategy; 

    public void setPersistenceStrategy(PersistenceStrategy strategy) { 
     this.persistenceStrategy = strategy; 
    } 

    public PersistenceStrategy getPersistenceStrategy() { 
     return this.persistenceStrategy; 
    } 
} 

實際持久類[6]和[7](例如PersistenceStrategyHibernate)等實現此接口和我聲明他們作爲一個Spring bean。我還將PersistenceService聲明爲一個bean。實際的PersistenceStrategy被注入PersistenceService。請注意,這個bean定義實際上在[5]和[6]中的實際持久化實現中,而不是在webapp項目[4]中。

<bean id="hibernatePersistenceStrategy" class="org.myProject.persistence.relational.HibernatePersistenceStrategy" /> 

<!-- PersistenceService is instantiated here with the actual persistence strategy implementation --> 
<bean id="persistenceService" class="org.myProject.persistence.PersistenceService"> 
    <property name="persistenceStrategy" ref="hibernatePersistenceStrategy"></property> 
</bean> 

在我的web應用程序maven項目[4]中,我參考了實際的持久性實現,例如, [5]或[6]。

<dependency> 
    <groupId>org.myProject</groupId> 
    <!-- this is where the persistence module is referenced. 
     if you want to change the type of persistence you can do it here. --> 
     <artifactId>persistence-relational</artifactId> 
     <version>0.0.1-SNAPSHOT</version> 
</dependency> 

在我的控制器類中,我可以引用PersistenceService和PersistenceStrategy。

@Controller 
public class NewDatasetController { 

    @Autowired 
    PersistenceStrategy persistenceStrategy; 

    @RequestMapping("/") 
    public String landing() { 

     ... 
    } 
} 

這些模式在我看來都不錯。如果你想添加一些東西到這個帖子,請隨時取消。

+0

我不太清楚PersistenceService的用法 – 2012-04-19 16:29:31

+0

PersistenceService的優點是有一箇中心對象來從中獲取persistenceStrategy對象。但你是對的。我想你也可以將'hibernatePersistenceStrategy'-Bean重命名爲'persistenceStrategy',並@Autowire它在你需要它的地方,並以這種方式保持'抽象'到實際的實現。 – matthaeus 2012-05-17 13:56:10