...
MyBatis maps Java objects to SQL result sets. This is different from Hibernate, which maps Java objects to RDBMS entities (tables or views) and generates the SQL for us. With MyBatis, you code SQL statements and map the result sets to Java POJOs. The quirks of the legacy MITSIS database are more readily handled by SQL than by Hibernate's object-relational model.
...
This project uses MyBatis to retrieve the data involved in the Departmental Audit API. This involves getting a list of students who are in a particular department for a given term. For each student, various sets of data are retrieved. For this overview, we'll concentrate on the students and their subjects.
1. The Java POJOs
The simplified object model is:
Gliffy Diagram | ||||
---|---|---|---|---|
|
...
Code Block |
---|
List<DeptAuditUgStudent> getStudentsByDeptAndTermWithSubjects( @Param("deptId") String deptId, @Param("termCode") String termCode); |
Making It All Work
Now that all the pieces are in place, how do we actually retrieve real data from the database?
The sample project uses a Spring-MyBatis module that enables the app to configure the MyBatis system at startup via bean definitions, and provides for dependency injection of the DeptAuditUgStudentMapper interface into classes where it's needed. The sample app's config is in src/main/resources/applicationContext
- Similar to Hibernate, we configure a data source and a MyBatis "SqlSessionFactory".
- We configure a MapperScannerConfigurer bean so that MyBatis knows where to find the mapping xmls.
To exercise all of this setup, there are several JUnit tests in csf.DeptAuditTest - the test that runs the query we've described above is testGetStudentsByDeptAndTermWithSubjects(). The test class is set up to run using Spring's JUnit runner: it loads the applicationContext and injects the DeptAuditUgStudentMapper interface. The test itself simple calls the relevant interface method (getStudentsByDeptAndTermWithSubjects) passing in department ID and term code as parameters. It receives a list of DeptAuditUgStudent objects; each of these object (representing a single student) has its subjects property fully populated with DeptAuditSubject objects.