My application has about 50 entities that are displayed in grid format in the UI. All 50 entities have CRUD operations. Most of the operations have the standard flow
ie. for get, read entities from repository, convert to DTO and return a list of DTO's.
for create/update/delete - get DTO's - convert to entities, use repository to create/update/delete on DB, return updated DTOs
Mind you that for SOME entities, there are also some entity specific operations that have to be done.
Currently, we have a get/create/update/delete method for all our entities like
getProducts
createProducts
updateProducts
getCustomers
createCustomers
updateCustomers
in each of these methods, we use the Product/Customer repository to perform the CRUD operation AFTER conversion from entity -> dto and vice versa.
I feel there is a lot of code repetition and there must be a way by which we can remove so many of these methods.
Can i use some pattern (COMMAND PATTERN) to get away with code repetition?
Have a look at the Spring Data JPA or here project. It does away with boilerplate code for DAO.
I believe it basically uses AOP to interpret calls like
findByNameandpassword (String name,String passwd)
to do a query based upon the parameters passed in selecting the fields in the method name (only an interface).
Being a spring project it has very minimal requirements for spring libraries.
Basically, you have 2 ways to do this.
First way: Code generation
Write a class that can generate the code given a database schema.
Note that this you will create basic classes for each entity.
If you have custom code (code specific to certain entities) you can put that in subclasses so that it doesn't get overwritten when you regenerate the basic classes.
Object instatiation should be via Factory methods so that the correct subclass is used.
Make sure you add comments in the generated code that clearly states that the code is generated automatically (so that people don't start editing them directly).
Second way: Reflection
This solution, while being more elegant, is also more complex.
Instead of generating one basic class for each entity you have one basic class that can handle any entity. The class would be using reflection to access the DTO:s.
If you have custom code (code specific to certain entities) you can put that in other classes. These other classes would be injected into the generic class.
Using reflection would require a strict naming policy on your DTO:s.
Conclusion
I have been in a project using the first method in a migration project to generate DTO classes for the service interface between the new application server (running java) and the fat clients and it worked quite well. We had more than 100 generated DTO classes. I am aware that what you are attempting is slighty different. Editing database records is a generic problem (all projects need it) but there aren't (m)any frameworks for it.
I have been thinking about creating a generic tool or framework for it but I have never gotten around to it.
Related
I am looking into Spring data and one thing I've noticed is that we're able to perform CRUD operations just by creating an interface which implements the CRUD repository and by default, we're given access to generated queieres to the db via the method name.
I thought whenever we implement an Interface, we need to provide an implementation to the methods. So why don't we override anything when we use an interface which implements from the CrudRepository interface?
One of the goals of Spring Data is to make database access easy, without the need to manually write a lot of boilerplate code.
Traditionally, one of the things developers commonly did when working with a database is write DAOs (database access objects) with methods, where each method would do a specific query. Such methods would typically be boilerplate code - simple, repetitive code that's a lot of work to write and maintain and that doesn't contain any business logic.
When you use Spring Data, all this code is automatically generated for you. The only thing you have to do is specify in a repository interface what query you want to do, and Spring Data then interprets the meaning of the method name to automatically generate the code that does the query for you.
That saves you a lot of time and helps you a great deal to keep your own code concise; it also helps with the prevention of bugs.
The implementation of a Spring Data repository interface is generated automatically at runtime. This isn't done by generating source code which is compiled - behind the scenes Spring Data directly generates the bytecode of the implementation of the interface.
I (think I) just understood the differences between Java Entity, VO, POJO, Javabeans, DAO, DTO, etc, I mean, the theory. Now, I'm trying to understand the implications of the implementations depending on the needs. Who cares if I create a POJO or a JavaBean? At the beginning I will create a POJO if I have no other constraint, until I realise I must make it a Javabean and deal with it's restrictions.
When do you tell yourself: "I need a DTO"? Only for web services or when any client/server call is made? In that case, do you put all the data you need (and the one you think you will need?) in one DTO bunch?
Lastly, in a MVC model, where does each one go? Can I make an entity or a vo in either layer? Where does the DTO go?
Thank you very much
You understood the difference between them, now you need to understand their purpose.
There is a neat definition for each one in this link.
Who cares if I create a POJO or a JavaBean? At the beginning I will create a POJO if I have no other constraint, until I realise I must make it a Javabean and deal with it's restrictions.
You need to think what the purpose of the class is. Is it a standalone class with no annotations that provides functionality but can be isolated (not counting libraries used)? Then it is likely a POJO.
Is it a class that serves as a bridge between layers of your project? Is it annotated? Does it implement some business logic for your project? Then it is a JavaBean.
When do you tell yourself: "I need a DTO"? Only for web services or when any client/server call is made? In that case, do you put all the data you need (and the one you think you will need?) in one DTO bunch?
DTOs are generally used to share information between layers. Their main purpose is isolating Entities so that you can change how your information is persisted from how the information flows through the different beans and controllers in your project.
To know when I need a DTO and when not I follow these rules:
Does the method more than three parameters? Then use a DTO.
Does the method return more than a single parameter? Then use a DTO.
When passing parameters to method calls / from method results: Does each element have more than one type (for Maps you would look at the value)? Then use a Collection of DTOs.
Otherwise use String, int, Long, etc.
Also never mind reusing DTOs even if most of its fields are not used for a specific method, you won't be wasting much memory if it's properly design. On the other hand, don't worry if you need to create new DTOs that share fields with some others, it might be clearer when reviewing your code. Try to find the right balance between too many DTOs and overpopulated DTOs.
Lastly, in a MVC model, where does each one go? Can I make an entity or a vo in either layer? Where does the DTO go?
It depends on how you structure your project. The term layer is a bit open as it can refer to each of the MVC elements and to the Data/Business/Client architecture (when I used the word layer in this answer, I'm talking about the later classification).
It is a good practice to separate each layer in a different project (specially in large projects). This is a common structure I use for enterprise web applications:
ProjectNameDao: Includes database access methods and entities.
ProjectNameBo: Includes all the business logic. Shares information with the other layers by using DTOs. It is, along ProjectNameDao, the Model in a MVC model.
ProjectNameWeb: Includes views and controllers from the MVC model.
ProjectNameDto: Includes all DTOs.
ProjectNameUtils: Shared utils, normally POJOs that hold constant values or provide basic functionality like Date formatting.
This structure needs to be adapted to whatever your requirements are, of course.
This question already has answers here:
How to use DTO in JSF + Spring + Hibernate
(2 answers)
JSF Service Layer
(2 answers)
Closed 7 years ago.
I am developing a java web application and am trying to follow some patterns like dao/dto. At the moment i am thinking about such base architecture layers:
I ran into some questions regarding the layers. The scheme would go as such: DAO takes in DTO and returns objects(entities) from DataBase, Service layer also takes in DTO, uses DAO and does all the required logic with the returned objects. UI Bean, Service, DAO and DTO classes are Entity specific - each entity has its own layers.
Now would i need the UI bean to use in views or would that be an overkill and UI views can directly use service classes as ui beans? If no, why would i need UI bean?
Another question is regarding DTO. I have created entities with all the required properties and as i understand DTO classes are like reflections of Entity classes. So why would i need these DTO classes and if i use them i recon it would require some converting from entity to dto and vice versa. Do i do the converting in Service layer? Would views (for eg. html pages) also display DTO object properties not actual Entities (as in calling #{UIBean.entityProperty})?
First of all, I would use the DTO beans on the front-end part only, but since u already mention UI-beans, i suppose these will do the trick just fine, the facade uses these to pass them to the controller for displaying your web-components.
in between the Service and the facade you map the entities of the backend towards dto-beans.
In this way your front-end will be completely loosely coupled to your backend.
Regarding your 2nd question I would like to point out an exact valable reason why your UI should always use dto or view beans.
You can combine several backend entity-beans into one dto bean for easier processing on the front-end.
In general I keep always in mind DTO's for public acces, eta a web-service exposing it or a web-front end or a swing app, or...
Entity classes only used in dao and service layer never further up.
As rule of thumb try to divide logical layers according to your context. Inspire you of the theory but use it with care. I give you my humble understanding of layer's interest with few examples. This vision is of course not complete but I hope it will help you to answer your questions.
So is it overkill to use UIBean instead of Service DTO ? I would say it depends of your context.
Maybe there are user inputs data inside your UI beans ? You have to validate them with JSR 303 annotations for example. If those annotations have a meaning in this layer they are useless for underneath layers. That's why you will have a UIBean with JSR 303 annotations and a DTOBean without JSR 303 annotations.
But if they are exactly the same why duplicate ? Maybe at UIBean layer a date could be represented as a String type and you want to manipulate Date type instead of String at DTO layer. That's why you need to adapt your data between layers to work with objects that make sense to a particular layer. For example, you could add a BOAdapter (between UIView and Service) and DTOAdapter (between Service and DAO). Those adapters are usefull for transforming your data inside each POJO's format. For example, you could have in your BO(=UIBean) a date expressed inside three strings and you want a Date object for DTO so you transform it inside the BOAdapter:
public class BOAdapter(){
private BOAdapter(){}
public static DTO toDTO(BO objectBO){
DTO objectDTO = new DTO();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-aa");
objectDTO.setDate(df.parse(objectBO.getYear()+"-"+objectBO.getMonth()+"-"+objectBO.getDay());
[...]
}
}
Why I need DTOAdapter ? Maybe you have a database that contains at least two tables Customers and Adresses with an integrity constraint between them. JPA will automatically generate the right code. But do you really need all this code up to UIView ? I mean if the functionnality you are coding needs only the name, surname and date of birth of your customer, their adress is useless. Again that's why you need to adapt your data between layers to work with objects that make sense to a particular layer. In this case you could create a DTO object only with name, surname and date of birth information and create a method inside your DTOadapter to transform your custom DTO into an heavy JPA object to work properly with database.
But I need the whole entity for coding my fonctionnality ? Maybe you need to add validation constraints inside this layer besides JSR 303. So it could be interesting to have DTO classes besides your entity for the same reason as BO objects.
But my entity is big how duplicate it easily ? Try to use a tool to map data (like dozer) automatically. If it is not too big do it manually.
Since you have Spring tag,
I will replace your [DAO] with Spring Data Repository. So most of the time, you write interface method / #query annotation, Spring Data write implement.
Replace DTO with JPA Entity. So I could use some reverse engineering.
[UI Bean] will most be composite of JPA Entity. With some validation
I'm hesitating between two designs of a database project using Hibernate.
Design #1.
(1) Create a general data provider interface, including a set of DAO interfaces and general data container classes. It hides the underneath implementation. A data provider implementation could access data in database, or an XML file, or a service, or something else. The user of a data provider does not to know about it.
(2) Create a database library with Hibernate. This library implements the data provider interface in (1).
The bad thing about Design #1 is that in order to hide the implementation details, I need to create two sets of data container classes. One in the general data provider interface - let's call them DPI-Objects, the other set is used in the database library, exclusively for entity/attribute mapping in Hibernate - let's call them H-Objects. In the DAO implementation, I need to read data from database to create H-Objects (via Hibernate) and then convert H-Objects into DPI-Objects.
Design #2.
Do not create a general data provider interface. Expose H-Objects directly to components that use the database lib. So the user of the database library needs to be aware of Hibernate.
I like design #1 more, but I don't want to create two sets of data container classes. Is that the right way to hide H-Objects and other Hibernate implementation details from the user who uses the database-based data provider?
Are there any drawbacks of Design #2? I will not implement other data provider in the new future, so should I just forget about the data provider interface and use Design #2?
What do you think about this? Thanks for your time!
Hibernate Domain objects are simple POJO so you won't have to create separate DPI-objects, H-Object themselves can be used directly. In DAO you can control whether they come from hibernate or anything else.
I highly recommend reading Chapter 4 "Hitting the database" of Spring in Action, 3rd edition, even if you aren't using Spring in your application. Although my second recommendation would be to use Spring :-)
The DAO pattern is a great way to keep database and ORM logic isolated in the DAO implementation, and you only need one set of entity objects. You can make that happen without Spring, it just takes more work managing your sessions and transactions.
If I understand your post, this is sort of a middle-ground between Design 1 and Design 2. The H-Objects (the entities that Hibernates loads and persists) don't need any Hibernate specific code in them at all. That makes them perfectly acceptable to be used as your DPI-Objects.
I've had arguments with folks in the past who complain that the use of JPA or Hibernate Annotations exposes Hibernate specifics through the DAO interface. I personally take a more pragmatic view, since annotations are just metadata, and don't directly affect the operation of your entity classes.
If you do feel that the annotations expose too much, then you can go old school and use Hibernate Mappings instead. Then your H-Objects are 100% Hibernate free :-)
I recommend design #2. Simply construct domain objects, and let hibernate look after them. Don't write separate classes that are persisted.
Hibernate tries to hide most of the persistence business from you. You may need to add a few small annotations to your entities to help it along. But certainly don't make separate classes.
You may need some very small DAO classes. For example, if you have a Person entity, it would be fairly common practice to have a PersonDAO object that saves a person. Having said that, the code inside the DAO will be very simple, so for a really small project, it may not be worth it. For a large project, it's probably worth keeping your persistence code separate from your business logic, in case you want to use a different persistence technology later.
I've been using JPA on a small application I've been working on. I now have a need to create a data structure that basically extends or encapsulates a graph data structure object. The graph will need to be persisted to the database.
For persistable objects I write myself, it is very easy to extend them and have the extending classes also persist easily. However, I now find myself wanting to use a library of graph related objects (Nodes, edges, simple graphs, directed graphs, etc) in the JGrahpT library. However, the base classes are not defined as persistable JPA objects, so I'm not sure how to get those classes to save into the database.
I have a couple ideas and I'd like some feedback.
Option 1)
Use the decorator design pattern as I go along to add persistence to an extended version of the base class.
Challenges:
-- How do I persist the private fields of a class that are needed for it to be in the correct state? Do I just extend the class add an ID field, and mark it as persistable? How will JPA get the necessary fields from the parent class? (Something like ruby's runtime class modification would be awesome here)
-- There is a class hierarchy (Abstract Graph, Directed Graph, Directed Weighted Graph, etc.). If I extend to get persistence, extending classes still won't have the common parent class. How do I resolve this? (Again, Something like ruby's runtime class modification would be awesome here)
Option 2) Copy paste the entire code base. Modify the source code of each file to make it JPA compatible.
-- obviously this is a lot of work
I'm sure there are other options.. What have you got for me SO???
Do the base classes follow the JavaBeans naming conventions? If so you should be able to map them using the XML syntax of JPA.
This is documented in Chapter 10 of the specification:
The XML descriptor is intended to
serve as both an alternative to and an
overriding mechanism for Java language
metadata annotations.
This XML file is usually called orm.xml. The schema is available online
Your options with JPA annotations seem pretty limited if you're working with a pre-existing library. One alternative would be to use something like Hibernate XML mapping files instead of JPA. You can declare your mappings outside of the classes themselves. Private fields aren't an issue, Hibernate will ignore access modifiers via reflection. However, even this may end up being more trouble than its worth depending on the internal logic of the code (Hibernate's use of special collections and proxies for instance, will get you in hot water if the classes directly access some of their properties instead of using getter methods internally).
On the other hand, I don't see why you'd consider option 2 'a lot of work'. Creating a ORM mapping isn't really a no brainer task no matter how you go about it, and personally I'd consider option 2 probably the least effort approach. You'd probably want to maintain it as a patch file so you could keep up with updates to the library, rather than just forking.