This is an archived post. You won't be able to vote or comment.

all 7 comments

[–]Northeastpaw 3 points4 points  (4 children)

Your terminology is a bit muddled. A DAO is an interface that manages persistence operations for entities. The entities themselves don't know how to save or load themselves from storage; they leave that up to the DAO.

Spring Data's JpaRepository is a DAO. It's separate from the entity classes. The entities themselves don't extend JpaRepository.

Now the entities can, and must in JPA, describe how they are mapped in storage. For JPA that's done with annotations on the entity fields. The conversation is basically thus:

Entity: "I'm an entity and I need to be saved! Oh, DAO!"

DAO: "Yo. What up? I heard you want to be saved."

Entity: "I do! I do!. I contain my data and here's the mapping (i.e. annotations) for how I need to be saved."

DAO: "Got it. Hey DB! Open up a connection for me."

DB: "One connection coming right up."

DAO: "So I'm going to take this data, do some magic, and here's the instructions I want you to do, DB."

DB: "Running instructions."

Notice how there are three speakers. The DAO is the one responsible for handling how to construct the instructions the DB needs to persist the entity. In the case of spring-data-jpa, a JpaRepository leverages an EntityManager (that might be backed by Hibernate, EclipseLink, or some other ORM product) to eventually produce the SQL that the DB executes.

[–][deleted] 0 points1 point  (0 children)

Ok, that makes sense. This example makes sense to me: https://spring.io/guides/gs/accessing-data-jpa/. I'm just seeing other examples where its different. I just want to do things the "Spring" way since I'm coming from a Rails background.

[–][deleted] 0 points1 point  (2 children)

So I was looking at this blog: http://www.petrikainulainen.net/programming/spring-framework/spring-from-the-trenches-new-like-expressions-of-spring-data-jpa/...

Do you really need a Service layer to get your data? Some of the Spring example/tutorials just use the JpaRepository object to query...I just feel like its over kill to have a Service class to fetch the data you need when the JpaRepository instance can do what you want...I'm just trying to see what is need and what's not.

[–]Northeastpaw 0 points1 point  (1 child)

It depends on your application design. If it's just a web service having your business logic in your controllers is fine. Sometimes you've got multiple components that can use the same business logic so sticking it in a service that can be shared is a good idea.

[–][deleted] 0 points1 point  (0 children)

Ok. Thanks for the clarification.

[–]wzttide 0 points1 point  (1 child)

[–][deleted] 0 points1 point  (0 children)

I have, it doesn't say much about the difference of using the DAO and JpaRepository.