string decoupling and field names - java

I have a number of domain/business objects, which when used in a hibernate criteria are referenced by the field name as a string, for example :
Criteria crit = session.createCriteria(User.class);
Order myOrdering = Order.desc("firstname");
crit.addOrder(myOrdering);
Where firstname is a field/property of User.class.
I could manually create an Enum and store all the strings in there; is there any other way that I am missing and requires less work(I'll probably forget to maintain the Enum).

I'm afraid there is no a good way to do that.
Even if you decide to use reflections, you'll discover the problem only when the query will run.
But there is a little bit better solution how to discover the problem early: if you use the Named Queries (javax.persistence.NamedQueries) you'll get all your queries compiled as soon as your entities are processed by Hibernate, so basically it will happen during the server's start-up. So if some object was changed breaking the query, you'll know about it the next time you start the server and not when the query is actually run.
Hope it helps.

This is one of the things that irritates me about Hibernate.
In any case, I've solved this in the past using one of two mechanisms, either customizing the templates used to generate base classes from Hibernate config files, or interrogating my Hibernate classes for annotations/properties and generating appropriate enums, classes, constants, etc. from that. It's pretty straight-forward.
It adds a step to the build process, but IMO it was exactly what I needed when I did it. (The last few projects I haven't done it, but for large, multi-dev things I really like it.)

Related

Entity/POJO with large number of attributes

We have a Java application which maps some entities to tables using Hibernate.
One entity has gotten very large and contains maybe 30+ fields.
One suggestion is to add a map to this entity consisting of generic 'Attribute' objects which would replace some of the fields.
Would this be bad design and if so what would be a better approach?
Tough it is not impossible, it is unusual to find entities with that many fields. I agree with #Gernot about giving a try to normalization.
Anyway, if you definitely need all of those attributes, go ahead and include them all. It is much better than the Map alternative you suggest, because it'd make your model lose semantic and specific typing.
First you should check if the database schema of the mapped table could be improved, if it contains that many fields. (have a look at Database Normalization)
If this really is the case, a library like Lombok can at least reduce the amount of boilerplate to write (setters, getters, builder...).

JOOQ Metamodel: why is there no Table.rename(String)?

I am dynamically creating and using physical DB tables for which I only have one metamodel object. An example: I have one JOOQ class Customer in my metamodel, but I have CUSTOMER1, CUSTOMER2, etc. at runtime. I'd like to write strongly typed JOOQ queries for these dynamic tables. The following seems to do the trick:
Customer CUSTOMER1 = Customer.rename("CUSTOMER1")
Of course, there's a whole bunch of tables for which I need to do this. Unfortunately, I cannot leverage the rename method generically, because it is not part of the Table<R> interface. Is this an oversight or a deliberate measure against something I am missing?
Is there a robust and elegant way to achieve what I want, i.e. without resorting to reflection?
EDIT: the two tables are never used jointly in the same query. Concrete usage pattern is the following: At any given moment, a DB synonym CUSTOMER will point to one (the active), while the other is being modified (the shadow copy). Once the modification is complete, roles are swapped by pointing the synonym at the other one, and we start over. We do this to minimize "downtime" of heavy reporting result tables.
The answer to your question
The question being in the title:
why is there no Table.rename(String)?
The feature was implemented in jOOQ 3.3 (#2921). The issue reads:
As table renaming is not really a SQL DSL feature, the rename() method should be generated onto generated tables only, instead of being declared in org.jooq.Table
In fact, this argument doesn't really make much sense. There are other "non-DSL" utilities on the DSL types. I don't see why rename() is special. The method should be declared on Table as you suggested. This will be done in jOOQ 3.9 (#5242).
The answer to your problem
From the update of your question, I understand that you don't really need that fine-grained renaming control. jOOQ's out of the box multi-tenancy feature will do. This is called "table mapping" in the manual:
http://www.jooq.org/doc/latest/manual/sql-building/dsl-context/runtime-schema-mapping
For the scope of a Configuration (most fine-grained scope: per-query level), you can rewrite any matching table name as such:
Settings settings = new Settings()
.withRenderMapping(new RenderMapping()
.withSchemata(
new MappedSchema().withInput("MY_SCHEMA")
.withOutput("MY_SCHEMA")
.withTables(
new MappedTable().withInput("CUSTOMER")
.withOutput("CUSTOMER1"))));

What algorithm or pattern to use to check what rows in what tables will be cascade deleted in mysql/pgsql?

So the question - I have a lot of tables in database and almost all of them have on delete cascade. What is the best way to inform user what will be deleted in entire database if he deletes one certain row. What algorithm/patterns should I read? It's desirable with implementation in java. Thank you.
First off, this seems like a wrong design when you consider the fact that the cascade paths through the object graph are known at compile time and you are asking how to construct them, on demand, at runtime. You could build them and store them once.
That said, there probably isn't much reason for a design pattern. Mostly you are going to need Reflection, including the ability to find annotations on either properties or methods.
Then as you navigate the graph, you will look for the target annotations and either add or not add, and of course, if you don't find a cascade, you can stop going down that branch of the graph.
If there were some reason to handle types differently, Visitor would apply, but there isn't. The annotation processing tool from Sun used visitor, but that was for compile time processing.
Probably don't have the ability to do this, but it would be interesting to do it in Java 8 because you could more cleanly separate the navigation code from the test code, by defining a Predicate (as a Lambda) and then just having that be evaluated at each node. Your predicate would simple check for the presence of the Cascade annotation. Sounds like maybe you are not using an ORM so might not have annotations in your code for the cascades, all the more reason to have a separate predicate because then you could have a metadata version that actually looks at the specific database (Postgres), but if you wanted to use it with an ORM, you'd literally be changing a few lines of code.

hibernate workflow

I'm trying to write a program with Hibernate. My domain is now complete and I'm writing the database.
I got confused about what to do. Should I
make my sql tables in classes and let the Hibernate make them
Or create tables in the
database and reverse engineer it and
let the hibernate make my classes?
I heard the first option one from someone and read the second option on the Netbeans site.
Does any one know which approach is correct?
It depends on how you best conceptualize the program you are writing. When I am designing my system I usually think in terms of entities and their relationships to eachother, so for me, I start with my business objects, then write my hibernate mappings and let hibernate create the database.
Other people are able to think better in terms of database tables, in whcih case that approach is best for them. So you gotta decide which one works for you based on your experience.
I believe you can do either, so it's down to preference.
Personally, I write the lot by hand. While Hibernate does a reasonable job of creating a database for you it doesn't do it as well as I can do myself. I'd assume the same goes for the Java classes it produces although I've never used that feature.
With regards to the generated classes (if you went the class generation route) I'm betting every field has a getter/setter whether fields should be read only or not (did somebody say thread safety and mutability) and that you can't add behavior because it gets overridden if you regenerate the classes.
Definitely write the java objects and then add the persistence and let hibernate generate the tables.
If you go the other way you lose the benefit of OOD and all that good stuff.
I'm in favor of writing Java first. It can be a personal preference though.
If you analyse your domain, you will probably find that they are some duplication.
For example, the audit columns (user creator and editor, time created and edited) are often common to most tables.
The id is often a common field.
Look at your domain to see your duplication.
The duplication is an opportunity to reuse.
You could use inheritance, or composition.
Advantages :
less time : You will have much less things to write,
logical : the same logical field would be written once (that would be other be many similar fields)
reuse : in the client code for your entities, you could write reusable code. For example, if all your entities have the same id field called ident because of their superclass, a client code could make the generic call object.getIdent() without having to find out the exact class of the object, so it will be more reusable.

Where do you put your dictionary data?

Let's say I have a set of Countries in my application. I expect this data to change but not very often. In other words, I do not look at this set as an operational data (I would not provide CRUD operations for Country, for example).
That said I have to store this data somewhere. I see two ways to do that:
Database driven. Create and populate a Country table. Provide some sort of DAO to access it (findById() ?). This way client code will have to know Id of a country (which also can be a name or ISO code). On the application side I will have a class Country.
Application driven. Create an Enum where I can list all the Countries known to my system. It will be stored in DB as well, but the difference would be that now client code does not have to have lookup method (findById, findByName, etc) and hardcode Id, names or ISO codes. It will reference particular country directly.
I lean towards second solution for several reasons. How do you do this?
Is this correct to call this 'dictionary data'?
Addendum: One of the main problems here is that if I have a lookup method like findByName("Czechoslovakia") then after 1992 this will return nothing. I do not know how the client code will react on it (after all it sorta expects always get the Country back, because, well, it is a dictionary data). It gets even worse if I have something like findById(ID_CZ). It will be really hard to find all these dependencies.
If I will remove Country.Czechoslovakia from my enum, I will force myself to take care of any dependency on Czechoslovakia.
In some applications I've worked on there has been a single 'Enum' table in the database that contained all of this type of data. It simply consisted of two columns: EnumName and Value, and would be populated like this:
"Country", "Germany"
"Country", "United Kingdom"
"Country", "United States"
"Fruit", "Apple"
"Fruit", "Banana"
"Fruit", "Orange"
This was then read in and cached at the beginning of the application execution. The advantages being that we weren't using dozens of database tables for each distinct enumeration type; and we didn't have to recompile anything if we needed to alter the data.
This could easily be extended to include extra columns, e.g. to specify a default sort order or alternative IDs.
This won't help you, but it depends...
-What are you going to do with those countries ?
Will you store them in other tables in the DB / what will happen with existing data if you add new countries / will other applications access to those datas ?
-Are you going to translate the contry names in several languages ?
-Will the business logic of your application depend on the choosen country ?
-Do you need a Country class ?
etc...
Without more informations I would start with an Enum with a few countries and refactor depending on my needs...
If it's not going to change very often and you can afford to bring the application down to apply updates, I'd place it in a Java enumeration and write my own methods for findById(), findByName() and so on.
Advantages:
Fast - no DB access for invariant data (or caching requirement);
Simple;
Plays nice with refactoring tools.
Disadvantages:
Need to bring down the application to update.
If you place the data in its own jarfile, updating is as simple as updating the jar and restarting the application.
The hardcoding concern can be made to go away either by consumers storing a value of the enumeration itself, or by referencing the ISO code which is unlikely to change for countries...
If you're worried about keeping this enumeration "in synch" with the database, write an integration test that checks exactly that and run it regularly (eg: on your CI machine).
Personally, I've always gone for the database approach, mostly because I'm already storing other information in the database so writing another DAO is easy.
But another approach might be to store it in a properties file in the jar? I've never done it that way in Java, but it seems to be common in iPhone development (something I'm currently learning).
I'd probably have a text file embedded into my jar. I'd load it into memory on start-up (or on first use.) At that point:
It's easy to change (even by someone with no programming knowledge)
It's easy to update even without full redeployment - put just the text file somewhere on the class path
No database access required
EDIT: Okay, if you need to refer to the particular country data from code, then either:
Use the enum approach, which will always mean redeployment
Use the above approach, but keep an enum of country IDs and then have a unit test to make sure that each ID is mapped in the text file. That means you could change the rest of the data without redeployment, and a non-technical person can still update the data without seeing scary code everywhere.
Ultimately it's a case of balancing pros and cons - if the advantages above aren't relevant for you (e.g. there'll always be a coder on hand, and deployment isn't an issue) then an enum makes sense.
One of the advantages of using a database table is you can put foreign key constraints in. That way your referential integrity will always be intact. No need to run integration tests as DanVinton suggested for enums, it will never get out of sync.
I also wouldn't try making a general enum table as saw-lau suggested, mainly because you lose clean foreign key constraints, which is the main advantage of having them in the DB in the first place (might was well stick them in a text file). Databases are good at handling lots of tables. Prefix the table names with "ENUM_" if you want to distinguish them in some fashion.
The app can always load them into a Map as start-up time or when triggered by a reload event.
EDIT: From comments, "Of course I will use foreign key constraints in my DB. But it can be done with or without using enums on app side"
Ah, I missed that bit while reading the second bullet point in your question. However I still say it is better to load them into a Map, mainly based on DRY. Otherwise, when whoever has to maintain it comes to add a new country, they're surely going to update in one place but not the other, and be scratching their heads until they figure out that they needed to update it in two different places. A case of premature optimisation. The performance benefit would be minimal, at the cost of less maintainable code, IMHO.
I'd start off doing the easiest thing possible - an enum. When it comes to the point that countries change almost as frequently as my code, then I'd make the table external so that it can be updated without a rebuild. But note when you make it external you add a whole can of UI, testing and documentation worms.

Categories