What is the best way to convert relational to object oriented? - java

Since I learned about RDBMS, I started thinking in the relational model and less in the object oriented. Now I'm having trouble trying to store and query data in Java data structures.
I want to write an application that has entity sets that relate to each other so I made each entity its own class. The attributes for each entity are the instance variables. Okay I think we're good so far. Title and Game are all entities. Game ISA Title so Title should be the parent class and Game should inherit from Title (think of Game as the physical copy and Title as the name of the Game).
I have a set of games in my main class and I can iterate through if I want to find a specific Game. How would I find a specific Title? I don't have a set of titles because Title is inherited so I would assume I should just iterate through games and when I find a name of a title, add it to a set so that I only get unique titles back.
Game is mutable (isBought can change) so is using a Set a bad idea? What is the best way to create Entity sets in Java? Using a Map instead of a set to map an id to an object?

Fixing the object-relational gap is not an easy task. There are ORM (object-relational mapping) frameworks that do that. But they have some learning curve. Hibernate and EclipseLink are two implementations of the ORM standard in Java - JPA (java persistance API).

There is no fundamental gap between relational and OO models. The relational data model is a type system that supports relation types and relational operators (and other types as well). An OO data model is a type system that supports inheritence.
The mistake that people often make when considering these paradigms is to equate types (classes) in OO terms with relations or tuples in the relational model. Date and Darwen call this the First Great Blunder. The reality is much simpler than that. Types are types, in both the relational model and the OO model. The two paradigms are orthogonal and complementary to each other, they are not mutually exclusive.
What the much-hyped OO/RM mismatch really means is that a programmer wishes to implement certain patterns of transformations which his software tools don't easily support. The relational model is not to blame. The software makers are.

Related

Converting database data into objects

I'm building my first real Java application, and I'm confused about following good object-oriented design practices.
My application allows a yoga instructor to design a yoga session. There is a MySQL database with five tables:
a table of yoga poses,
a table for the warmup section of the session
a table for the work section of the session
a table for the restore section of the session
and finally a table containing the various yoga sessions the user has created.
The sessions are composed of sections, and the sections are composed of poses. I purposefully chose to use a database in this design rather than lists or arrays for the purpose of learning how to integrate a database with Java.
Here is my question:
Is it really necessary to make objects out of the poses, sections and sessions?
They are merely data, and they don't have behavior of any kind. The real objects in my application are the windows and tools the user is using to assemble these poses and sections into yoga sessions. It just seems that my code will become unnecessarily inflated and complicated if I force each pose and section and session to be an object. I realize that I may be asking for opinions here, and that is generally discouraged on this forum. But my intent is to understand and follow object-oriented design in what seems to me to be a murky area.
To answer your question, Yes, create objects for each. The main principle of Object oriented programming is having different "types" of Objects and doing stuffs (Behaviors - methods) around them.
I suggest you to look at the concept of ORM. ORM is the process of mapping Objects to their persistent representation, i.e Database tables.
If you go for plain JDBC, you may need to write a lot of native SQLs and code to extract individual column's values from your table. When the complexity of your schema increases, it will get difficult to maintain these queries.
With ORM, you can write simple java programs to get and save data from persistent layers.
You can go through this thread to look at the ORM advantages
Hibernate is a great framework available for Java which does ORM
1) If you use Hibernate or other ORM, you must use POJOs. There's no other way.
2) If you use JDBC directly, for example Spring JDBC, you could use maps (SimpleJdbcTemplate returns maps in many functions etc.), but reading POJO field is much quicker and less error-prone than reading field from map. Maps take also more place in memory.
3) If you are using JSF, you need POJOs with getters and setters, maps could theoretically be used for read-only, but the syntax is going obscure.
Reassuming, there's no good alternative for POJOs in Java for storing datas. In some cases you can use maps, but it's good only when the data structures are dynamic or as temporary solution.

JPA, complex object graphs and Serialisation

I have a "Project" entity/class that includes a number of "complex" fields, eg referenced as interfaces with many various possible implementations. To give an example: an interface Property, with T virtually of any type (as many types as I have implemented).
I use JPA. For those fields I have had no choice but to actually serialize them to store them. Although I have no need to use those objects in my queries, this is obviously leading to some issues, eg maintenance/updates to start with.
I have two questions:
1) is there a "trick" I could consider to keep my database up to date in case I have a "breaking" change in my serialised class (most of the time serialisation changes are handled well)?
2) will moving to JDO help at all? I very little experience with JDO but my understanding is that with JDO, having serialised objects in the tables will never happen (how are changes handled though?).
In support to 2) I must also add that the object graphs I have can be quite complex, possibly involving 10s of tables just to retrieve a full "Project" for instance.
JDO obviously supports persistence of interface fields (but then DataNucleus JPA also allows their persistence, but as vendor extension). Having some interface field being one of any possible type presents problems to RDBMS rather than to JDO as such. The underlying datastore is more your problem (in not being able to adequately mirror your model), and one of the many many other datastores could help you with that. For example DataNucleus JDO/JPA supports GAE/Datastore, Neo4j, MongoDB, HBase, ODF, Excel, etc and simply persists the "id" of the related object in a "column" (or equivalent) in the owning object representation ... so such breaking changes would be much much less than what you have now

Separate data representation for business-logic and database storage

I am writing some hobby project for poker game. My application will store a lot of games in database. I created representation of object Game which uses a lot of other objects like: PlayerHand (basically 2 Card objects as properties, and some utility methods like isSuited(), isPaired(), etc), Actions (describes stakes raisings done by players), Board (describes flop, turn and river cards), etc.
Problem is that for database storage I can describe game in a more compact and efficient way. For instance I can just use integers for each unique hand. Such representation is compact and good for DB, but for other logic implementation I would like to have more fields describing a hand then just one integer. I don't like idea having both representations in one class this just doesn't look right.
Question: what approach can be used for my problem?
The best solution I've come up with is something like MVC pattern. Where Model is my compact database representation and view is my business-logic representations. But again, this doesn't seem right to me, because looks too complex for such a simple task. Are there more elegant approaches or maybe more simple patterns?
MVC is for the entire application, to separate flow control, from presentation, from business logic. What you need is Data Mapper, so you can have domain objects that know nothing about the db. For most applications I usually use both MVC and Data Mapper.
If I was doing it in an 'enterprise-y' way using MVC, I'd have separate object for the DB representation and for the game entity class you will actually use, and a distinct service layer to convert between the two. That way the database mapping is simpler and the conversion is explicit.
Since its a game though I'd probably combine the two and have the conversion done by the DB layer. If you were using Hibernate you could use custom UserTypes to do that hard work, and keep it separate from your model classes.

Should my DAOs (Database Entities) Directly match my UI Objects?

I am trying to figure out best practice for N-Tier application design. When designing the objects my UI needs and those that will be persisted in the DB some of my colleagues are suggesting that the objects be one in the same. This doesn't not feel right to me and I am ultimately looking for some best practice documentation to help me in this decision.
EDIT:
Let me clarify this by saying that the tables (Entity Classes) that are in the DB are identical to the objects used in the UI
I honestly do not understand why I would want to design this way given that other applications may want to interact with my Data Access Layer....or it is just ignorance or lack of understanding on my part.
Any documentation, information you could provide would be greatly appreciated. Just want to better understand these concepts and I am having a hard time finding some good information on the best practice for implementing these patterns (Or it is right in front of me on what I found and I didn't understand what was being outlined).
Thanks,
S
First of all, DAOs and database entities are two very different things.
Now to the question. You're right. The database entities are mapped to a database schema, and this database schema should follow the database design best practices, and be normalized. The UI sometimes dislays exactly the information from a given entity, but often show data that comes from multiple entities, in an aggregate format. Or, to the contrary, they only show a small part of a given entity.
For example, it would make sense for a UI to show a product name, description and price along with the name of its category, along with the number of remaining items in stock, along with the manufacturer of the product. It would make no sense to have a persistent entity containing all those fields.
In general and according to most "best practices" comments, yes, those two layers should be decoupled and there should be separate objects.
BUT: if your mapping would only be a one-to-one-mapping without any further functionality in the non-database-object, why introduce an additional object? So, it depends. (as usual ;-) ).
Don't use additional objects if the introduced overhead is bigger than the gain. And don't couple the two layers if re-usability is a first-class-goal. That may not be the case with some legacy applications, e.g.

Why to use Hibernate Mapping Component?

I am learning hibernate an I came across Hibernate Mapping Component.
Why should we use it if we can have the same pojo class for student and address?
You can. But that doesn't mean you want.
Reason one: you want to model them differently
In objects you want to model something the best possible way. That means one thing are Students and other Addresses. In a future you could have more Address per student, or none, so migration to that model will be easier if you have two differents objects.
Think of it as high cohesion and low coupling (good design patterns). Each class has its meaning, its responsability, its limited range of action. The more isolated classes are, the more punctual changes will be. The more modular your code will be too.
By contrast, in tables you make concessions in order to gain performance and more direct queries. That means you can denormalize your model (like joining students and addresses).
Reason two: legacy models
By example. If you have a legacy single table and want to use two objects, you need this mapping. Or... if your application is already made, based on two objects, but your database is reengineered and you decide one table is better.
One more point is that Address (which is treated as component here) cannot have its own primary key, it uses the primary key of the enclosing Student entity.

Categories