我在想我是否真的需要一个服务层。
我正在将 spring + hibernate 用于桌面摇摆应用程序,此时我有 gui/swing 层->服务层->dao 层。我仅将 spring 用于@Transactional 支持和 IOC 注入
最佳实践说我必须编写一个服务来使用我的 daos,并将所有事务管理放在服务中。
但是我经常意识到,服务层只复制 dao 方法,例如:
// a DAO example
@Repository
public class CustomerHibernateDAO extends BaseHibernateDAO implements CustomerDAO {
public List<Customer> findAllCustomerILikeName(String name){
return getSession()
.createCriteria(Customer.class)
.add(Restriction.ilike("name", name))
.list();
}
}
// Customer service to use this dao...
@Service
@Transactional
public class CustomerService {
@Autowired
CustomerDAO customerDAO;
// Why i can't call DAO instead the service?
public List<Customer> getAllCustomersByName(String name){
return customerDAO.findAllCustomerILikeName(name);
}
}
这是服务层的典型用法...... Hibernate 与 db 无关,spring 与技术无关:所以,我真的需要它吗?
管理所有 DAO 的独特服务类怎么样?我认为这可能是一个很好的妥协,或者,是一个不好的做法?
我知道将@Transactional 放在DAO 上是一种不好的方法,但是此时我必须编写服务仅用于将@Transactional 放在上面...
编辑
有关我的应用程序的更多信息。
我的应用程序是一个管理软件,管理用户注册、产品、订单和其他类似的东西。在实践中,它包含许多读取实体->编辑->保存实体或创建->编辑->保存操作,并且由于休眠,这些操作大部分时间由 ONE dao 管理,因为休眠与@manyto。 .. collection 和 cascade.save_update 允许在同一个持久化操作中保存两个或多个实体。
因此,例如,在我可以插入、编辑或创建项目(要出售的产品)的项目 JFrame 中,有:
public ItemFrame(){
// the constructor
itemService=springAppContext.getBeans(ItemService.class);
}
public boolean validateForm(){
// test if the gui is correctly filled by user
}
public boolean save(){
// create an Item entity taking value from swing gui(JTextField etc)
Item item=new Item();
item.setName(nameTextField.getText());
item.setEtc...
// ItemService ' save method is a wrap around itemDao.save(item)...
itemService.save(item);
}
private void saveItemActionPerformed(ActionEvent evt){
// When i press SAVE button
if(validateForm()){
save();
}
}
这是我在大多数情况下所拥有的,所以我认为我陷入了贫血域反模式......
谢谢。