Map collection attributes in JPA entity from SQL view - sql

I have the following Entities, User and Policy. A User can have multiple policies. I wanted to avoid associations between them, firstly, because the logic behind which policies belong to which user would depend on other things as well, and secondly, to avoid linking aggregate roots by direct reference, so I only store an identifier in the Entity classes.
In order to get a user together with all his attached policies, I decided to create a SQL view, for future reference let's call it user_permission_view, which would look something like this, simplified for brevity
CREATE VIEW "user_permission_view" AS
SELECT * FROM "users"
LEFT OUTER JOIN "permissions"
ON "users"."id" = "permissions"."userId"
The resulting view would have the attributes of both User and Policy. I decided to map this to a Java class called UserPolicyView. However, I'm struggling with how to map the attributes from Policy into a collection field inside the UserPolicyView.
Is it possible to do something like this with JPA? Do I need to define associations to the Policy entity from inside UserPolicyView? How would that affect the generated SQL, if the view already contains a JOIN clause?
Edit:
One possible solution I came up with was to discard the user_permission_view entirely, declare an embeddable PolicyDetails object, create a view containing all user permissions, and use #ElementCollection to specify that view as the source table. Would that work?

declare an embeddable PolicyDetails object, create a view containing all user permissions, and use #ElementCollection to specify that view as the source table. Would that work?
From a technical point of view - yes, it should work (I'll refrain from commenting on whether it's a sound idea from the point of view of domain modelling). You might also want #Immutable, to prevent accidental modification attempts.
As regards your earlier suggestion - you'll only be able to map it as the flattened structure that the view represents. No collection fields, I'm afraid. You can, of course, choose to map only some of the view columns onto properties. But, I suppose that's not what you're after.

Related

Embed Ektron smartform in another Ektron smartform

(Using Ektron version 8.6.1)
Say I have a smartform ContactInfo, something like:
<ContactInfo>
<Name></Name>
<Email></Email>
</ContactInfo>
I would like to create another smartform (e.g. NewsArticle) and "embed" ContactInfo inside
<NewsArticle>
<Title></Title>
<Summary></Summary>
...
<ContactInfo>
<Name></Name>
<Email></Email>
</ContactInfo>
</NewsArticle>
My solution thus far has been to include a Resource Selector field to add a reference to an existing smartform instance. I would prefer to make the association at the configuration level, to make the data entry workflow more intuitive.
I'm using Bill Cava's ContentTypes and generating classes from smartform XSDs, so it would also make the presentation code more natural and type-safe in that embedded fields could be accessed directly (rather than having to make another request based on a reference ID, which may or may not be an ID to the smartform I'm expecting).
I gather this is not possible out of the box; I'm not opposed to hacking Workarea code to make something like this work. Does anyone have experience with a scenario like this?
I heard from an Ektron rep that they are planning on elevating the role of smartforms in an upcoming summer release - can anyone offer some more info to that point? Perhaps smartform composition like I've described will be supported?
Currently it isn't possible to do smartform composition. Depending on why/if you actually need a second smartform definition, you could just define the contact info in the news article.
If the contact info smartforms are related to the news articles in a one to many or many to many fashion, then using the resource selector as you have is the only way that I know of to create the relationship you are looking for.
If the relationship is one-to-one or many-to-one, then I'd suggest doing away with the separate smartform definition.
If you can clarify the workflow you are trying to achieve for the content authors, I might be able to respond better.
The Content Types would represent the data in the CMS. Suppose, as in your example, a NewsArticle contains a reference to a ContactInfo. Embedding the ContactInfo inside your NewsArticle might make sense from a presentation perspective, but it turns your ContentTypes into a one-way data model. You would lose the ability to construct a new NewsArticle and persist it into the CMS.
What might work well for you is to leave the content types as-is, with the id of the ContactInfo from the resource selector. Then create a NewsArticleDisplayModel... essentially a view model that contains the news article data plus ContactName and ContactEmail.
Now, if you need the contact info to be searchable, you could get really fancy with CMS Extensions and hook into the OnBeforePublish event to update searchable metadata with the name from the ContactInfo, so that the NewsArticle can be searched for using the values from the other "embedded" resource. That could get kinda tricky, though... ideally you'd have to also hook into the publish events of the ContactInfo objects in case something changes on that side, too. Then do you create a custom database table to track which NewsArticle content ids are using a particular ContactInfo?
Your solution can get as complex as it needs to, but I would keep the content blocks separate. If nothing else, you'll end up with a more maintainable and upgradable solution.

Repository pattern, POCO, ORM and intermediate entities

I am trying to figure out how to address this issue:
I have 3 tables with a many-to-many relationship.
Users *-* Roles *-* Permissions
I use a ORM to obtain data from them.
A method of my business layer must return users per permission, so I return objects with this class:
public class UsersPerPermission
{
public User[] {get;set;}
public Permission {get;set;}
}
But this class does not map to any table in the repository, it is something I generate from the existent tables. Where should this class live?
In other words:
Should I have a IRepository.GetUsersPerPermission()? And then that class should live in the repository.
Or should I have a IBusinessLayer.GetUsersPerPermission()? And then I have to invoke the CRUD methods in the repository?
It makes sense to put it in the business layer only, because the repository should just expose CRUD operations to tables... BUT, in order to execute this operation from the Business layer, I would have to execute several independent queries to get the data and create the 'UserPerPermission' class. In the other hand, if I place it in the repository, I can get that information in one shot using grouping.
Thanks!
PS: What is the name of this intermediate objects? 'transformations'?
In DDD, most entities and value objects should correspond to identified domain concepts that are part of your ubiquitous language. I usually try to limit many-to-many relationships and artificial association objects as much as possible. Eric Evans describes a few techniques allowing that in his book. When I have to create an association object, it must have a meaningful name with regard to the domain, basically I never name it Class1ToClass2.
In your scenario, it's even more artificial since your object :
Redundantly models an association that already exists (indirectly) in the original model.
Has a name that doesn't reflect any particular business concept.
Note that this kind of object wouldn't be useless if we were in the presentation or application layer as it could come in handy to have a structure containing exactly what is displayed on the screen (DTO). But I'm talking about the domain layer here, which should be devoid of such composite objects.
So I wouldn't create a UsersPerPermission class in the first place. If what you want is a list of users and User is an aggregate root, just create a GetUsersByPermission() method in UserRepository. It doesn't mean that you can't have a GetUsersByPermission() method in an application service as well, if it matches a use case of your application (a screen that displays the details of one permission and the list of users with that permission).
I agree with guillaume31 that there is no need to introduce a domain object "UsersPerPermission" to support a single use case.
There are two ways you can implement your use case using existing domain classes "User", "Role" and "Permission".
Solution one:
Assume you have: Permission --> Role --> User
Arrow denotes navigability. A Permission has association to a list of Roles and a Role has association to a list of Users.
I would add a method GetPermittedUsers() : List<User> to the Permission class, which is trivial to implement.
Th UI logic will invoke GetPermissions() of PermissionRepository then call GetPermittedUsers() on each Permission.
I assume that you use a ORM framework like hibernate(Nhibernate) and defines the many-to-many relationships correctly. If you defines eager loading for Role and User from Permission, the ORM will generate a query that joins Permission, Role and User tables together and load everything in one go. If you defines lazy loading for Role and User, you will load a list of Permissions in one query when you call PermissionRepository, and then load all associated Roles and Users in another query. Everything is load from database with up to three queries maximum. This is called a 1+n problem which most ORMs handle properly.
Solution two:
Assume you have: User --> Role --> Permission
Arrow denotes navigability. A User has a list of Roles. A role has a list of Permission.
I'd add getUsersByPermissions(List<long> permissionIds) : List<Users> to the UserRepository, and add getPermissions() : List<Permission> to the User class.
The implementation of the UserRepository need to join the User, Role and Permission tables together in a single query and load everything in one go. Again, most ORMs will handle it correctly.
Once you have a list of Users, you can create a method to build a Map<Permission, List<User>> quite easily.
To be honest, I muck like the solution one. I avoid to write a complicate method to convert a List of Users to to a map of Permission and Users, hence I don't need to worry about where to put this method. However solution one may create cyclic relationship between User, Role and Permission classes if you already have navigability in another direction. Some people don't like cyclic relationship. I think the cyclic relationship is acceptable even necessary sometime if you user cases demand it.
In a similar context I used a query method in a domain service that returns something like an
IEnumerable<KeyValuePair<PermissionName, IEnumerable<Username>>>
By using the KeyValuePair<> I avoided to pollute the domain model with an artificial concept (like UsersPerPermition). Moreover such a structure is immutable.
I didn't used a query method on the repository because, in my context, no entity was coupled with the other. So it wasn't matter for any of the repositories.
However this solution is useful for your GUI, if and only if you modelled correctly the identifiers of your entities (in your example both Permissions and Users are entities).
Indeed if they are shared identifiers that belong to the ubiquitous language that your users understand, they will be enough without further descriptions.
Otherwise you are just building a useful DTO for your GUI. It does not belong to the domain thus you should use the simplest possible thing that works (an ADO.NET query? something even simpler?).
Indeed, in my own scenario both the GUI and the domain used such a service (the GUI showing a preview of an elaboration).
In general, the domain model must mirror the domain expert's language, capturing the knowledge relevant to the bounded context. Everything else must be outside the domain (but most of time can be expressed in terms of the domain's value objects).

ORM: authorization via reachability

We are building a webapplication which uses a database. Also we use an object relational mapper to access the database. One aspect of authorization in the webapplication is that the user may access an object referred to by an URL. The URL contains a unique id (for example the Primary Key) to a specific record in the database. Consider the following example.
a user may belong to many groups and a group may have many users (many-to-many).
a survey belongs to a group (many-to-one).
a survey may have multiple questions. (many-to-one).
Say we have the following URL: http://app.local/question/edit/10. This means we want to edit question with PK 10. Now, we want to verify if the logged in user may access question with PK 10. This can be done by retrieving this question, then it's survey then it's group and then all its users. If any of the users is the same as the logged in user the logged in user may access the question.
To generalize this a bit; we want to check if a record is reachable from another record by the known many-to-one or many-to-many relations. So if there is a many-to-one relation (like with a survey and a question then we should check if a user is reachable from the question through the survey and then through the group. The group has a many-to-many relation with the user so we should check if any (not all) of the users is the same as the logged in user.
If a table has multiple many-to-one relations, say; we can attach a CSS template to a survey and this template also belongs to a group then we have to check if a user is reachable from all many-to-one relations (thus the group and the template). The same holds of course for multiple many-to-many relations.
Are there Object Relation Mappers which support this behaviour? And what is this behaviour called, maybe reachability? Does Propel (for PHP) support this behaviour? I think this reachability can be done in any of the following two ways:
Execute a query to get each "parent", uses many queries)
Join all necessary tables to see if a record exists (the reachable users matches the logged in user) in one query.
Furthermore this behaviour of the ORM should support nested sets, thus if a group contains nested set behaviour it should also try to reach a user through the group's parent.
I don't think this kind of behaviour should be restricted to authorization; objects should simply be able to see if they can reach another object.
Note that I do not mean persistence by reachability: http://jpaobjects.sourceforge.net/m2-site/main/documentation/docbkx/html/user-guide/ch08s03.html.
Or... am I simply looking at this authorization wrong and is there a far better and different approach with an ORM?
I've handled this in the past using nested resources in Ruby on Rails (which uses the Active Record ORM). Rather than http://app.local/question/10/edit, the URI would be http://app.local/survey/5/questions/10/edit
In the controller you load both the question and survey. You check authorization by comparing the survey to the authenticated user's group memberships. One way to engineer this would be to embed this logic into the User class. For example, in the controller you have question and survey (and the relationship between the two is well understood by the ORM, i.e. question.survey). You could then check access as user.hasAccess?(question), which would be a relatively easy method to write. Pseudocode:
class User < ActiveRecord::Base
def hasAccess?(question)
return question.group.users.include?(self)
Yes, this will result in several queries behind the scenes, but ORMs do the work. I do it this way because you're left with solid schema and easy to read code. Don't optimize until you actually have a performance problem.

Additional RESTful methods and actions DRY

I have a model that has several columns I want to present to the interface to update as different pages. My question deals with what is the best rails-y way to organize your routes and controller actions.
For example, a User has a "Profile" and a "Billing Address". Both pages contain columns only from the User model, they are required and one-to-one, and small, so an additional model seems like unnecessary overhead.
It seems like I have to add a GET and a PUT for each different view I want to present, is that right? So instead of just edit/update, I'd need edit_profile/update_profile and edit_billing/update_billing, etc.
Even without a Profile model, I think you still can use ProfileController and views for profile like 'views/update.html.erb', and make it route as '/users/123/profile/'.
In my opinion, we don't need to mapping every view or controller to one model strictly. Rails is based on ROA, but here the "resource" can be more abstract.

How to associate calculated values to an object

I have some basic objects like Customer, Portfolio and ... with some association to other objects. I can easily display the required information in the web page by reading object values. The problem is that what do I do when the value associated with the object is calculated and returned by a method, a value that makes sense only in certain context and cannot be attached to the object as an instance variable? In this case if I have a list of say Users I have to pass the username of each user to the method to get the calculated value. This causes problem to keep the association while displaying the values in the page.
An example to make this clear:
An application provides the functionality for users to keep track of each others activities by letting them add whoever they want to a list. If this user performs a search on users there's the option to follow each returned user. I want to make sure this option is disabled for those user's that are already being followed. This functionality is provided by a method like isFollowed(String follower, String followee) which returnes a boolean. How can I associate this boolean values to each user in search result?
Solutions:
One thing I can think of is to add a followed instance variable to User class. But I don't think it's a good approach because this variable only makes sense in a certain context. It's not a part of User class in the domain.
The other way I can think of is to use Decoration or Wrappers in a way to extend the User class and add the attribute in the child class. But again what if I have several objects that need to be in the same context. In that case I have to extend all of them with the same boolean attribute in all classes.
I hope I could make it clear.
In principle, I don't see anything wrong with instance method on User: bool IsFollowedBy(User user).
Of course, this could lead to performance issues. If that is the case, you can create separate object for presentation purposes which bundles data from User and whether he is being followed by the user performing search. Then you can build query which retrieves all necessary data for such object in a single roundtrip to DB.
One solution is to avoid querying Entities (as in DDD/ORM) and query directly using subquery/join or even using some denormalized database. This is something CQRS pattern suggests.
Other solution is to do computations on application layer (how many Users can you show on the same page anyway), which is expensive but you can implement some caching techniques to make things easier.