MappedSuperclass Alternatives in Grails - grails

In many past projects, I used this JPA / Hibernate approach to add auditing capabilities to a system. It's very effective and unobtrusive.
Is there a Grails #MappedSuperclass alternative (short of coding domain model objects in Java instead of Groovy)? How can one declare a parent class in a table-per-subclass approach without having a table created for it? I've read the GORM documentation (5.2.3 Inheritance in GORM) but besides the table-per-hierarchy vs. table-per-subclass discussion, I did not find any details on how to do this.
Alternatively, what is the recommended way to achieve this type of auditing in Grails?

Essentially, it's as simple as declaring the MappedSuperclass as abstract and Grails will not create a table for it. I realized by re-reading the manual:
GORM supports inheritance both from abstract base classes and concrete persistent GORM entities. I.e. concrete classes are persistent, so abstract ones are not. Pays to read more carefully.
E.g.
abstract class Auditable {
Date dateCreated
Date lastUpdated
}
class Book extends Auditable {
String title
String description
}
Only the book table will be created and it will have the date_created and last_updated columns. Furthermore, as an added bonus, the dateCreated and lastUpdated properties are auto time-stamped by Grails.

Related

Java8 and Spring Data Neo4j application queries

I have a bunch of questions regarding Java 8 and SDN4. I created a model in Neo4j v3.0, played a bit with Cypher queries, and now moved to creating a Spring Boot application. As i started coding classes in Java, I've begun to rethink some of my model as well. Here's some questions in my mind (and I haven't found an example explaining this):
Do you need to use Interfaces in Java, with SDN?For eg. I'd code a Product interface and then have my products implement it, but is that how it's done when working with labels?
This is somewhat tied to my question on inheritance - I'd usually have a ProductFamily that my Product would inherit from. At the database level its modeled as (:Product)-[PartOf]->(:ProductFamily), but in the code these would not be super/sub class.
Any examples of using Generics in a graph context?
Is there a way to define constraints on what relationships a node can have and their direction in Java?
I understand there is probably not one right answer, but there's precious little on the web, so hope to get enlightened here!
If you had a Product interface annotated with #NodeEntity, then the you'll have the Product label in addition to the label on your implementing class, which I assume is what you want. If your interface isn't annotated, then your implementing classes will not inherit a label from it.
Not sure what you mean- if you say you have a ProductFamily that Product inherits from, but in the code it would not be a super/sub class?
Based on your graph model, if you want (:Product)-[PartOf]->(:ProductFamily) then you will have a Product class that maintains a reference to a ProductFamily class, and that reference annotated with #Relationship. If the Product class inherits from ProductFamily then persisting the Product will result in two labels- Product and ProductFamily because a Product IS-A ProductFamily.
How do you see yourself using generics- the answer really depends on that. Some cases are supported, some are not (an example of something not supported right now is equivalent of template.createRelationBetween in SDN4)
Yes, via the #Relationship annotation which accepts a type and direction. Note that this annotation only constrains your domain model, but you could very well flout this by creating relationships in another direction via a custom query.

Grails GORM Inheritance best practices

I am working on a grails project with potentially 36 domain classes each with a dozen plus unique properties and a handful of shared properties that can be inherited from a base domain class. The problem with this is that grails will generate 1 table with all the properties from all the domain classes that inherit from the base class. This means a table with well over 300 columns which seems problematic on multiple levels. The other route is to do away with inheritance and each domain represents a unique database table. No matter what, either a lot of time will be spent duplicating code or trying to manage the generated database. Is there another option that I am missing?
All thoughts and opinions welcome.
It would appear you are missing the all important tablePerHierarchy mapping value for domain classes. I highly recommend you read the Inheritance Strategies documentation regarding this.
From the documentation:
By default GORM classes use table-per-hierarchy inheritance mapping.
This has the disadvantage that columns cannot have a NOT-NULL
constraint applied to them at the database level. If you would prefer
to use a table-per-subclass inheritance strategy you can do so as
follows:
class Payment {
Integer amount
static mapping = {
tablePerHierarchy false
}
}
class CreditCardPayment extends Payment {
String cardNumber
}
The mapping of the root Payment class specifies that it will not be
using table-per-hierarchy mapping for all child classes.
Don't use inheritance between classes. It is very hard to make refactors in classes with inheritance.
You can use dynamic behavior for common classes through interfaces, or maybe re-think the design in the model classes.

What are the pros and cons of writing class methods in grails domain classes?

What are the pros and cons of writing class methods in grails domain classes? I am asking, because I often do not see any grails projects with methods inside the domain classes, only data members. Is there a disadvantage to doing so?
When a domain class (not just in grails, but in object oriented programming in general), this is known as an anemic domain model. Martin Fowler proposes that domain logic gets put into the domain class to create a rich domain model. By doing this, domain classes become smarter and know how to perform operations, rather than having another service class that has to operate on the domain class. The pros of having a rich domain model is that the class encapsulates more of its own behavior, and it is more self contained. On the flip side, it does make the domain class more complex. Though I think the domain class should be more than just a business object.
In grails, I tend to try to use a combination of a rich domain model and using services. It's difficult to make a blanket statement as to when a method should be in a domain class and when it should be in a service. As a general rule though, if an operation is complex and requires multiple collaborators, I'll tend to put it in a service class. If the method seems like it should be behavior on the domain class, I'll put it there.
To give a more concrete example, let's take a Person class.
class Person {
String firstName
String lastName
List<Person> friends
}
In our application a person can speak. Now I can have a TalkService that knows how a person talks. But in this case, I think that talk is a core behavior of the person, so I would add a talk method to Person.
Let's say I also have functionality where I want to find all of the friends of friends of people (2nd degree friends). To me, this is not core behavior of a Person, so I woul delegate this out to a service.
To recap, in general I would add methods to the domain class when it is core behavior of the object (e.g. is it a domain method), otherwise, I would put it in a service.
In a Java project, you must have POJO classes that represents the model.
For example: Person, Invoice, Book, ...
Then there is the service layer, which contains interfaces for users to do some database queries, it takes in parameters your Model, and also return Model, and there is the controller layer which is responsible for redirection and inject your services.
In grails, this is very easy using injection of services into your controller
Now, when do we need to use methods inside the domain classes ? it's when only the model which responsible for what do we need to do, for example, how old is a Person X (it's from the date of birth), how many items exist in a Invoice (from the List), the think is we use that only when we manipulate the data of the current object.
For save method for example, you cannot add it in your model
PersonController :
def personService
def save() {
...
Person person = ...
personService.save(person);
...
}
This is more evolutive

Use data annonations in ASP.NET MVC using DDD

I've started to develop ASP.NET MVC application using Entity Framework and I wish to use DDD. It's my first time using DDD in ASP.NET (used until now in PHP), so I'm little confused.
I'm using code-first approach, so I'm creating my entites in the core and then the DbContext in the Infrastructure.
My questions is about data annotations: Is it OK to annonate the entities in the core? with Required, DataType, etc. or I have to create entries with pure C# validation (in the setters and getters) and then create a map objects for the database creation?
For example, I got:
public class Account
{
public string AccountName { get; set; }
}
Can I annonate the AccountName with [Required] or I need to create a map class which will just reflect the exact same properties in the Account class but will have attributes and that will be the class that I'll use in Entity Framework DbContext?
Thanks!
Neither.
Your entities should have barely any public getters or setters. Domain model is a behavioral model, not a data model. Your entities should have private fields and methods that changes the entity state. Those methods should have a business meaning and should protect entities invariants (validate input). For example - we have UserAddress and want to change it. Is it just user.Address = newAddress? NO. What's the meaning of changing that? Maybe your User want to FixMistypedAddress(str). Or maybe your UserMoved(newLocation)? Different business rules may apply tho those scenarios. For example when UserMoved() we want to send him a champagne bottle, but not when he just fixed a typo. You should already see that there is no use of data annotations here because we don't just set properties but we do meaningful operations.
Entities should always be valid. That mean there should be no way to put it in an invalid state. Data annotations only allow you to check whether the object is valid or not. They not guarantee is will be valid all the time.
IMO Data annotations are fine for:
Using Entity Framework in a CRUD application (no DDD applied)
In DTO or ViewModels. In other words - for validating user forms, not entities.
So the first quiestion for you is: Are you doing CRUD or DDD?
I'd say either way is fine.
If you want a more pure approach you would create a buddy class that has the metadata on it however it is also acceptable to put it directly on the domain class.
In the end it comes down to how much you want to remain "pure" and how much extra work you want to put into maintaining buddy classes, not to say that it is a bad thing.

Setting metaClass property on domain object

Any reason not to use metaClass on domain objects? as in
domainObjectInstance.metaClass.dynamicTransientGreeting = "Hello"
Will this mess with hibernate at all?
It won't mess with Hibernate at all since it won't be seen by Hibernate. GORM only maps "real" properties to Hibernate properties.
That's why the id and version columns and the collections that are generated from hasMany declarations (e.g. the users collection generated by static hasMany = [users: User] are added to the actual bytecode using an AST. If they were added just to the MetaClass they wouldn't be seen and wouldn't be persistent.

Resources