Showing posts with label myBatis. Show all posts
Showing posts with label myBatis. Show all posts

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>
    





Tuesday, September 8, 2015

How to pass multiple parameters to a mybatis xml mapper element

Using mybatis mapper XML files with only one parameter to pass into SQL statements is straightforward.  For example, if you had a select statement that retrieved a record by an id, then you need to:

  • Define an element in the xml mapper file.  i.e. the select element can receive a parameter type of "Long" with name of "logsId" with an id of "getRecordsByLogsId"
  • Define a function in the mapper java file.  i.e. the function name is "getRecordsByLogsId" and takes an Integer parameter named "logsId"
  • You'll notice that the id in the mapper xml file and the function name in the mapper java file match; as well as the parameter name defined in both.  
  • The parameter notaton of #{} tells mybatis to make a prepared statement
Single Parameter XML Mapper:
  <select id="getRecordsByLogsId" parameterType="Long"resultMap="baseResultMap">
    SELECT
          <include refid="base_column_list" />
    FROM vw_cherryshoe
    WHERE logs_id = #{logsId}
  </select>

Mapper Java Class - single parameter - VwCherryShoeMapper.java:
VwCherryShoe getRecordByLogsId(Integer logsId);

I had to create a SQL statement to find all records between a date range for a timestamp with no timestamp column.  I needed  a way to pass multiple parameters to the xml mapper.  To do this you have to do in addition:

  • In the xml mapper file, use a parameter type of "map".  This allows you to pass in multiple parameter names into the map
  • In the mapper java file, use the @Param annotation for the function's parameters

Two parameters XML Mapper:
<select id="getRecordsBySentDateRange" parameterType="map"resultMap="baseResultMap">
    SELECT
          <include refid="base_column_list" />
    FROM vw_cherryshoe
    WHERE sent_date BETWEEN TO_TIMESTAMP(#{fromTimestamp}, 'DD/MM/YYYY HH24:MI:SS')
    AND TO_TIMESTAMP(#{toTimestamp}, 'DD/MM/YYYY HH24:MI:SS')
  </select>

Mapper Java Class - multiple parameter  - VwCherryShoeMapper.java
List<VwCherryShoe> getRecordsBySentDateRange(
@Param("fromTimestamp") String fromTimestamp, @Param("toTimestamp") String toTimestamp);

This worked with Postgresql 9.0.4 and Oracle Database 11g Enterprise Edition Release 11.2.0.2.0.


Monday, July 28, 2014

Accessing Alfresco's Spring datasource

In past articles I've discussed having the need to store custom application data in addition to Alfresco document and metadata storage in Alfresco's Two-Phase commit limitation, or a backup and restore strategy for Alfresco and a custom application.  For another recent project of mine, the custom application data that needed to be stored was so small that we decided to go ahead and store it inside the Alfresco database itself as an additional status table.

Note: A similar version of the example below were tested on:
  • Alfresco 4.1.5 with Windows default Tomcat install with PostGreSQL 
  • Alfresco 4.1.5 with JBoss 7.0.0 install with Oracle
High Level Steps:
  1. Created a maven database module using mybatis for persistence.  This article helped immensely when setting this up.
    • Included the CherryShoeStatusDao class, mybatis domain classes, mapper classes, and mapper xml files
    • The key to accessing Alfresco's spring datasource is to reference it as "defaultDataSource" in the alfresco-custom-database spring configuration file's datasource bean.  This is because the alfresco datasource is defined in core-services-context.xml with that spring bean id.
      <!-- Alfresco's DataSource is obtained via a bean called "defaultDataSource" which is a org.apache.commons.dbcp.BasicDataSource, it's defined in WEB-INF/classes/alfresco/core-services-context.xml, simulating it here -->
      
      <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
      
      <property name="dataSource" ref="defaultDataSource" />
      </bean>
    • Necessary dependencies included (versions were controlled by the parent pom so not shown here):
      <dependency>
       <groupId>org.mybatis</groupId>
       <artifactId>mybatis-spring</artifactId>
      </dependency>
      <dependency>
       <groupId>log4j</groupId>
       <artifactId>log4j</artifactId>
      </dependency>
      <dependency>
       <groupId>cglib</groupId>
       <artifactId>cglib</artifactId>
      </dependency>
      <dependency>
       <groupId>com.google.guava</groupId>
       <artifactId>guava</artifactId>
      </dependency>
        
  2. Add the database module as a module dependency to the alfresco amp module pom:
        <dependency>
             <groupId>com.cherryshoe</groupId>
            <artifactId>alfresco-custom-database</artifactId>
        </dependency>
    
  3. Import the alfresco-custom-database.xml spring file to module-context.xml so it will be recognized by alfresco. The classpath should be from the root of the jar file created (/spring/spring-alfresco-custom-database.xml). Import it before any other imports that depend on it.
    <!--  alfresco-custom-database spring config file -->
    <import resource="classpath:/spring/spring-alfresco-custom-database.xml" />
    
    ... other imports
  4. cherryShoeStatusDao will already be available as a spring bean after step 3 is done because of component scanning in the custom database module spring configuration file.  It can be referenced from other beans in alfresco's service-context.xml custom spring config file.  i.e. a CustomAlfrescoService can now access CherryShoeStatusDao to insert and update Status table values.
           
    <bean id="CustomAlfrescoService" class="com.cherryshoe.services.impl.CustomAlfrescoServiceImpl" >
        <property name="cherryShoeStatusDao" ref="cherryShoeStatusDao" />
    </bean>

Reference Only
Detailed Files: