Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are you supposed to have one repository per table in JPA?

Are you supposed to have one repository per table in JPA? If not, how do you resolve the generics in the repository database?

For example, below is a StoreRepository. It handles CRUD operations on the Store object. If I wanted the repository to save a StoreEvent object as well, how would I go about changing the interface below to accommodate both objects?

@Repository
public interface StoreRepository extends JpaRepository<Store, String> {
    public Store findByGuid(String guid);
}
like image 830
user1099123 Avatar asked Jan 21 '14 17:01

user1099123


People also ask

Do you need a Repository for each entity?

It depends on your logic and how "important" are every entity. For example, if you had the entities User and Address you could have UserRepository and AddressRepository. But only UserService, with methods like addAddress(User user, Address address)...

Can we have multiple Repository in Spring boot?

You can only have one repository per entity... however, you can have multiple entities per table; thus, having multiple repositories per table.

How does Repository work JPA?

JPA repositories are created by extending the JpaRepository library consisting of implementation of different functions, methods, and other related dependent data types to enable persistence in web or desktop applications designed using JAVA.


1 Answers

As repository is a concept derived from Domain Driven Design, thinking about database tables is the wrong approach. By definition you access aggregate roots from a repository. Effectively a repository is simulating a collection of these.

Now what forms an aggregate root? Probably even more interesting: what does not? That's, of course, highly dependent on your domain, but let me give you an example here. An Order containing LineItems usually is modeled as an aggregate root. This is due to the composition nature of the Order. A LineItem would not exist without a surrounding Order.

Usually the persistence access mechanisms should follow the domain principles. Thus, you'd model both Order and LineItem as @Entity classes but only create an OrderRepository, as they form the aggregate root and effectively control the consistency rules within the object graph.

We also strongly recommend not to use the store specific repository base interfaces as they - as the name suggests - expose store specifics (e.g. flush()) to the clients of which they shouldn't be aware, if possible. Read more on that in my answer here.

like image 187
Oliver Drotbohm Avatar answered Oct 14 '22 12:10

Oliver Drotbohm