【发布时间】:2017-03-12 12:01:11
【问题描述】:
我是来自 PHP/Larvel、Ruby/Rails 和 Python/Django 的 Spring 新手。来自这些框架,我习惯于只看到模型(实体/Dao?),其他一切都由框架/ORM/QueryBuilders 处理,因此我要做的就是声明一个模型并向其中添加任何操作/我需要的关系/方法。
在这些框架中,这就是我所拥有的:
class User extends BaseModel
{
public function devices() { .. } // Relation to Device model
// Any additional functions on user go here these can operate on
// just the User model or pull additional data from DB or other models.
public function assignUserToDevice();
public function getUsersScore();
public function connectUserToService();
}
然而,在这个 Spring 教程之后,我现在有了这个:
模型(实体/道?):仅包含属性,除了 GET/SET 和关系之外没有方法。
@Entity
@Table(name = "users")
class User {
@Id
@GeneratedValue
var id: Long = 0
var username: String = "" //...
}
存储库:
interface UserRepository : CrudRepository<User, Long> {
fun findByUsername(username: String): User
}
用户服务合约:
interface UserServiceContract {
/**
* Attempts to find User associated with the given id.
* @throws ModelNotFoundException if not user has been found associated with the given id.
* @param id given users id.
* @return User associated with the given id.
*/
@Throws(ModelNotFoundException::class)
fun find(id: Long): User
/**
* Returns all existing users.
* @return list of all existing users.
*/
fun findAll(): List<User>
}
还有一个服务:
@Service
class UserService : UserServiceContract {
@Autowired
lateinit var userRepository: UserRepository
/**
* Attempts to find User associated with the given id.
* @throws ModelNotFoundException if not user has been found associated with the given id.
* @param id given users id.
* @return User associated with the given id.
*/
override fun find(id: Long) = userRepository.findOne(id) ?: throw ModelNotFoundException("User not found!")
override fun findAll(): List<User> {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
}
问题:
为什么我需要
UserRepository和UserService + UserServiceContract?根据我在 Spring guides on Repositories 上阅读的内容,您已经获得了默认的CRUD方法save, read, update, delete..,除此之外,您还可以使用查询方法进行findUserBy...或编写带注释的原始查询。所以我有点困惑,为什么不声明UserServiceContract和UserService只是为了实现存储库已经提供的功能?以前我会在所述模型中保留处理/使用模型的方法,但是我从很少的资源中注意到这不是它们在 Spring 中的去处,那么我应该将它们保留在哪里?这就是为什么有
UserService和UserServiceContract的原因吗? 我真的应该将UserRepository仅用于数据库访问,并在UserServiceContract中声明与用户一起工作的方法,例如:public function connectUserToService()吗?
【问题讨论】:
-
您并不严格需要该服务。您可以直接使用 DAO/Repository。如果您想将低级数据库表示转换为严格的内部模型(不可变和断言),该服务可以派上用场。这些模型更适合由更高级别的层处理(因此您不会暴露 ID 等数据库内部结构)。如果您需要这种额外的分层,这取决于您的应用程序有多大。
标签: java spring spring-data kotlin dao