让我们考虑一个简单的用户插入操作。我做这项工作的 Spring 相关类是 UserController
, UserService
, UserServiceImpl
, UserDAO
, UserDAOImpl
.
在 Controller 端我打电话 userService.insert(new User())
并在 userService.insert()
我调用的方法 userDAO.insert(user)
.我认为这种模式存在方法重复。
有没有办法避免方法重复?可能是我的编码有问题。我等你的回复,经验...
预先感谢...
最佳答案
对于我的项目,我使用这些服务和 DAO 层。
我不知道这是否是最佳实践。
这是一个示例创建操作级别:
[View Layer]
* Simple HTML form or AJAX request
|
| User submits create form. Browser sends POST data
| to controller.
|
[User Controller]
* Authentication and authorization. @Security annotations can be for method security.
* Controller tries to bind POST data to UserCreateForm. If can't Validation exception occurs.
* Validates bind data according to validation annotations. @Required ...
|
| (UserCreateForm) is POJO class which has validation annotations.
| It is similar but different from domain objects.
|
[User Controller]
* Logs errors via Logging API (logback, slf4j, log4j ...)
* Copies form values from UserCreateForm to User domain object
* Calls service methods.
* Passes messages and model objects to desired view page.
|
| (User) is POJO class. called domain object, contains ORM annotations if using JPA
| or hibernate. It is similar but different from form/command objects. It can be
| generated automatically by tools (IDE, hibernate tools ...)
|
[UserService & UserServiceImpl]
* Calls multiple DAO methods in one transaction. If an error occurs. rolls back.
* Contains business logic
* Doesn't know the database technology.
|
| (User) domain object.
|
[UserDAO & HibernateUserDAOImpl || JpaUserDAOImpl || OracleJdbcDAOImpl ...]
* DAO layer knows the persistence technology
* Operations are atomic
关于spring - service-dao 模式的最佳实践是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17639731/