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

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.

Related

GreenDao and entity inheritance

My task is to make disk cache on Android OS for my application (it is some sort of messenger). I'd like to store messages in database, but have met a problem of storing different types of messages (currently 5 types of messages each type have it's own fields and they all extends base class)
GreenDao documentation says:
Note: currently it’s impossible to have another entity as a super class (there are no polymorphic queries either)
I am planing to have entity which almost 1 to 1 to base class, except one column - raw binary or json data in which every child class can write anything it need.
My questions are:
GreenDao is good solution in such case? Is there any solutions which allow not to worry about inheritance - and how much did they cost in terms of efficiency.
How to "serialize" data to such field (what method I should override or where I should put my code which will do all necessary things
How to give GreenDao correct constructor to "deserialize" Json or binary to correct class instance
Should I use reflection - or just switch/case for finding correct constructor (only 5 types of constructors are possible) - is reflection how much will reflection "cost" in such case?
If you really need inheritance greendao is not the r I get choice, since it doesn't support it. But I think you can go without inheritance:
You can design an entity with a discriminator column (messagetype) and a binary or text column (data). Then you can use an abstract factory to create desired objects from data depending of the messagetype.
If the conversion is complex, I'd put it in a separate class, otherwise I'd put it as a method in the keep section.
Be aware that this design may slow you down, if you really have a lot of messages, since separate tables would reduce index sizes.
Talking about indexes: if you want to access a message through some property of your data column later on, you are screwed since you can't put an index on it.

Implementing the Strategy Pattern against generated pojos

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.

Best Practice: String converting batch in instantiating class or capsulated in every instantiated class

One class Customers instantiates many other classes (e.g. CustomersFromMysql, CustomersFromPostgeSQL) that all query databases which give back customer names. Now these customer names come back as for example name = "John Doe", what my Customers class needs though is more than name, it also needs nameNoSpace = "JohnDoe" and nameInvertedComma = "Doe, John" for example.
I would programm a helper class Converter which has methods like invertName(name) and removeComma(name). Would I instantiate the converter in every class that queries the database (CustomersFromMysql, CustomersFromPostgeSQL) to give back all required variables or would I instantiate the Converter in the instantiating class Customers so when I get back results I iterate through my list and batch convert them?
Of course both works, but what is the way to go?
You should remember separation of duties in such cases. The database related classes should handle only the database specific aspects. Performing operations (calculations) on the retrieved data should be treated as business logic. So, if your Customers class already has some logic in it, it would be the perfect place for putting in the conversion routines. Neverthess, it really depends on where you think your logic belongs to.
It may also make sense to apply some naming conventions. In general you can distinguish between at least the different kinds of classes in case like the one you desribed in your question:
Data Access Objects (DAO); perform database opertions (your SQL classes)
Data Transfer Objects (DTO) or entities; represent the structure of your business objects
Business Logic; retrieve the DTO by using DAOs, perform some logic according to your requirements, push the DTO back into the database by using the DAOs again

On abstract classes in Java and Hibernate annotations

I am planing to create an application relying on DB using Hibernate. I will have some similar classes like teacher and student and so on. In DB they will have some fields with similar names. So I wonder If I can create a class Human with annotations for standard fields like Name, SName and so on so to just extend that class in teacher student and so on. Will it work? Does any one use it in such way?
I would suggest that teacher and student are not subclasses of human, but rather are roles that a human can play. If you make them subclasses then you are effectively saying that teacher can never be a student and vice versa.
Also, if one goes from being a student to teacher (or vice versa) then you lose any associations and history for that object.
Consider roles instead. Consider composition and delegation instead of inheritance in this example.
Take a look at Peter Coad's book: Java Design for more on this.
Also, you do want to think about the table implementation if you do decide to use inheritance: single table (with null cols for the subtype attribs) separate table or single table for super class and separate tables for subclasses.
Hibernate has extensive support for different scenarios involving inheritance and polymorphism. See the documentation
http://docs.jboss.org/hibernate/stable/core/reference/en/html/inheritance.html
The short answer is, yes you can do exactly what you want -- create a base class with fields common to subclasses. How hard/involved it is depends on how you structure the tables.

Should there be 2 datatables for a Parent and Child class in Java?

I have two classes Parent and Child.
class Child extends Parent {
private String extraField1;
private String extraField2;
...
}
Child class has 2 extra fields extraField1 and extraField2.
Q1. Should I make two diff. tables in the databse: one for Child and other for Parent?
or
Q1. Should I add two columns in the Parent table (each column for one extra field) and store the Child in the Parent table.
=============================== EDITED =======================================
Yes, Child and Parent are classes in the same hierarchy.
Should there be 2 datatables for a Parent and Child class in Java?
There is no universal answer to this question. There are actually several techniques to map an inheritance hierarchy into a relational database and they all have advantages and disadvantages. Choosing one or the other depends on your context.
Scott Ambler details the various approaches in the section 2. Mapping Inheritance Structures of his famous paper Mapping Objects to Relational Databases: O/R Mapping In Detail that I'm quoting below:
(...) In this
section you’ll see that there are
three primary solutions for mapping
inheritance into a relational
database, and a fourth supplementary
technique that goes beyond inheritance
mapping. These techniques are:
Map the entire class hierarchy to a single table
Map each concrete class to its own table
Map each class to its own table
Map the classes into a generic table structure
For a full comparison (with advantages, disadvantages and a recommendation on when to use), have a look at the section 2.6 Comparing The Strategies.
I can't do a better job than him so there is no point at paraphrasing him, just refer to the original paper.
Patterns of Enterprice Application Architecture covers this as well in its chapters on Single-table inheritance, Class-table inheritance, and Concrete-table inheritance.
The coverage is similar to what Pascal has said. There's no One True Way, but the book does give you a good breakdown of costs and benefits, e.g.
The strengths of Concrete Table Inheritance are:
Each table is self-contained and has no irrelevant fields. As a result
it makes good sense when used by other
applications that aren't using the
objects.
There are no joins to do when reading the data from the concrete
mappers.
Each table is accessed only when that class is accessed, which can
spread the access load.
The weaknesses of Concrete Table Inheritance are:
Primary keys can be difficult to handle.
You can't enforce database relationships to abstract classes.
If the fields on the domain classes are pushed up or down the hierarchy,
you have to alter the table
definitions. You don't have to do as
much alteration as with Class Table
Inheritance (285), but you can't
ignore this as you can with Single
Table Inheritance (278).
If a superclass field changes, you need to change each table that has
this field because the superclass
fields are duplicated across the
tables.
A find on the superclass forces you to check all the tables, which leads
to multiple database accesses (or a
weird join).

Categories