How to do POST on a dependent Entity without a backing Repository - spring

I find mentions in lot of answers to Spring Data Rest design related questions to "Aggregate Root" and "Entity" together with "Value Objects".
And I think Repository equate to Aggregate Root.
CASE 1
My question is around this , say there are 2 Entities - User and UserSettings , represented in database as 2 tables and UserSettings having a foreign key user_id pointing to User.
In this case, i would like to do GET/POST on both User as well as UserSettings. From some posts, i found out that repositories should be at aggregate root level which would mean in this case exposing repository for only User since UserSettings depends on User completely.
Right now, i have 2 repositories with bidirectional relationships , one for each i.e UserRepository and UserSettingsRepostory , both exposed as REST services.
As a result, I do POST on UserSettings and User as
/app/userSettings
/app/users
For, GET I use for UserSettings & User -
/app/users/{id}/userSettings
/app/users/{id}
If I don't expose UserSettingsRepository , what will be equivalent to POST on /app/userSettings, where I am currently doing as below -
Method - POST
Input JSON - {
"user" - "/app/users/{id}",
..
}
CASE 2
Likewise if there are following Entities/Tables - User, UserPost and UserComment - here UserComment has 2 foreign keys as UserPost as well as User.
I suppose here we have 2 aggregate roots and therefore should have 2 repositories as UserRepository and UserPostRepository.
Another way of thinking about is that since all are after all dependent on user and so we can just have 1 repository for UserRepository only.
Here too, contrary to my current state where I have even UserCommentRepository, I am not sure how to do POST on UserComment once remove that.

If you you want to interact with UserSettings individually, they need to become dedicated resources, which means they're not part of the User aggregate anymore. An aggregate makes sure certain assertions are held within itself by making sure, nobody else manipulates the state of parts of it. So if you want do the latter, the aggregate is not an aggregate anymore. Spring Data REST just exposes these concepts on an HTTP level.
To keep User and UserSettings together you basically have two options:
Introduce a dedicated state transition for the user resource by adding a link. Define the supported HTTP verbs and data structure for that resource pointed to.
Use an HTTP PATCH operation on the user resource to manipulate parts of the resource.

Related

Handle model dependencies in Laravel Repository Pattern

I'm discovering the Repository Pattern for my Laravel project but I have to say that I'm a bit lost once a model has several dependencies and the examples on the web are always basic and don't answer the question for more complex use cases.
Let's imagine a user on my app. He can have badges, he has different things on the app that will be slightly modified when he first performs the action (when he first sees the comments, I tell him once the different things he can do, etc), he has several "counters" to record the number of comments he made, the number of friends he invited, without having to count each entry each time.
My database looks like this:
users table:
id
pseudo
name
password
...
badges table:
user_id
badge1_xxxxxx
badge2_xxxxxx
...
I have a very limited number of badges so I decided to create a column for each of them and as soon as a user wins a badge, I get his entry (in OneToOne relationship) and I indicate that the badge in question has been won.
onboarding table:
user_id
seen_comments (boolean)
seen_results (boolean)
...
As you can see, I store each action I'd like the user to do in different columns and as soon as he has done one and I've been able to modify my app accordingly (by showing him an arrow, etc), I put the column in question to true.
user_counters table:
user_id
count_comments
count_invited_friends
...
I don't consider a user to be a user if he doesn't have an entry in each of the tables (I could have done everything in one table but the users table seemed to me to become huge). The only relationship used is OneToOne between the user and the table in question.
Should I do this ?
class UserRepository {
public function register($data) {
// Create the user
$user = User::create($data);
// Create all its dependencies which are required if I want to consider the user as fully registered in my DB
$user->badges()->create();
$user->onboarding()->create();
$user->counter()->create();
// Return the user
return $user;
}
}
Or should I create a Repository for each of these elements and create the entire user in a UserService ?
How far should I separate things and when does it become overkill?
Is there something that I don't understand in concept of Repository ? If so, could you give me some links that you found useful because I feel like I ran out of ideas for search keywords.
Thanks

Spring data JPA save() return less/incorrect child and parent association mapping fields [duplicate]

I'm developing a RESTful webservice with spring-data as its data access layer, backed by JPA/Hibernate.
It is very common to have relationships between domain entities. For example, imagine an entity Product which has a Category entity.
Now, when the client POSTs a Product representation to a JAX-RS method. That method is annotated with #Transactional to wrap every repository operation in a transaction. Of course, the client only sends the id of an already existing Category, not the whole representation, just a reference (the foreign key).
In that method, if I do this:
entity = repository.save(entity);
the variable entity now has a Category with only the id field set. This didn't surprise me. I wasn't expecting a save (SQL insert) to retrieve information on related objects. But I need the whole Product object and related entities to be able to return to the user.
Then I did this:
entity = repository.save(entity);
entity = repository.findOne(entity.getId());
that is, retrieve the object after persisting it, within the same transaction/session.
To my surprise, the variable entity didn't change anything. Actually, the database didn't even get a single select query.
This is related with Hibernate's cache. For some reason, when in the same transaction, a find does not retrieve the whole object graph if that object was previously persisted.
With Hibernate, the solution appears to be to use session.refresh(entity) (see this and this). Makes sense.
But how can I achieve this with spring data?
I would like to avoid to create repetitive custom repositories. I think that this functionality should be a part of spring data itslef (Some people already reported this in spring data's forum: thread1, thread2).
tl;dr
References between entities in the web layer need to be made explicit by using links and should not be hidden behind semi-populated object instances. References in the persistence layer are represented by object references. So there should be a dedicated step transforming one (the link) into the other (the fully populated object reference).
Details
It's an anti-pattern to hand around backend ids as such and assume the marshaling binding doing the right thing. So the clients should rather work with links and hand those to the server to indicate they want to establish a connection between an already existing resource and one about to be created.
So assuming you have the existing Category exposed via /categories/4711, you could post to your server:
POST /products
{ links : [ { rel : "category", href : "/categories/4711" } ],
// further product data
}
The server would the instantiate a new Product instance, populate it with additional data and eventually populate the associations as follows:
Identify properties to be populated by looking up the link relation types (e.g. the category property here.
Extract the backend identifier from the given URI
Use the according repository to lookup the related entity instance
Set it on the root entity
So in your example boiling down to:
Product product = new Product();
// populate primitive properties
product.setCategory(categoryRepository.findOne(4711));
productRepository.save(product);
Simply posting something like this to the server:
POST /products
{ category : {
id : 1, … },
…
}
is suboptimal for a lot of reasons:
You want the persistence provider to implicitly persist a Product instance and at the same time 'recognize' that the Category instance referred to (actually consisting of an id only) is not meant to be persisted but updated with the data of the already existing Category? That's quite a bit of magic I'd argue.
You essentially impose the data structure you use to POST to the server to the persistence layer by expecting it to transparently deal with the way you decided to do POSTs. That's not a responsibility of the persistence layer but the web layer. The whole purpose of a web layer is to mitigate between the characteristics of an HTTP based protocol using representations and links to a backend service.

How to have a User Account for different entities in Spring JPA?

I'm making a system (using Spring + JPA with MySQL) that shows the best applicants for a certain job offer. The company and the applicants have their respective user account, and with that, they can fill in their personal/company information and their job profile/job offer conditions. With that, the system should match the job conditions (like 3+ years of experience in C) with the applicant's job profile.
My problem is that the User Account is created first, and should be independent, but these two different entities (Applicant and Company), with different attributes, are using it. So if I do something like create an applicant and company in the User Account, one of them will be always null.
How can I solve this? I guess the problem would be something like: how to implement a user account that can hold data from different entities that have different attributes (therefore, can't be grouped)? (In fact, I need one more entity, but I tried to simplify it to illustrate the problem more clearly).
I think, you should make marker interface, like public interface UserAccountable or smth. Implement this interface in your Applicant and Company classes. Then you can make a field in UserAccount class, like private UserAccountable someUser; and throught setters and getters you can assign and get this variable to Applicant or Company.
Hope this helps!
I found what I needed here: https://thoughts-on-java.org/complete-guide-inheritance-strategies-jpa-hibernate/
The problem was the mapping, not the class design per se. I could create interfaces and abstract classes to solve it in the Java world, but in the SQL world that's not possible, so the mapping is the key. In this case, I was looking for the Joined table mapping, but I realized I needed it just to not have null fields in my UserAccount, because I don't need a polymorphic query (e.g. give me the names of every 'user type' (Person, Company)), and it would be too costly performance wise to implement it that way, so I'll trade off space for performance, and I'll just reference all three user types in the User Account, leaving two of those three fields null forever.
PS: Single table mapping won't help because I do need to use not null conditions.

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?
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 :
Cohesion & Coupling
if it's real project , it might become problem to support it
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
when you don't use active record pattern you can share entity with web layer , with active record entity can't be Serializable.
code become bigger and bigger

Getting all aggregate root entities child entities?

I am attempting to refactor my application from a repository per entity to a repository per aggregate root.
A basic example would be I have an entity root of Cars. Cars have hire contracts. As far as I can see contracts don't exist without cars hence cars is the aggregate root.
I am trying to implement a user view which will shows every contract in the system(all the child entities of the root entities). Before refactoring I could just go to my contracts repository and get All. As contracts repository has been removed (as its not a root) I now need to get all cars out of my repository and then get all their contracts.
My repository has the interface
public interface ICarRepository
{
IQueryable<Car> All { get; }
IQueryable<Car> AllIncluding(params Expression<Func<Car, object>>[] includeProperties);
Car Find(long id);
void InsertOrUpdate(Car car);
void Delete(long id);
void Save();
}
I thought of creating an ICarManagementService and having it have a GetAllContracts method (perhaps with filter parameters). Would that mean to get all contracts I need to pull all car entities out with their contracts and then retrieve each entities associated hire contracts and filter them?
I can then pass these to the controller and AutoMap the contracts as before.
Is this best practice?
Thanks
Graeme
As far as I can see contracts don't exist without cars hence cars is
the aggregate root.
This is not necessarily true. 'Don't exist without' is not enough for an entity to become a part of an Aggregate Root. Consider classic order processing domain. You have an Order that is an Aggregate Root. You also have a Customer that is an Aggregate Root. Order can not exist without a Customer but it does not mean that Orders are part of the Customer Aggregate. In DDD entities inside one Aggregate can have references to other Aggregate Roots. From DDD book:
Objects within the AGGREGATE can hold references to other AGGREGATE
roots.
Aggregate is a life cycle and data exchange unit. It is essentially a cluster of objects that enforces invariants. This is something you want to be locked if you have multiple users changing domain at the same time.
Back to your question, my understanding is that the domain is something like rent / lease a car / truck / limo / bulldozer. I think that HireContract may not be a part of Car aggregate because they may have different lifecycles and HireContract just makes sense on its own, without a Car. It seem to be more of a Order-Product relationship that is also a classic example of two different Aggregates referencing each other. This theory is also confirmed by the fact that business needs to see "All Contracts". They probably don't think of Car containing all Contracts. If this is true than you need to keep your ContractsRepository.
On an unrelated note, you might be interested in reading this answer about repository interface design.
Separate the concept of read/query from the write/command, as guided by CQRS it is preferable to design the application by separating read model which consists of read only queries and the write model on the other hand which consists of commands to execute certain logic on the domain model.
thus querying all aggregate roots or creating custom queries to join sets of data is not a good candidate of domain repository, instead put these queries into read repository (or better named Finders).
if you find yourself wanting to query a collection of objects in order to execute some domain logic then it is an indicator that you have to abstract this collection and put it into an aggregate root to encapsulate them and make the business operation or method act on them.
check out (http://moh-abed.com/2011/09/13/pure-old-ddd-with-a-twist-from-cqrs/) and (http://simon-says-architecture.com/2011/08/23/repository)

Resources