Piyush Kumar Baliyan
Piyush Kumar Baliyan

Reputation: 404

Combine DAO and Entity in Spring and Hibernate

I was wondering if it is possible to combine DAO and Entity in a single class. e.g.

In rails

If I have table named user then there will be one ActiveRecord User and by using that class I can access access Methods related to DB and user i.e. it has both methods user.name (accessing object properties) and user.save / User.get_all methods (managing DB interactions) in the same class

In Spring/Hibernate Configuration

I have two things: DAO and Entity

Entity: I have User class that is an entity and is mapping Table as POJO, so that I can access methods related to a single user e.g. user.getName()

DAO: I have a DAO in which there are DB interactions e.g. userDAO.save(user) and userDAO.get(id).

Question:

I was wondering if I can create single User class and define User properties and getter/setter inside along with DB interactions so that I can single class as both, i.e. user.getName() (as POJO) and User.get(id)/user.save() (as DAO).

Is this method possible, and why are the complications I might run into, if I start with this approach?

Upvotes: 0

Views: 662

Answers (1)

xyz
xyz

Reputation: 5427

it's called Active Record Pattern . Here is article about topic for JPA . Active Record Pattern . and example https://github.com/ActiveJpa/activejpa

Is this method possible, and why are the complications I might run into, if I start with this approach?

it's :

  1. Cohesion & Coupling

  2. if it's real project , it might become problem to support it

  3. when you have 20 entities it's difficult to decide where to put method into what entity , and also find method that you need as it might be in many places

  4. when you don't use active record pattern you can share entity with web layer , with active record entity can't be Serializable.

  5. code become bigger and bigger

Upvotes: 1

Related Questions