Why should there be separate MyBatis mappers for each entity?

Ada Melentyeva :

I'm developing a small application that uses MyBatis annotations and mapper interfaces. In all the examples I have seen on MyBatis, including the official website, a separate mapper class is created for each entity. I have two entities, Foo and Bar, and two DBs that each contain these entities. So currently a part of my project structure looks like this:

model
├── bar
│   ├── Bar.java
│   ├── DB1BarMapper.java
│   └── DB2BarMapper.java
└── foo
    ├── Foo.java
    ├── DB1FooMapper.java
    └── DB2FooMapper.java

In my project, Foo and Bar objects are treated more or less the same, but the databases logically have different functions. I'm considering a change to my project design, where I would group mappers by database, then the structure could be simplified like this:

model_new
├── Bar.java
├── Foo.java
├── DB1Mapper.java
└── DB2Mapper.java

Here, the DB mappers would contain methods to access both Foo and Bar entities (and return corresponding POJOs) each.

As far as I understand, this would be valid programming-wise, because mappers are added to database configurations, and because the mappers themselves don't refer to specific objects other than returning them from methods.

I've tried to research whether that's an acceptable practice, but I didn't find any questions or articles on why that is the custom, neither does MyBatis site address this. My best guess is that it's related to the DAO pattern, but I don't see any advantages in using it this way in my case.

So my question is, why is having a separate MyBatis mapper per entity the custom, and is it acceptable design-wise to have a mapper per database connection if, for me, the database matters more than the entity?

Roman Konoval :

There's nothing wrong with having one mapper for multiple entities. Mappers are kind of modules with DAO layer logic. And the same criteria as are applied to splitting other code to modules are applied to mappers namely: things in one mapper should have high cohesion and things in different mappers should have low coupling.

Basically the structure of mappers reflects the structure of the application. As in most often there is a mapper per module with a broad definition of the module. It doesn't necessarily mean mapper per class. It may be mapper per database type if it makes sense to separate the code in the application by the database types.

The reason mapper per entity class is popular because mapper per class is a natural way to split mappers as entity class is a natural module of the application. But this is not always the case and not always the most convenient way to do the split. In many cases it makes sense to have mapper per aggregate that is one mapper for a cluster of the domain objects that can be treated as one unit/module.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=81746&siteId=1