6

I'm new to MVC and the different layers architecture and this is what I have currently:

2 models: User, Company

2 service layers: UserService, CompanyService

2 interfaces which abstract the database layer from the service layer: IUser, ICompany

2 database layers: UserDB, CompanyDB

Here's the scenario - a functionality that will update both User and Company table in the database. If update company succeed and update user failed, I will rollback the database for the company. Hence I think it makes sense to do this in 1 method.

If so, where do I put this method that handles 2 models? Is it normal to create UserCompanyDB in the database layer and UserCompanyService in the service layer just for this purpose? And even IUserCompany as well.

Since I'm new to everything, chances are, you may think I'm having some misconceptions on the layers based on my current way of thinking? If so I would like to take this opportunity to rectify it too.

Oh and if it helps, I'm mainly trying to follow the example in this link: https://www.playframework.com/documentation/2.5.x/JavaTest#Unit-testing-models

8

In the MVC design pattern, the Controller part is responsible for translating user actions into modifications of the various Model classes that are involved in a piece of functionality.

There is no one-to-one relation between Controllers, Views and Models. In particular, if a user action requires changes to multiple Model classes, then it is the responsibility of the Controller to arrange that (and also to take care of the corner cases where a failure to update one model must rollback the updates to other models). To make it possible to handle such corner cases, the Unit-of-Work design patterns can be used. With this pattern, database updates from multiple models can be put in a single database transaction.

Creating a model, service and database class for a feature that needs two otherwise separate models is not the way to go.

  • Sorry I think I phrase my question severely wrong for the updating database. Here's the updated version as above: If update company succeed and update user failed, I will rollback the database for the company. Based on this requirement, let's say updating user failed, how do I go about rolling back the company table by simply using conn.rollback() if previously I need to exit the database layer and return to the Controller to arrange updating user? – user3373225 Jan 31 '16 at 17:29
  • 1
    You would usually use the Unit of Work design pattern for that, or alternatively a framework that supports automatic transaction demarcation (eg Spring). – Jules Jan 31 '16 at 17:57
  • @user3373225: I updated the answer – Bart van Ingen Schenau Jan 31 '16 at 18:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.