简体   繁体   中英

How to organize controller, service and Dao

I've a REST api in Java and the application has three layers:

Controller -> public String storeInfo(JsonModel jsonModel)
Service -> public String store(InfoEntity entity)
Dao -> public String store(InfoEntity entity)

Now, I realized that the "service" didn't have much to do, a part sending back and forward the requests. Then I realized this was because "Dao" and "service" have the same interface.

So, I changed:

Controller -> public String storeInfo(JsonModel jsonModel)
Service -> public String store(JsonModel jsonModel)
Dao -> public String store(InfoEntity entity)

Now, the "service" has more to do. It has to map the input data to the entity to be stored into the database. It gets help from another object for this, but this is its responsability.

However, now I realized the "jsonModel" object has more information than just the one to save. For example there is the username and the password for accessing my API. This is responsability of the controller. Maybe I sent to many information to the "service" I thought.

So, I changed as follow:

Controller -> public String storeInfo(JsonModel jsonModel)
Service -> public String store(TransferObject transferObject)
Dao -> public String store(InfoEntity entity)

But after that I realized that now I have three different objects and that means I have to do two different mappings. A lot of code and it looks overengineered.

How shold I change now, to get it simple and functional?

Your middle option is good, but I'd have a specific Info model which isn't polluted with your app's username and password.

Controller -> public String storeInfo(Info info)
Service -> public String store(Info info)
Dao -> public String store(InfoEntity entity)

Three beans is usually avoidable. Two has worked out best for me in the past - in exactly this line up.

Another approach would be to use the same bean through every layer. But I hate that.
You'd end up with a single Info bean containing hibernate annotations, JSON annotations, validation annotations, multiple constructors, different date formats for different situations, etc. A mess.
I only mention it because it is advocated by many examples online, and used in many books. But only really works if your database, UI and business representations happen to be exactly the same - which, in the real world, is never.

Also, don't forget that your Service should be acting as your transaction boundary: with each of its methods annotated with @Transactional : that's another job for it!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM