如何在 Spring Mybatis 中区分 EntityDAO、EntityDAOImpl 和 EntityService?
How to diff EntityDAO, EntityDAOImpl and EntityService in Spring Mybatis?
我看到一些 Spring-MVC 项目有 EntityDAO、EntityDAOImpl 和 EntityService。我不明白他们之间有什么不同。
例如,我有一个 user
实体。
public Class UserEntity {
private int userId;
private String userName;
private String userInfo;
// getter and setter
}
UserDAO:
@Repository
public interface UserDAO {
@Select({"SELECT * FROM user WHERE id=#{id};"})
UserEntity getById(final int id);
}
UserDAOImpl:
@Repository
public class UserDAOImpl implements UserDAO {
@Autowired
private UserDAO userDAO;
@Override
public UserEntity getById(int id) {
return userDAO.getById(id);
}
}
用户服务:
@Service
public class UserService {
@Autowired
private UserDAOImpl UserDAO;
public UserEntity getById(int id) {
return userDAO.getByid(id);
}
}
所以,我觉得用UserDAOImpl就够了,为什么还需要UserService?
服务层是一种软件工程模式,试图将现有的代码依赖解耦,旨在使代码层具有高内聚性,使每个class具有单一的职责。 This answer on SO and this other answer in SE 提供有关 MVCS(模型视图控制器服务)模式的一些详细信息,它也适用于您的问题。
在这种情况下,UserDao
接口将在 UserDaoImpl
中实现,因为通过使用接口构建松散耦合的系统要容易得多(也更好)(一个很好的here).
UserService
class 提供了许多不同的方法来操作 UserEntity
对象。在这种情况下,该服务将利用 DAO 执行任何与数据库相关的操作,但也可用于提供超出 DAO 范围的其他功能 class.
简而言之:DAO 应该只执行与数据库连接有关的操作。您想要对从数据库中检索到的结果执行的任何其他操作将由服务负责。
通常以服务公开方法来分隔这些层,这些方法在由更简单的接口(例如 DAO)提供的实体(或多个实体)之上执行附加操作。例如,如果您需要解析结果或在其上执行任何缩减操作,这不是 DAO 的职责,因此它将分配给服务。
另一本超越我的解释并提供了关于该主题的出色详细信息的好书是 Service layer vs DAO — Why both?,在软件工程堆栈交换上。
我看到一些 Spring-MVC 项目有 EntityDAO、EntityDAOImpl 和 EntityService。我不明白他们之间有什么不同。
例如,我有一个 user
实体。
public Class UserEntity {
private int userId;
private String userName;
private String userInfo;
// getter and setter
}
UserDAO:
@Repository
public interface UserDAO {
@Select({"SELECT * FROM user WHERE id=#{id};"})
UserEntity getById(final int id);
}
UserDAOImpl:
@Repository
public class UserDAOImpl implements UserDAO {
@Autowired
private UserDAO userDAO;
@Override
public UserEntity getById(int id) {
return userDAO.getById(id);
}
}
用户服务:
@Service
public class UserService {
@Autowired
private UserDAOImpl UserDAO;
public UserEntity getById(int id) {
return userDAO.getByid(id);
}
}
所以,我觉得用UserDAOImpl就够了,为什么还需要UserService?
服务层是一种软件工程模式,试图将现有的代码依赖解耦,旨在使代码层具有高内聚性,使每个class具有单一的职责。 This answer on SO and this other answer in SE 提供有关 MVCS(模型视图控制器服务)模式的一些详细信息,它也适用于您的问题。
在这种情况下,UserDao
接口将在 UserDaoImpl
中实现,因为通过使用接口构建松散耦合的系统要容易得多(也更好)(一个很好的here).
UserService
class 提供了许多不同的方法来操作 UserEntity
对象。在这种情况下,该服务将利用 DAO 执行任何与数据库相关的操作,但也可用于提供超出 DAO 范围的其他功能 class.
简而言之:DAO 应该只执行与数据库连接有关的操作。您想要对从数据库中检索到的结果执行的任何其他操作将由服务负责。
通常以服务公开方法来分隔这些层,这些方法在由更简单的接口(例如 DAO)提供的实体(或多个实体)之上执行附加操作。例如,如果您需要解析结果或在其上执行任何缩减操作,这不是 DAO 的职责,因此它将分配给服务。
另一本超越我的解释并提供了关于该主题的出色详细信息的好书是 Service layer vs DAO — Why both?,在软件工程堆栈交换上。