简体   繁体   English

在hibernate / jpa实体类中定义save方法是否是一个好习惯?

[英]Is it a good convention to define save method inside hibernate/jpa entity class?

I have a hibernate entity/model class as given below 我有一个休眠的实体/模型类,如下所示

class User{
  private Integer id,
  Private String name,
  private String description

  //getters and setters

   public void Save(this){
  }
}

Is it a good convention to define save method inside this class declaration along with setters and getters? 在此类声明中与setter和getter一起定义save方法是否是一个好习惯? Do we have any benefit of using like this such as avoiding duplicate records? 这样使用是否有好处,例如避免重复记录?

No, that is not a good convention. 不,那不是一个好习惯。 Usually you have a special layer called DAO (Data Access Object) that cares about saving/fetching/deleting... your entities. 通常,您有一个称为DAO(数据访问对象)的特殊层,它关心保存/获取/删除...您的实体。 The Domain Models (ie your entities) represent only data, and there is the DAO layer that plays with them. 域模型(即您的实体)仅表示数据,并且有DAO层与它们一起使用。 With such a powerful specification as JPA you could merge your DAO layer with your Business Logic layer (EJB/Beans/CDI), but that could be the topic for another discussion. 使用JPA这样强大的规范,您可以将DAO层与业务逻辑层(EJB / Beans / CDI)合并,但这可能是另一个讨论的主题。 Of course you could have some validation things in your entity, or eg a method getLoggingString() that is not persisted, but returns a String version of the entity to be logged. 当然,您可以在实体中进行一些验证,例如,未持久化但返回要记录的实体的String版本的方法getLoggingString()。

PS: the method that you wrote makes little sense with that signature: you need either a public User save() method that saves itself or you need a static public User save(User userToSave) . PS:您编写的方法与该签名毫无意义:您需要保存自身的public User save()方法,或者需要static public User save(User userToSave)

Some references: 一些参考:

  1. DAO DAO
  2. Should you have a separate DAO layer (ie not merged with your business layer)? 您是否应该有一个单独的DAO层(即不与您的业务层合并)?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM