Spring Data REST - How to update entities in child collections of aggregates - rest

Following the principles of DDD and using Spring Data REST/HATEOAS what is the best way to manipulate entities in child collections.
For example:
#Entity
public class Topic{
#Id #GeneratedValue
private Long id;
private String title;
#OneToMany
private Set<Post> posts;
…
}
#Entity
public class Post{
#Id #GeneratedValue
private Long id;
private String title;
private String body;
#OneToMany
private Set<Comment> comment;
…
}
#Entity
public class Comment{
#Id #GeneratedValue
private Long id;
private String text;
}
Spring Data REST (SDR) inlines domain objects that don't have their own repositories when serializing to JSON.
{
"title" : "Spring",
"posts" : [{
"title": "Spring Boot 1.5.8",
"body": "blah",
"comments":[ {"text":"great!"} , {"text":"boo"},
{"text":"comment that should be removed by moderators"}]
}]
"_links" : {
"self" : {
"href" : "http://localhost:8080/topics/1"
}
}
}
The issue I have is that I am unable to get a handle on individual objects in a collection because SDR not only hides ids for all entities but also does not provide a 'self' link for inlined entities.
I don't want to simply PUT the whole aggregate because inline with DDD I want to handle changes of state via dedicated 'controller' resources, allowing the raising of event to trigger additional business logic. Consider adding/removing/updating a post comment in the example above.
I'm left with an number of options none of which I really like.
Reverse all my unidirectional relationships and create repositories for all the child entities, effectively abandoning the DDD aggregate design concept.
Move to bi-directional relationships, create repositories for all child entities and compose the aggregate using a Projection. The general advice from the internet (including SDR developer Oliver Gierke) is to avoid bi-directional relationships if at all possible due to performance considerations and having to manually manage the relationship.
Add a GUID or some other immutable unique identifier to the child entities. This feels wrong considering the whole point of HATEOAS is that the URI is the identifier. Even this breaks down when dealing with children of children.
I'm currently feeling inclined towards 2 as it seems to be the only workable option that allows me to retain the design principle.
Has anyone encountered and overcome a similar problem?
Edit:
I've come up with a possible solution:
Move to bi-directional relationships without creating repositories for child entities. This will give me the parents key so that I can compose a 'self' & other links using a ResourceProcessor e.g /topics/1/posts/add-post which I can handle via a RestController. This should work well enough at 1 level deep, it may have performance implications for deeper nesting e.g. /topics/1/posts/1/comments/add-comment as with JPA there's going to be a cost associated with doing the lookups to traverse the parent relationships. This would be done in tandem with #Alan Hay's solution to exposing Id's where there is no natural key in the entity.
This approach maintains DDD & HATEOAS at the cost of going against advice on bi-directional relationships.
Thoughts?

It is possible to add _links to resources that are not mapped through repositories. To add an action deleteComment, for instance, you should configure a #Bean like this:
#Bean
public ResourceProcessor<Resource<Comment>> commentProcessor() {
return new ResourceProcessor<Resource<Comment>>() {
#Override
public Resource<Comment> process(Resource<Comment> resource) {
resource.add(linkTo(methodOn(MyCustomController.class).deleteComment(resource.getContent().getId())).withRel("deleteComment"));
return resource;
}
};
}
You should get the link of the action on the Comment object inside the Post

Related

Simple Tagging Implementation with Spring Data JPA/Rest

I am trying to come up with a way of implementing tags for my entity that works well for me and need some help in the process. Let me write down some requirements I have in mind:
Firstly, I would like tags to show in entities as a list of strings like this:
{
"tags": ["foo", "bar"]
}
Secondly, I need to be able to retrieve a set of available tags across all entities so that users can easily choose from existing tags.
The 2nd requirement could be achieved by creating a Tag entity with the value of the Tag as the #Id. But that would make the tags property in my entity a relation that requires an extra GET operation to fetch. I could work with a getter method that resolves all the Tags and returns only a list of strings, but I see two disadvantages in that: 1. The representation as a list of strings suggests you could store tags by POSTing them in that way which is not the case. 2. The process of creating an entity requires to create all the Tags via a /tags endpoint first. That seem rather complicated for such a simple thing.
Also, I think I read somewhere that you shouldn't create a repository for an entity that isn't standalone. Would I create a Tag and only a Tag at any point in time? Nope.
I could store the tags as an #ElementCollection in my entity. In this case I don't know how to fulfill the 2nd requirement, though.
#ElementCollection
private Set<String> tags;
I made a simple test via EntityManager but it looks like I cannot query things that are not an #Entity in a result set.
#RestController
#RequestMapping("/tagList")
#RequiredArgsConstructor(onConstructor = #__(#Autowired))
public class TagListController implements RepresentationModelProcessor<RepositoryLinksResource> {
#PersistenceContext
private final #NonNull EntityManager entityManager;
#RequestMapping(method = RequestMethod.GET)
public ResponseEntity<EntityModel<TagList>> get() {
System.out.println(entityManager.createQuery("SELECT t.tags FROM Training t").getFirstResult());
EntityModel<TagList> model = EntityModel.of(new TagList(Set.of("foo", "bar")));
model.add(linkTo(methodOn(TagListController.class).get()).withSelfRel());
return ResponseEntity.ok(model);
}
}
org.hibernate.QueryException: not an entity
Does anyone know a smart way?
The representation as a list of strings suggests you could store tags by POSTing them in that way which is not the case
This is precisely the issue with using entities as REST resource representations. They work fine until it turns out the internal representation (entity) does not match the external representation (the missing DTO).
However, it would probably make most sense performance-wise to simply use an #ElementCollection like you mentioned, because you then don't have the double join with a join table for the many-to-many association (you could also use a one-to-many association where the parent entity and the tag value are both part of the #Id to avoid a join table, but I'm not sure it's convenient to work with. Probably better to just put a UNIQUE(parent_id, TAG) constraint on the collection table, if you need it). Regarding the not an entity error, you would need to use a native query. Assuming that you have #ElementCollection #CollectionTable(name = "TAGS") #Column(name = "TAG") on tags, then SELECT DISTINCT(TAG) FROM TAGS should do the job.
(as a side note, the DISTINCT part of the query will surely introduce some performance penalty, but I would assume the result of that query is a good candidate for caching)

Inheritance vs composition in JPA

A legacy application persistence is based on JPA. There is an entity, People, mapped to the database table People.
Now a subset of all the rows in People needs some additional fields.
One possible solution is to use jpa inheritance and create a new entity, suppose EmployeedPeople, which extends People.
#Entity
#Inheritance(strategy = InheritanceType.JOINED)
public class People {
...
#Entity(name = “EmployeedPeople”)
public class EmployeedPeople extends People {
Alternatively I can use unidirectional one to one relationship
#Entity(name = “EmployeedPeople”)
public class EmployeedPeople {
...
#OneToOne(optional = false)
private People commonPersonData;
I thought about a third way too: the new entity is based on a database view which joins People table with EmployeedData table.
This last approach is good for reading EmployeedPeople but impractical for inserting and updating because I have to work with different entities (People and EmployeedData).
Which criteria can help in choosing the strategy ?
Which are the pros and cons of each solutions ?
In internet I have already found the following guide which compares the inheritance strategies and this one on composition but my ideas are not clear yet.

JPA Simple ForeignKey relationship

Is it possible to create a basic FK relationship in JPA without involving the full entity target object?
As an example, imagine I have an entity:
#Entity(name = "Mechanic")
public class Mechanic {
#Id
private Long id;
//...
and a Car that I want to reference a Mechanic.id:
#Entity(name = "Car")
public class Car {
//...
#NotNull
private Long mechanic_id;
From an Object perspective, this would be a unidirectional, one to one relationship with the Car requiring a Mechanic.id and the Mechanic not needing any back reference to Car.
All I want out of this is to store the Mechanic.id ONLY. For the purposes of this question it is not useful to have a #OneToOne (or #OneToMany etc) relationship with the entity reference, I'm explicitly trying to avoid that but still retain the underlying integrity that a FK will provide.
JPA 2 and I'm using EclipseLink.

JPA 2.0 retrieve entity by business key

I know there have been a number of similar posts about this, but I couldn't find a clear answer to my problem.
To make it as simple as possible, say I have such an entity:
#Entity
public class Person implements Serializable {
#Id
private Long id; // PK
private String name; // business key
/* getters and setters */
/*
override equals() and hashCode()
to use the **name** field
*/
}
So, id is the PK and name is the business key.
Say that I get a list of names, with possible duplicates, which I want to store.
If I simply create one object per name, and let JPA make it persistent, my final table will contain duplicate names - Not acceptable.
My question is what you think is the best approach, considering the alternatives I describe here below and (especially welcome) your own.
Possible solution 1: check the entity manager
Before creating a new person object, check if one with the same person name is already managed.
Problem: The entity manager can only be queried by PK. IS there any workaround Idon't know about?
Possible solution 2: find objects by query
Query query = em.createQuery("SELECT p FROM Person p WHERE p.name = ...");
List<Person> list = query.getResultList();
Questions: Should the objects requested be already loaded in the em, will this still fetch from database? If so, I suppose it would still be not very efficient if done very frequently, due to parsing the query?
Possible solution 3: keep a separate dictionary
This is possible because equals() and hashCode() are overridden to use the field name.
Map<String,Person> personDict = new HashMap<String,Person>();
for(String n : incomingNames) {
Person p = personDict.get(n);
if (p == null) {
p = new Person();
p.setName(n);
em.persist(p);
personDict.put(n,p);
}
// do something with it
}
Problem 1: Wasting memory for large collections, as this is essentially what the entity manager does (not quite though!)
Problem 2: Suppose that I have a more complex schema, and that after the initial writing my application gets closed, started again, and needs to re-load the database. If all tables are loaded explicitly into the em, then I can easily re-populate the dictionaries (one per entity), but if I use lazy fetch and/or cascade read, then it's not so easy.
I started recently with JPA (I use EclipseLink), so perhaps I am missing something fundamental here, because this issue seems to boil down to a very common usage pattern.
Please enlighten me!
The best solution which I can think of is pretty simple, use a Unique Constraint
#Entity
#UniqueConstraint(columnNames="name")
public class Person implements Serializable {
#Id
private Long id; // PK
private String name; // business key
}
The only way to ensure that the field can be used (correctly) as a key is to create a unique constraint on it. You can do this using #UniqueConstraint(columnNames="name") or using #Column(unique = true).
Upon trying to insert a duplicate key the EntityManager (actually, the DB) will throw an exception. This scenario is also true for a manually set primary key.
The only way to prevent the exception is to do a select on the key and check if it exists.

Persisting a list of an interface type with JPA2

I suspect there's no perfect solution to this problem so least worst solution are more than welcome.
I'm implementing a dashboard using PrimeFaces and I would like to persist the model backing it (using JPA2). I've written my own implementation of DashboardModel and DashboardColumn with the necessary annotations and other fields I need. The model is shown below:
#Entity
public class DashboardSettings implements DashboardModel, Serializable{
#Id
private long id;
#OrderColumn( name="COLUMN_ORDER" )
private List<DashboardColumn> columns;
...a few other fields...
public DashboardSettings() {}
#Override
public void addColumn(DashboardColumn column) {
this.columns.add(column);
}
#Override
public List<DashboardColumn> getColumns() {
return columns;
}
...snip...
}
The problem is the columns field. I would like this field to be persisted into it's own table but because DashboardColumn is an interface (and from a third party so can't be changed) the field currently gets stored in a blob. If I change the type of the columns field to my own implementation (DashboardColumnSettings) which is marked with #Entity the addColumn method would cease to work correctly - it would have to do a type check and cast.
The type check and cast is not the end of the world as this code will only be consumed by our development team but it is a trip hazard. Is there any way to have the columns field persisted while at the same time leaving it as a DashboardColumn?
You can try to use targetEntity attribute, though I'm note sure it would be better than explicit cast:
#OrderColumn( name="COLUMN_ORDER" )
#OneToMany(targetEntity = DashboardColumnSettings.class)
private List<DashboardColumn> columns;
Depends on the JPA implementation (you don't mention which one); the JPA spec doesn't define support for interface fields, nor for Collections of interfaces. DataNucleus JPA certainly allows it, primarily because we support it for JDO also, being something that is part of the JDO spec.