如何持久化每一个新实体?
我希望每个实例化实体都对应于数据库中的一个元组(& co)。在我看到的示例中,人们总是实例化实体(通过构造函数),然后调用该实体的持久化。我发现这很容易出错,并且想知道是否不可能让每个实例化实体自动管理/保留/反映到数据库(至少是有意这样做)。
这似乎也阻止我持久保存实例变量实体。即我有一个实体在其构造函数中实例化另一个实体(与其关联的实体)。
I expect every instantiated entity to correspond to a tuple (& co) in the database. In the examples I see around, one always instantiates the entity (via a constructor) and then calls persist with that entity. I find this error-prone, and was wondering if it wasn't possible to have every instantiated entity automatically managed/persisted/reflected to the database (at least intended to).
This also seems to prevent me from persisting instance variable entities. I.e. I've an entity which instantiates another (entities it has an association with) in its constructor.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这只是一种练习。该模型不应该知道任何 DAO/持久性逻辑。如果是,那么它是紧密耦合的,并且不能重用于其他持久性框架。但是,如果您确定自己长期坚持使用 JPA,那么您可能会考虑这样做。但这通常不是一个好的做法。那么该模型可能无法在其他层中重用。例如,您可能希望为视图层创建一个模拟/虚拟模型对象,让新用户填写注册详细信息,然后仅在提交和验证成功完成后才保留它。
That's just a practice. The model shouldn't be aware of any DAO/persistence logic. If it does, then it is tight coupled and not reuseable for another persistence frameworks. However, if you are sure that you stick to JPA for ages, then you may consider to do so. But this is generally just not a good practice. The model may not be reuseable in another layers then. For example, you may want create a mock/dummy model object for the view layer to let a new user fill in the registration details and then only persist it when submission and validation is done succesfully.