I'm a bit confused about mybatis mapper xml files.
Is it better to have each class in a separate mapper file like below:
<mappers>
<mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
<mapper resource="org/mybatis/builder/BlogMapper.xml"/>
<mapper resource="org/mybatis/builder/PostMapper.xml"/>
</mappers>
Or could I put all my select/insert/update statements for all Classes in one Mapper file:
<mappers>
<mapper resource="org/mybatis/builder/AllInOnerMapper.xml"/>
<mappers>
Right now I use one mapper file for everything, and it works. But I am wondering what the right way is and why?
The best practice is to use one mapper for each table.
One obvious reason is that you can use simpler statement IDs (e.g. selectById
, insert
) instead of verbose IDs (e.g. selectAuthorById
, insertAuthor
).
Another less obvious, but more practical reason is that MyBatis manages cache (2nd level cache, to be precise) based on a statement's namespace (statements in the same mapper share the same namespace).
And the cache is cleared when an insert/update/delete statement defined in the same 'namespace' is executed.
So, if you put Author
and Blog
in the same mapper, for example, cached Author
data is cleared when a Blog
is inserted.
This usually is not the desired behavior.
If the application you develop is relatively small and does not use cache, it should be OK to use one mapper for everything.