Why to use Hibernate Mapping Component? - java

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.

Related

Best practices implementing list of objects in Java

I'm currently working on improving some old uni assignments moving them from serializable files to any other form of storage, mainly SQL Databases.
I understand the concept of relational database design and the similarities with OOP Classes, however, I'm not entirely sure how to approach this issue from an OOP design perspective.
Right now I have a Hotel class with a List of Rooms as property, each Room has a list of Guests as property (full code here)
Back when using files I could mark these classes with the Serializable interface and store the parent object in a single file. But when using relational DB, I store each list as a single table and use separate queries to obtain the corresponding results. Same goes for the add() operation: with databases, I can do something like Guest.add() and add all the required fields directly to the database, whereas with my current design I need to call Room.getGuestList().add() (or a similar approach).
I totally understand that neither of both approaches is ideal, as both classes should be only worried about storing the data and not about the implementation of an add method, but even if I separate this in a single class, shall I still define a List property within each class?
I'm pretty sure I'm missing a design pattern here, but I cannot find the one that would solve this problem or maybe it's just that I've been taught wrong.
Thanks for your answers
Edit: I've decided thanks to the answers provided to transform my implementation following the DAO pattern as explained in this question and the Oracle documentation.
Normally you would have 3 tables: hotels, rooms, guests.
Rooms would have relation to hotel (hotel id) and guest would have relation to room(room id). That's it.
Those relations can be easily reflected in OOP using some sort of ORM. JPA with Hibernate is an excellent example. Check that out. You will be able to get hotel, its rooms and all guests of hotel just like you described without using a single SQL query in your code.

Auditing using Data tables vs Separate Audit tables

I am in the process of designing a new java application which has very strict requirements for auditing. A brief context is here:
I have a complex entity with multiple one to many nested relationships. If any of the field changes, I need to consider it as a new version of the object and all this need to be audited as well. Now I have two options:
1.) Do not do any update operation, just insert a new entity whenever anything changes. This would require me to create all the relational objects (even if they have not been changed) as I do not want to hold references to any previous version objects. My data tables becomes my auditing table as well.
OR
2.) Always do an update operation and maintain the auditing information in separate tables. That would add some more complexity in terms of implementation.
I would like to know if there is a good vs bad practice for any of these two approaches.
Thanks,
-csn
What should define your choice is your insert/update/read patterns for both the "live" data and the audits.
Most commonly these pattern are very different for both kinds.
- Conserning "live" it depends a lot on your application but I can imagine you have significants inserts; significatant updates; lot of reads. Live data also require transactionality and have lot relationship between tables for which you need to keep consistency. They might require fast and complex search. Indexes on many columns
- Audits have lot of inserts; almost no update; few reads. Read, search don't requires complex search (e.g. you only consult audits and sort them by date) and indexes on many columns.
So with increased load and data size you will probably need to split the data and optimize tables for your use cases.

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.

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

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.

DAO design pattern and using it across multiple tables

I'm looking for feedback on the Data Access Object design pattern and using it when you have to access data across multiple tables. It seems like that pattern, which has a DAO for each table along with a Data Transfer Object (DTO) that represents a single row, isn't too useful for when dealing with data from multiple tables. I was thinking about creating a composite DAO and corresponding DTO that would return the result of, let's say performing a join on two tables. This way I can use SQL to grab all the data instead of first grabbing data from one using one DAO and than the second table using the second DAO, and than composing them together in Java.
Is there a better solution? And no, I'm not able to move to Hibernate or another ORM tool at the moment. Just straight JDBC for this project.
I would agree with your approach. My DAOs tend to be aligned more at the object level, rather than from a DB Table perspective. I may manage more than one object through a DAO, but they will very likely be closely related. There is no reason not to have SQL accessing two tables living in one DAO.
And for the record, I have banished the acronym DTO from my vocabulary and code.
Ideally, how you store your data in a database, and then how you access them, should be derived from the nature of the relationship among the domain entities in your domain model. That is, Relational Model should follow from Domain Model. For example, if you have two entities, say, User and Address.
Scenario #1: Address are never accessed independently, they are always an attribute of User.
In this case, Address is a Value Object and User is an Entity, and there are guides on how to store this relationship. One way is to store Address attributes of Address alongside of attributes of User, in a single table. In this case, UserDao will handle both objects.
Scenario #2: Address can be associated to a User, but also can be separate on its own, an entity.
In this case, an approach different from the first one is needed. You may have a separate DAO and table for the Address type.
My point is, that more often this important idea is ignored that Domain Model should be the core of the application, driving other layers.
For instance, if your domain model is properly define and you are well aware of the type of entities you have and the relationship among them, then your persistence (relational tables and their relationships, your DAOs, etc) will evolve as a very logical consequence of what you have in the domain model.
In other words, if you spend some time studying your model, you will be able to trace your problem in determining how to organize your DAOs to a place in the domain model. If you can clearly define the type of the objects and the nature of relationship among them in the domain model, it will, help you resolve your problem in DAL layer.

Categories