简体   繁体   中英

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? 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. The Domain Models (ie your entities) represent only data, and there is the DAO layer that plays with them. 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. 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.

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) .

Some references:

  1. DAO
  2. Should you have a separate DAO layer (ie not merged with your business layer)?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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