1. Introduction

The Mybatis plugin enables lightweight access to datasources using MyBatis. This plugin does NOT provide domain classes nor dynamic finders like GORM does.

Griffon version: 2.11.0

2. Usage

The following sections describe how you may use this plugin in an project.

2.1. Configuration

This plugin relies on the griffon-datasource-plugin. Please follow the instructions to configure this plugin first.

You must create a configuration file named Mybatis that holds the settings for creating instances of SqlSessionFactory. This file follows the same standard configuration mechanism as the application’s Config file, which means you can define the configuration using

  • a properties file

  • a Java file

  • a Groovy script

The following example shows the default settings needed to connect the default database taking into account that each environment may connect to a different database.

src/main/resources/Mybatis.groovy
sessionFactory {
    // specify any properties from org.apache.ibatis.session.Configuration
    lazyLoadingEnabled = false
}

environments {
    development {
        sessionFactory {
            lazyLoadingEnabled = false
        }
    }
    test {
        sessionFactory {
            lazyLoadingEnabled = false
        }
    }
    production {
        sessionFactory {
            lazyLoadingEnabled = true
        }
    }
}

You may configure multiple named SqlSessionFactories (the default factory is aptly named default) as the following snippet shows

src/main/resources/Mybatis.groovy
sessionFactories {
    internal {
        lazyLoadingEnabled = false
    }
    people {
        lazyLoadingEnabled = false
    }
}

The following properties are optional

Property Type Default Description

connect_on_startup

boolean

false

Establishes a connection to the datasource at the beginning of the Startup phase.

jmx

boolean

true

Expose sessions using JMX.

The plugin’s module registers a MybatisHandler helper class that defines the base contract for accessing a datasource and issue SQL queries to it. This class has the following methods

griffon.plugins.mybatis.MybatisHandler.java
@Nullable
<R> R withSqlSession(@Nonnull MybatisCallback<R> callback)
    throws RuntimeMybatisException;

@Nullable
<R> R withSqlSession(@Nonnull String sessionFactoryName, @Nonnull MybatisCallback<R> callback)
    throws RuntimeMybatisException;

void closeSqlSession();

void closeSqlSession(@Nonnull String sessionFactoryName);

These method are aware of multiple datasources. If no sessionFactoryName is specified when calling them then the default datasource will be selected. You can inject an instance of this class anywhere it’s needed using @Inject. There is one callback you may use with this method: MybatisCallback.

This callback is defined using a functional interface approach, which means you can apply lambda expressions if running with JDK8+ or closures if running Groovy.

griffon.plugins.mybatis.MybatisCallback.java
public interface MybatisCallback<R> {
    R handle(@Nonnull String sessionFactoryName, @Nonnull SqlSession session);
}

2.1.1. Mappers

MyBatis requires a mapper class for each type you’d like to map to a table. The plugin can automatically discover mappers that should be added to a SqlSessionFactory as long as they are annotated with @TypeProviderFor. For example

src/main/groovy/griffon/plugins/mybatis/mappers/PersonMapper.groovy
package griffon.plugins.mybatis.mappers

import griffon.metadata.TypeProviderFor
import griffon.plugins.mybatis.MybatisMapper
import griffon.plugins.mybatis.Person

@TypeProviderFor(MybatisMapper)
interface PersonMapper extends MybatisMapper {
    Person findPersonById(int id)

    int insert(Person person)

    int update(Person person)

    int delete(Person person)

    List<Person> list()
}

Don’t forget mappers require a matching XML file that contains query definitions, such as

src/main/resources/griffon/plugins/mybatis/mappers/PersonMapper.xml
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="griffon.plugins.mybatis.mappers.PersonMapper">
    <select id="findPersonById" parameterType="int" resultType="griffon.plugins.mybatis.Person">
        SELECT * FROM people WHERE id = #{id}
    </select>
    <select id="list" resultType="griffon.plugins.mybatis.Person">
        SELECT * FROM people
    </select>
    <insert id="insert" parameterType="griffon.plugins.mybatis.Person">
        INSERT INTO people (id, name, lastname)
        VALUES (#{id}, #{name}, #Almiray)
    </insert>
    <update id="update" parameterType="griffon.plugins.mybatis.Person">
        UPDATE people SET name = #{name}, lastname = #Almiray
        WHERE id = #{id}
    </update>
    <delete id="delete" parameterType="int">
        DELETE FROM people WHERE id = #{id}
    </delete>
</mapper>

2.1.2. Bootstrap

You may execute arbitrary database calls during connection and disconnection from a SqlSessionFactory. Simply create a class that implements the MybatisBootstrap interface and register it within a module, for example

src/main/java/com/acme/SampleMybatisBootstrap.java
package com.acme;

import griffon.plugins.mybatis.MybatisBootstrap;
import org.apache.ibatis.session.SqlSession;

import javax.annotation.Nonnull;
import javax.inject.Named;

@Named("sample")
public class SampleMybatisBootstrap implements MybatisBootstrap {
    @Override
    public void init(@Nonnull String sessionFactoryName, @Nonnull SqlSession session) {
        // operations after first connection to datasource
    }

    @Override
    public void destroy(@Nonnull String sessionFactoryName, @Nonnull SqlSession session) {
        // operations before disconnecting from the datasource
    }
}
src/main/java/com/acme/ApplicationModule.java
package com.acme;

import griffon.plugins.mybatis.MybatisBootstrap;
import griffon.core.injection.Module;
import org.codehaus.griffon.runtime.core.injection.AbstractModule;
import org.kordamp.jipsy.ServiceProviderFor;

@ServiceProviderFor(Module.class)
public class ApplicationModule extends AbstractModule {
    @Override
    protected void doConfigure() {
        bind(MybatisBootstrap.class)
            .to(SampleMybatisBootstrap.class)
            .asSingleton();
    }
}

2.2. Example

The following is a trivial usage of the MybatisHandler inside a Java service

com.acme.SampleService.java
package com.acme;

import griffon.core.artifact.GriffonService;
import griffon.metadata.ArtifactProviderFor;
import org.codehaus.griffon.runtime.core.artifact.AbstractGriffonService;

import griffon.plugins.mybatis.MybatisHandler;
import griffon.plugins.mybatis.MybatisCallback;
import org.apache.ibatis.session.SqlSession;

import com.acme.mappers.PersonMapper;

import javax.annotation.Nonnull;
import javax.inject.Inject;

@ArtifactProviderFor(GriffonService.class)
public class SampleService extends AbstractGriffonService {
    @Inject
    private MybatisHandler mybatisHandler;

    public String getPersonName(final int id) {
         return mybatisHandler.withSqlSession(new MybatisCallback<String>() {
             public String handle(@Nonnull String sessionFactoryName, @Nonnull SqlSession session) {
                 PersonMapper mapper = session.getMapper(PersonMapper.class);
                 Person person = mapper.findPersonById(id);
                 return person != null ? person.getName() : null;
         });
    }
}

Here’s the Groovy version of it

com.acme.SampleService.groovy
package com.acme

import griffon.core.artifact.GriffonService
import griffon.metadata.ArtifactProviderFor

import griffon.plugins.mybatis.MybatisHandler
import org.apache.ibatis.session.SqlSession

import com.acme.mappers.PersonMapper

import javax.inject.Inject

@ArtifactProviderFor(GriffonService)
class SampleService {
    @Inject
    private MybatisHandler mybatisHandler

    String getPersonName(int id) {
         mybatisHandler.withSqlSession { String sessionFactoryName, SqlSession session ->
             session.getMapper(PersonMapper)?.findPersonById(id)?.name
         }
    }
}

2.3. Events

The following events will be triggered by MybatisHandler

MybatisConnectStart(String sessionFactoryName, Map<String, Object> config)

Triggered before connecting to the datasource.

MybatisConnectEnd(String sessionFactoryName, Map<String, Object> config, SqlSessionFactory factory)

Triggered after connecting to the datasource.

MybatisDisconnectStart(String sessionFactoryName, Map<String, Object> config, SqlSessionFactory factory)

Triggered before disconnecting from the datasource.

MybatisDisconnectEnd(String sessionFactoryName, Map<String, Object> config)

Triggered after disconnecting from the datasource.

DataSource events may be triggered during connection and disconnection from a SqlSessionFactory.

2.4. AST Transformation

You can apply the @MybatisAware AST transformation on any class. This injects the behavior of MybatisHandler into said class. The previous Groovy service example can be rewritten as follows

com.acme.SampleService.groovy
package com.acme

import griffon.core.artifact.GriffonService
import griffon.metadata.ArtifactProviderFor
import griffon.transform.MybatisAware

import org.apache.ibatis.session.SqlSession

import com.acme.mappers.PersonMapper

@MybatisAware
@ArtifactProviderFor(GriffonService)
class SampleService {
    String getPersonName(int id) {
         withSqlSession { String sessionFactoryName, SqlSession session ->
             session.getMapper(PersonMapper)?.findPersonById(id)?.name
         }
    }
}

2.5. DSL Descriptors

This plugin provides DSL descriptors for Intellij IDEA and Eclipse (provided you have the Groovy Eclipse plugin installed). These descriptors are found inside the griffon-mybatis-groovy-compile-2.0.0.jar, with locations

  • dsdl/griffon_mybatis.dsld

  • gdsl/griffon_mybatis.gdsl

3. Build Configuration

3.1. Gradle

You have two options for configuring this plugin: automatic and manual.

3.1.1. Automatic

As long as the project has the org.codehaus.griffon.griffon plugin applied to it you may include the following snippet in build.gradle

dependencies {
    griffon 'org.codehaus.griffon.plugins:griffon-mybatis-plugin:2.0.0'
}

The griffon plugin will take care of the rest given its configuration.

3.1.2. Manual

You will need to configure any of the following blocks depending on your setup

dependencies {
    compile 'org.codehaus.griffon.plugins:griffon-mybatis-core:2.0.0'
}
Compile Only
dependencies {
    compileOnly 'org.codehaus.griffon.plugins:griffon-mybatis-groovy-compile:2.0.0'
}

3.2. Maven

First configure the griffon-mybatis-plugin BOM in your POM file, by placing the following snippet before the <build> element

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.codehaus.griffon.plugins</groupId>
            <artifactId>griffon-mybatis-plugin</artifactId>
            <version>2.0.0</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

Next configure dependencies as required by your particular setup

<dependency>
    <groupId>org.codehaus.griffon.plugins</groupId>
    <artifactId>griffon-mybatis-core</artifactId>
</dependency>
Provided scope
<dependency>
    <groupId>org.codehaus.griffon.plugins</groupId>
    <artifactId>griffon-mybatis-groovy-compile</artifactId>
</dependency>

Don’t forget to configure all -compile dependencies with the maven-surefire-plugin, like so

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <configuration>
        <classpathDependencyExcludes>
            <classpathDependencyExclude>
                org.codehaus.griffon:griffon-mybatis-groovy-compile
            </classpathDependencyExclude>
        </classpathDependencyExcludes>
    </configuration>
</plugin>

4. Modules

The following sections display all bindings per module. Use this information to successfully override a binding on your own modules or to troubleshoot a module binding if the wrong type has been applied by the Griffon runtime.

4.1. Mybatis

Module name: mybatis

Depends on: datasource

bind(ResourceBundle.class)
    .withClassifier(named("mybatis"))
    .toProvider(new ResourceBundleProvider("Mybatis"))
    .asSingleton();

bind(Configuration.class)
    .withClassifier(named("mybatis"))
    .to(DefaultMybatisConfiguration.class)
    .asSingleton();

bind(MybatisStorage.class)
    .to(DefaultMybatisStorage.class)
    .asSingleton();

bind(MybatisFactory.class)
    .to(DefaultMybatisFactory.class)
    .asSingleton();

bind(MybatisHandler.class)
    .to(DefaultMybatisHandler.class)
    .asSingleton();

bind(GriffonAddon.class)
    .to(MybatisAddon.class)
    .asSingleton();