Implementing the Strategy Pattern against generated pojos - java

I am writing a parser for a couple of different DB tables. We're using Hibernate with Eclipse, and we've made hbm.xml mapping files that correspond to our tables so that our .java files are generated in line with the tables.
We've added a new table called Gamer containing the usual user stuff (address name phone# etc). It's not related to the established Customer table(also containing address name phone# etc), but there's a lot of shared behaviour in the validation steps.
I think this would be ripe for applying the Strategy design pattern to, the problem being that the Customer POJO and the Gamer POJO aren't inheriting from anything, and they are being defined off of independent unrelated tables.
I'm quite new to design patterns and I'm rather wary that I may be being an utter dumbass so any suggestions on how I might go forward and share the validation logic, without having to resort to having CustomerAddressValidator and GamerAddressValidator classes which do the exact same thing.

First of you have to distinguish whether the Gamer is a Customer, or Gamer and Customer are both Persons.
In both cases you will have some base class and extended class(es). In Hibernate (and JPA) there are three ways to handle inheritance: Single Table, Joined and Table Per Class. All three methodologies have prons and cons, so you have to chose one based on your concrete domain problem. More about ineritance you can read here(JPA) and here(Hibernate).
After that, you will be able to write single Validator for base class (if all required values for validation are placed in base class) and call that validator for both base and extended class.
As I can from your answer you need Address validator, sou you have to put address in the base class. Hope this help.

Related

Best approach for linking diverse entity types in JPA

Short version for the hasty:
There's various tables/entities in my domain model which have the same field (a UUID). There is a table where I need to link rows/instances of such entities to other JPA-managed entities. In other words, the instance of the field in that link table won't be known up-front. The two approaches I can think of are:
Use an abstract entity and a TABLE_PER_CLASS strategy, or
use an #MappedSuperClass store the class name of the instance in the link table as well, or something similar that lets me define logic for getting the actual instance from the right table.
Both have advantages and disadvantages in terms of complexity and performance. Which do you believe to be best, is there maybe a third option, or have you tried something like this in the past and would advice/strongly warn against?
Long version in case you want more background:
I have a database/object model wherein many types have a common field: a universally unique identifier (UUID). The reason for this is that instances of these types can be subject to changes. The changes follow the command model and their data can be encapsulated and itself persisted. Let's call such a change a "mutation". It must be possible to find out which mutations exist in the database for any given entity, and vice-versa, on which entity a stored mutation operates.
Take the following entities with UUIDs as an (extremely simplified) example:
To store the "mutations", we use a table/entity called MutationHolder. To link a mutation to its target entity, there's a MutationEntityLink. The only reason this data isn't directly on the MutationHolder is because there can be direct or indirect links, but that's of little importance here so I left it out:
The question comes down to how I can model the entity field in MutationEntityLink. There are two approaches I can think of.
The first is to make an abstract #Entity annotated class with the UUID field. Customer, Contract and Address would extend it. So it is a TABLE_PER_CLASS strategy. I assume that I could use this as a type for the entity field, although I'm not certain. However, I fear this might have a serious performance penalty since JPA would need to query many tables to find the actual instance.
The second is to simply use #MappedSuperClass and just store the UUID for an entity in the entity field of MutationEntityLink. In order to get the actual entity with that UUID, I'd have to solve it programmatically. Adding an additional column with the class name of the entity, or something else that allows me to identify it or paste it in a JPQL query would do. This requires more work but seems more efficient. I'm not averse to coding some utility classes or doing some reflection/custom annotation work if needed.
My question is which of these approaches seems best? Alternatively, you might have a better suggestion, or notice I'm missing something; for example, maybe there's a way to add a type column even with TABLE_PER_CLASS inheritance to point JPA to the right table? Perhaps you've tried something like this and want to warn me about numerous issues that would arise.
Some additional info:
We create the database schema, so we can add whatever we want.
A single table inheritance strategy isn't an option. The tables must remain distinct. For the same reason, joined inheritance doesn't seem a good fit either.
The JPA provider is Hibernate and using things that are not part of the JPA standard isn't an issue.
If the entities don't have anything in common besides having a uuid I'd use the second approach you describe: use MappedSuperclass. Making the common superclass an entity would prevent you to use a different inheritance strategy if needed, would require a table for that super entity even if no instances exist and from a business point of view it's just wrong.
The link itself could be implemented in multiple ways, e.g. you could subclass MutationEntityLink for each entity to map (e.g. CustomerMutationEntityLink etc.) or do as you described it, i.e. only store the uuid as well as some discriminator/type information and resolve programatically (we're using that approach for something similar btw.).
You need to use #MappedSuperclass while inheriting associations/methods/properties whereas TABLE_PER_CLASS is generally used when you have entity and sub-entities. If there are entities having an association with the base class in the model, then use TABLE_PER_CLASS since the base class behaves like an entity. Otherwise, since the base class would include properties/attributes and methods which are general to such entities not related to each other, using #MappedSuperclass would be a better idea
Example1: You need to set alarms for some different activities like "take medicine", "call mom", "go to doctor" etc. The content of the alarm message does not matter, you will need a reminder. So use TABLE_PER_CLASS since alarm message, which is your base class is like an entity here.
Example2: Assume the base class AbstractDomainObject enables you to create login ID, loginName, creation/modification date for each object where no entity has an association with the base class, you will need to specify the association for the sake of clearing later, like "Company","University" etc. In this situation, using #MappedSuperclass would be better.

Fowler's Patterns: Dealing with table inheritance in a specific way

These days I'm reading Martin Fowler's Patterns of Enterprise Application Architecture, it's really great.
Since I kinda started an OO PHP project (app backend) I want to use Data Mapper for my Domain Model. I read about Table inheritance and I noticed there are 3 types of it.
I don't like Single because I will have more than few types of entries, which will be subclassed from the base class/type. In this case I would have lots of empty space in the db.
I don't see the other two being suitable either.
That is due to my plan of having:
Base class (Entry)
Subclass (example: StateInstitution extends Entry)
Subclass (example: CompanyAffiliate extends Entry)
....
The main point here is that I intend to be saving the extra info of the subclasses into a common table tbl_entrymeta - that is, I can have many subclasses that extend from the base Entry class, but not a separate table for each (just one, tbl_entrymeta).
My question is: How to use Data Mapper in this scenario? Is the key in creating inheritance mappers? Or metadata mappers are the key?
Create a Data Mapper class for the common table (EntryMeta) which represents the object of the relational database table tbl_entrymeta. This object will hold the meta of the subclasses within 3 Fields (columns):
1. SubClass
2. FieldName
3. FieldType
This way you can easily store the meta of all the sub-classes that inherit the base class and extend it with additional fields of information.

Is there a way to override ID in an entity's subclass in JPA?

Under a specific requirement such as not using an abstract base class (or super class), I need to implement a simple hierarchy of two entities one of which is supposed to extend the other but have a different #Id of its own.
My googling about this seems to conclude this is impossible or only on condition that I use a mapped super class (which is forbidden in my case due to a certain policy).
I don't want to duplicate the code of the entity with several dozen attributes and then mutate the duplicate by adding / overriding attributes in order to avoid future maintenance problems, but then I'm stuck in JPA restrictions.
Any help / suggestion will be appreciated.
Having different id types for non-abstract derived entities is not compatible with the JPA inheritance strategies.
What I mean is:
Imagine you have succeeded and different classes in the hierarchy use different incompatible types for the id.
how would you define the DB constraints for a single table inheritance in such a case?
and for joined inheritance?
EDIT: JPA does not distinguish between inheritance strategies when it comes to id definition. And you cannot even be sure that you can use TABLE_PER_CLASS with pure JPA. Virtually all providers implement it, but it is specified as optional and thus the least portable inheritance strategy.
The question remains however. How can the DB constraints look in order to make the table usable unambiguously by the persistence provider? E.g. Which columns should comprise the primary key on DB level?
If you cannot make the parent entity neither abstract nor embeddable nor use the same id, you will have to work around that. How you do that is highly dependant on what you want to achieve and what organizational constraints you have.
There are several possibilities - the least invasive would be composition, having A as a field in B, effectively creating a 1-1 relation.
More ugly approaches could be native and constructor queries but I doubt you want to descend that far.
tl;dr No, it is not possible.

Naming convention when using hibernate

Me and my team are building java EE app as a school project and we've decided to use hibernate. We also want to make the whole project as nice and clean as possible, so we're trying to follow recommended conventions. Nevertheless I wasn't able to find out, what are the conventions for hibernate files.
I.E. I've got a folder /cz/fit/cvut/nameofmyproject/ and there I've got packages controllers, models, utils. In controllers I've got Spring controllers, in models I want to have models for my entities and in utils I've got SessionFactory for hibernate. And now my question:
How shall I name classes in model package? Should it be MyEntityNameDTO, or did I misunderstand the meaning of the DTO and should I just name them MyEntityNameModel? And what should be the proper name for the folder for my DAO classes? Will this simple division be enough for a middle-size project (max ~20 classes/folder) or would it be too confusing? Thanks for any tips from praxis :)
DTO stands for Data Transfer Object. A DTO is a class which is more a data structure than a real class, usually, and which is created to transfer information from one layer to another, often across the network. It's not a model entity.
A DTO is often used
when serializing real model objects is not paractical (because the structure doesn't fit, or because the receiver doesn't have access to Hibernate classes, or because lazy-loaded entities are a problem)
when you want to transfer information that is an aggregation, or a complex view, over your model objects (like data of a statistical report for example)
So naming your entities DTO is not a good idea. DTOs and entities are different things. The Model suffix is also cumbersome. Entities are usually named after what they represent: Customer, Company, Player, Order, etc.
Segregating classes based on their technical role is an often used solution. But it tends not to scale when the application grows. I usually have a first level of segregation based on a functional aspect (like customer management, order management, security, etc.), and then a second level based on technical aspects (service, dao, model, etc.)
UserDAO - interface
UserDAOImpl - implements UserDAO
That is generally what I use. Sometimes the Default prefix like DefaultUserDAO might make more sense if you're creating an interface that you expect others to implement but you're providing the reference implementation.
Most of the time I feel those two can be used interchangeably but in some situations one provides a little more clarity than the other.
There are two conventions that I've seen:
FooDao for the interface and FooDaoImpl for the implementation
IFooDao for the interface and FooDao for the implementation
The former has its roots in CORBA; the latter is a Microsoft COM/.NET convention. (Thanks to Pascal for the correction.)
Hibernate provides the Naming Strategy interface to be implemented by the implementation.
I am listing here few methods.
String classToTableName(String className) – should return the table name for an entity class.
String columnName(String columnName) – handle to alter the column name specified in the mapping document.
String tableName(String tableName) – handle to alter the column name specified in the mapping document.
String propertyToColumnName(String propertyName) – handle to map property name to column name.

Hibernate Inheritance Mapping and Attribute Override

The system I'm working on has a domain object named Order which inherits from AbstractPersistentObject. Now I need to add another domain object named ExternalOrder which has some of the properties of Order but not all. I would like these two objects to be treated polimorphically in certain places. Hence I'm thinking of implementing inheritance mapping.
I've created an AbstractOrder which now extends AbstractPersistentObject and moved the common properties to AbstractOrder. Order and ExternalOrder now extends AbstractOrder.
Since the Order table already has lots of data in the database, I would prefer not to make too many changes to the schema.
If I omit InheritanceType.SINGLE_TABLE, which inheritance strategy would be better for me? I should mention I've to use OnetoMany join in at least one domain Object. The domain object would refer to AbstractOrder and Hibernate would decide at runtime the concrete subclass for this AbstractOrder.
AbstractPersistentObject has #Id and #GeneratedValue(strategy=GenerationType.IDENTITY) for the property id. Is there a way to override this when I implement inheritance? As I understand, GenerationType.IDENTITY is not going to work for certain inheritance choices and I'm not sure how to override this. I've looked into #AttributeOverride but I think it's only useful when you want to override certain #Column values.
1) You don't really have too many options here. Two other inheritance mapping strategies are table per class which won't work for you (as it doesn't support IDENTITY) and joined subclasses which will require you to split your "Orders" table into two (AbstractOrder and Order) plus add another table for ExternalOrder.
2) You can't override attributes on id within inheritance hierarchy. That's just as well, though, table-per-class strategy is definitely not ideal.

Categories