Friday, October 23, 2015

Manual and Annotation based myBatis-Spring Configuration

Here are two essentially same examples of configuring myBatis-Spring with annotations or using manual configuration, using a custom maven modules.  You can look at the details on github (https://github.com/cherryshoe/cherryshoe-examples/tree/master/mybatis-spring), but the highlights are called out below.

Directory Structure
/*-custom-database     <-- Maven pom.xml
  /src
    /main/
      /java                   <-- Java code
        /com/
          /cherryshoe
            /database
                          /dao            <-- Dao logic
              /domain         <-- Business domain objects
              /persistence    <-- Mapper interfaces
      /resources              <-- Non java files
        /com
          /cherryshoe
            /database
              /persistence    <-- Mapper XML files
                /spring               <-- Spring files
    /test/
      /java                   <-- Java code
        /com/
          /cherryshoe
            /database
                          /dao            <-- Dao logic tests
      /resources              <-- Non java files
        /database             <-- Sql in memory files (H2)

        /spring               <-- Spring test files

Differences with the manual configuration method:
LogsDao.java
  • No @Service for LogsDao class
  • No @Autowired for LogsMapper
  • Add in setter method for LogsMapper
    public void setVwDocManCtsMapper(VwDocManCtsMapper vwDocManCtsMapper) {
        this.vwDocManCtsMapper = vwDocManCtsMapper;
    }
    
spring-custom-database.xml and spring-custom-database-test.xml
  • No <context:component-scan> to enable component scanning
  • No <context:annotation-config> to enable use of autowiring
  • No org.mybatis.spring.mapper.MapperScannerConfigurer to scan for mappers and let them be autowired
  • Add in spring beans for the LogsMapper and LogsDao classes.  These can then also be used when importing this module into another maven module.
    <bean id="logsMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
      <property name="mapperInterface" value="com.cherryshoe.database.persistence.LogsMapper" />
      <property name="sqlSessionFactory" ref="sqlSessionFactory" />
    </bean>
    
    <bean id="logsDao" class="com.cherryshoe.database.dao.LogsDao" >
        <property name="logsMapper" ref="logsMapper" />
    </bean>
    





No comments:

Post a Comment

I appreciate your time in leaving a comment!