2012-12-03 31 views
1

我正在使用Struts2,Hibernate和Spring來管理sessionFactory的生命週期的中型應用程序。我的問題是,我應該創建一個能夠爲我的整個應用程序提供所有服務的大服務類嗎?或者應該爲每個模型創建一個服務類?構建休眠的服務層

比方說,我有這樣的一個大的服務類

@Transactional 
public class Services { 
    // So Spring can inject the session factory 
    SessionFactory sessionFactory; 
    public void setSessionFactory(SessionFactory value) { 
     sessionFactory = value; 
    } 

    // Shortcut for sessionFactory.getCurrentSession() 
    public Session sess() { 
     return sessionFactory.getCurrentSession(); 
    } 

    public Event getEventById(long id) { 
     return (Event) sess().load(Event.class, id); 
    } 

    public Person getPersonById(long id) { 
     return (Person) sess().load(Person.class, id); 
    } 

    public void deleteEventById(long id) { 
     sess().delete(getEventById(id)); 
    } 

    public void deletePersonById(long id) { 
     sess().delete(getPersonById(id)); 
    } 

    public void createEvent(String name) { 
     Event theEvent = new Event(); 
     theEvent.setName(name); 
     sess().save(theEvent); 
    } 

    public void createPerson(String name) { 
     Person p = new Person(); 
     p.setName(name); 
     sess().save(p); 
    } 

    @SuppressWarnings("unchecked") 
    public List<Event> getEvents() { 
     return sess().createQuery("from Event").list(); 
    } 

    @SuppressWarnings("unchecked") 
    public List<Person> getPeople() { 
     return sess().createQuery("from Person").list(); 
    } 

    public void removePersonFromEvent(int personId, int eventId) { 
     getEventById(eventId).getPeople().remove(getPersonById(personId)); 
    } 

    public void addPersonToEvent(int personId, int eventId) { 
     getEventById(eventId).getPeople().add(getPersonById(personId)); 
    } 

     .....Some more services methods here 
} 

什麼是我們的最佳方法呢?整個應用程序的一個大服務類?或每個型號有不同的服務等級?

+1

我的建議是遵循REST,具有一個'PersonService'和'EventService'以及一組最小的CRUD方法。 – Asaf

+0

一個具體的例子會很好。 – KyelJmD

+0

查看'UserService' [here](http://krams915.blogspot.co.il/2012/01/spring-mvc-31-implement-crud-with_7897.html),例如 – Asaf

回答

3

Martin Fowler's book on Enterprise Patterns在構建服務層方面有一些很好的指導。在extract of the book你可以找到這樣的:

對於一個足夠小的應用程序,可能就足夠了,但有一個 抽象,應用程序本身的名字命名。以我的經驗 較大的應用程序被劃分成幾個「子系統」,其中每個 包括一個完整的垂直切片,通過堆棧的 體系結構層。

所以在服務層模式中沒有石頭定律。在我看來,你並不屬於小應用程序(你的Services類有太多的方法),所以一切都減少到識別應用程序的子系統。本書還推薦與市長抽象相關的服務層(可能爲EventServicePeopleService)或應用行爲(如EventManagementService);最終由您來決定您項目的最佳代碼組織。

0

爲完整的應用程序創建一個大服務不會有這種意義,它將開始創建一個readability以及maintenance問題隨着您的應用程序的增長。

它總是更好地遵循@Asag建議模塊化approach.As:

不同的模塊中創建不同的服務,並確定相關服務there.This將幫助您區分功能,以及將幫助任何人你的方法在未來誰將在同一個應用程序上工作。