我正在开发一个中型应用程序,使用 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
}
最好的方法是什么?整个应用程序的一个大服务类?还是每个型号有不同的服务等级?
最佳答案
Martin Fowler's book on Enterprise Patterns有一些关于构建服务层的很好的指南。在 extract of the book你可以找到这个:
For a sufficiently small application, it may suffice to have but one abstraction, named after the application itself. In my experience larger applications are partitioned into several “subsystems,” each of which includes a complete vertical slice through the stack of architecture layers.
所以在服务层模式中没有一成不变的法则。在我看来,你不是小型应用程序的情况(你的 Services
类有太多方法),所以一切都减少到识别应用程序上的子系统。该书还推荐与主要抽象(可能是 EventService
或 PeopleService
)或应用程序行为(如 EventManagementService
)相关联的服务层;最后由您来确定项目的最佳代码组织。
关于java - 使用 Hibernate 构建服务层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13675742/