--- /dev/null
+Create database with createdatabase.sh script.
+
+export M2_HOME=/opt/maven/apache-maven-2.2.1
+PATH=$M2_HOME/bin:$PATH
+
+mvn clean install -Dmaven.test.skip=true
+mvn dependency:sources
+mvn dependency:resolve -Dclassifier=javadoc
--- /dev/null
+#!/bin/bash
+mysql -uroot -proot -e "CREATE DATABASE mybatis_example DEFAULT CHARACTER SET utf8"
+
+mysql -uroot -proot -e "USE mybatis_example; CREATE TABLE ad (id SERIAL, company_id BIGINT, company_categ_id BIGINT, ad_gps BLOB, ad_mobile_image varchar(255), created_at TIMESTAMP NOT NULL, updated_at TIMESTAMP NOT NULL, PRIMARY KEY (id)) ENGINE=InnoDB, DEFAULT CHARSET=utf8, COLLATE=utf8_unicode_ci"
+
+# Por alguna extraña razon no pude poner el id de esta tabla como serial y no tiene ahora este id autoincrement
+# Daba un error raro diciendo que no podia haber 2 claves con autoincrement en la misma tabla. Pero sí se puede...
+# debo estar haciendo algo mal... :(
+mysql -uroot -proot -e "USE mybatis_example; CREATE TABLE ad_description (id BIGINT(20) UNSIGNED NOT NULL, laguage_id BIGINT NOT NULL, ad_id SERIAL NOT NULL, ad_name VARCHAR(255) NOT NULL, ad_description LONGTEXT, ad_mobile_text VARCHAR(500) NOT NULL, ad_link VARCHAR(3000) NOT NULL, PRIMARY KEY (id), INDEX(ad_id), FOREIGN KEY (ad_id) REFERENCES ad (id) ON DELETE CASCADE) ENGINE=InnoDB, DEFAULT CHARSET=utf8, COLLATE=utf8_unicode_ci"
--- /dev/null
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>de.example.mybatis</groupId>
+ <artifactId>mybatis-spring-example</artifactId>
+ <packaging>jar</packaging>
+ <version>1.0-SNAPSHOT</version>
+ <name>mybatis-spring-example</name>
+ <url>http://gumartinm.name</url>
+ <properties>
+ <mybatis.generator.outputdirectory>${project.build.directory}/generated-sources/mybatis-generator/</mybatis.generator.outputdirectory>
+ </properties>
+ <dependencies>
+ <dependency>
+ <groupId>org.mybatis</groupId>
+ <artifactId>mybatis-spring</artifactId>
+ <version>1.2.0</version>
+ </dependency>
+ <dependency>
+ <groupId>org.mybatis</groupId>
+ <artifactId>mybatis</artifactId>
+ <version>3.2.2</version>
+ </dependency>
+ <dependency>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-context</artifactId>
+ <version>3.2.4.RELEASE</version>
+ </dependency>
+ <dependency>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-jdbc</artifactId>
+ <version>3.2.4.RELEASE</version>
+ </dependency>
+ <dependency>
+ <groupId>com.mchange</groupId>
+ <artifactId>c3p0</artifactId>
+ <version>0.9.2.1</version>
+ </dependency>
+ <dependency>
+ <groupId>mysql</groupId>
+ <artifactId>mysql-connector-java</artifactId>
+ <version>5.1.9</version>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ <version>1.7.5</version>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-log4j12</artifactId>
+ <version>1.7.5</version>
+ </dependency>
+ <dependency>
+ <groupId>cglib</groupId>
+ <artifactId>cglib</artifactId>
+ <version>2.2.2</version>
+ </dependency>
+ </dependencies>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <version>2.0.2</version>
+ <configuration>
+ <source>1.6</source>
+ <target>1.6</target>
+ <encoding>${project.build.sourceEncoding}</encoding>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-resources-plugin</artifactId>
+ <version>2.6</version>
+ <configuration>
+ <encoding>${project.build.sourceEncoding}</encoding>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.mybatis.generator</groupId>
+ <artifactId>mybatis-generator-maven-plugin</artifactId>
+ <version>1.3.2</version>
+ <executions>
+ <execution>
+ <id>Generate MyBatis Artifacts</id>
+ <goals>
+ <goal>generate</goal>
+ </goals>
+ </execution>
+ </executions>
+ <configuration>
+ <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
+ <jdbcDriver>com.mysql.jdbc.Driver</jdbcDriver>
+ <jdbcPassword>root</jdbcPassword>
+ <jdbcURL>jdbc:mysql://localhost:3306/mybatis_example</jdbcURL>
+ <jdbcUserId>root</jdbcUserId>
+ <outputDirectory>${mybatis.generator.outputdirectory}</outputDirectory>
+ <overwrite>true</overwrite>
+ <verbose>true</verbose>
+ </configuration>
+ </plugin>
+ <!-- Required to work with m2e plugin for Eclipse (there is an available connector for this plugin but no for mybatis-generator-maven-plugin) -->
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>build-helper-maven-plugin</artifactId>
+ <version>1.8</version>
+ <executions>
+ <execution>
+ <id>add-source</id>
+ <phase>generate-sources</phase>
+ <goals>
+ <goal>add-source</goal>
+ </goals>
+ <configuration>
+ <sources>
+ <source>${mybatis.generator.outputdirectory}</source>
+ </sources>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+</project>
--- /dev/null
+package de.example.mybatis.spring;
+
+import org.apache.log4j.Logger;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.support.ClassPathXmlApplicationContext;
+
+
+/**
+ * Spring context locator.
+ *
+ */
+public final class SpringContextLocator {
+ private static final Logger logger = Logger.getLogger(SpringContextLocator.class);
+
+ /** Spring ApplicationContext **/
+ private final ApplicationContext context;
+
+ /** Spring Context **/
+ private static final String SPRING_CONFIG_CONTEXT="spring-config.xml";
+
+
+ /**
+ * Private constructor. Singleton pattern.
+ */
+ private SpringContextLocator() {
+ final String[] factoryFiles = new String[] { SPRING_CONFIG_CONTEXT };
+
+ logger.info("Loading context files " + SpringContextLocator.SPRING_CONFIG_CONTEXT);
+
+ this.context = new ClassPathXmlApplicationContext(factoryFiles);
+
+ logger.info("The context has been loaded successfully!! ");
+ }
+
+ /**
+ * SingletonHolder Thread-safety. To use an Enum class (see Effective Java
+ * Second Edition) if we need serialization and thread-safety.
+ */
+ private static class SingletonHolder {
+ public static final SpringContextLocator INSTANCE = new SpringContextLocator();
+ }
+
+ /**
+ * Return singleton instance. Thread-safety.
+ *
+ * @return Singleton instance.
+ */
+ public static SpringContextLocator getInstance() {
+ return SingletonHolder.INSTANCE;
+ }
+
+ /**
+ * Return bean from application context.
+ *
+ * @param beanId
+ * Bean's id.
+ * @return The bean instance.
+ */
+ public Object getBean(final String beanId) {
+ return this.context.getBean(beanId);
+ }
+}
--- /dev/null
+package de.example.mybatis.spring;
+
+import org.apache.log4j.Logger;
+
+import de.example.mybatis.spring.service.ExampleService;
+
+public class TestMain {
+ private static final Logger logger = Logger.getLogger(TestMain.class);
+
+ public static void main(final String[] args) {
+
+ logger.info("Starting application");
+
+ final ExampleService exampleService = (ExampleService) SpringContextLocator
+ .getInstance().getBean("exampleService");
+
+ exampleService.getAdsByCriteria();
+ }
+
+}
--- /dev/null
+package de.example.mybatis.spring.service;
+
+import java.io.UnsupportedEncodingException;
+import java.util.Date;
+import java.util.List;
+
+import org.apache.log4j.Logger;
+import org.springframework.transaction.annotation.Transactional;
+
+import de.example.mybatis.model.Ad;
+import de.example.mybatis.model.AdCriteria;
+import de.example.mybatis.repository.mapper.AdMapper;
+
+public class ExampleService {
+ private static final Logger logger = Logger.getLogger(ExampleService.class);
+
+ private AdMapper adMapper;
+
+ public void setAdMapper(final AdMapper adMapper) {
+ this.adMapper = adMapper;
+ }
+
+ @Transactional /**There is not inserts so this is useless, anyhow this is just an example**/
+ public void getAdsByCriteria() {
+ logger.info("Using criteria");
+
+ final AdCriteria adCriteria = new AdCriteria();
+
+ adCriteria.or().andAdMobileImageEqualTo("mobileImage.jpg")
+ .andCreatedAtNotEqualTo(new Date());
+
+ adCriteria.or().andAdMobileImageNotEqualTo("noMobileImage.jpg")
+ .andAdMobileImageIsNotNull();
+
+ // where (ad_mobile_image = "mobileImage.jpg" and created_at <> Now())
+ // or (ad_mobile_image <> "noMobileImage.jpg" and ad_mobile_image is not null)
+
+ final List<Ad> adLists = this.adMapper.selectByExampleWithBLOBs(adCriteria);
+ for (final Ad ad : adLists) {
+ logger.info("Ad id: " + ad.getId());
+ if (ad.getAdGps() != null) {
+ try {
+ logger.info("Ad GPS: " + new String(ad.getAdGps(), "UTF-8"));
+ } catch (final UnsupportedEncodingException e) {
+ logger.error("Encoding error", e);
+ }
+ }
+ logger.info("Ad mobileImage: " + ad.getAdMobileImage());
+ logger.info("Ad companyCategId: " + ad.getCompanyCategId());
+ logger.info("Ad companyId: " + ad.getCompanyId());
+ logger.info("Ad createdAt: " + ad.getCreatedAt());
+ logger.info("Ad updatedAt: " + ad.getUpdatedAt());
+ logger.info("\n");
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="UTF-8" ?>
+<!DOCTYPE configuration
+ PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
+ "http://mybatis.org/dtd/mybatis-3-config.dtd">
+
+<configuration>
+<settings>
+ <setting name="cacheEnabled" value="false"/>
+ <setting name="lazyLoadingEnabled" value="false"/>
+ <setting name="aggressiveLazyLoading" value="false"/>
+ <setting name="multipleResultSetsEnabled" value="true"/>
+ <setting name="useColumnLabel" value="false"/>
+ <setting name="useGeneratedKeys" value="false"/>
+ <setting name="autoMappingBehavior" value="PARTIAL"/>
+ <setting name="defaultExecutorType" value="SIMPLE"/>
+ <setting name="defaultStatementTimeout" value="5"/>
+ <setting name="safeRowBoundsEnabled" value="false"/>
+ <setting name="mapUnderscoreToCamelCase" value="false"/>
+ <setting name="localCacheScope" value="SESSION"/>
+ <setting name="jdbcTypeForNull" value="OTHER"/>
+ <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
+ <setting name="logPrefix" value="mybatislogger"/>
+ <setting name="logImpl" value="LOG4J"/>
+ <setting name="proxyFactory" value="CGLIB"/>
+ </settings>
+</configuration>
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE generatorConfiguration
+ PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
+ "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
+
+<generatorConfiguration>
+ <!--
+ user.home property is not working with maven 2.2.1
+ <classPathEntry location="${user.home}/.m2/repository/mysql/mysql-connector-java/5.1.9/mysql-connector-java-5.1.9.jar" />
+ -->
+ <classPathEntry location="/home/gustavo/.m2/repository/mysql/mysql-connector-java/5.1.9/mysql-connector-java-5.1.9.jar" />
+
+ <context id="MySQLTables" targetRuntime="MyBatis3">
+
+ <plugin type="org.mybatis.generator.plugins.RenameExampleClassPlugin">
+ <property name="searchString" value="Example$"/>
+ <property name="replaceString" value="Criteria"/>
+ </plugin>
+
+ <!-- This can be useful in paging applications -->
+ <plugin type="org.mybatis.generator.plugins.RowBoundsPlugin">
+ </plugin>
+
+ <commentGenerator>
+ <property name="suppressAllComments" value="false" />
+ <property name="suppressDate" value="false" />
+ </commentGenerator>
+
+ <!--
+ If you are dropping like me (by means of some firewall) IPV6 connections and you feel
+ during the first MySLQ connection as if there is a huge lag and you are using
+ *NIX, you could use this system property -Djava.net.preferIPv4Stack=true
+ in order to stop using IPV6 from JVM.
+ -->
+ <jdbcConnection driverClass="com.mysql.jdbc.Driver"
+ connectionURL="jdbc:mysql://localhost:3306/mybatis_example?characterEncoding=UTF-8" userId="root" password="root">
+ </jdbcConnection>
+
+ <javaTypeResolver>
+ <property name="forceBigDecimals" value="false" />
+ </javaTypeResolver>
+
+ <javaModelGenerator targetPackage="de.example.mybatis.model" targetProject="MAVEN">
+ <!--property name="constructorBased" value="true" />
+ <property name="immutable" value="true" /-->
+ <property name="enableSubPackages" value="true" />
+ <property name="trimStrings" value="false" />
+ </javaModelGenerator>
+
+ <sqlMapGenerator targetPackage="de.example.mybatis.repository.mapper" targetProject="MAVEN">
+ <property name="enableSubPackages" value="true" />
+ </sqlMapGenerator>
+
+ <javaClientGenerator type="XMLMAPPER" targetPackage="de.example.mybatis.repository.mapper"
+ targetProject="MAVEN">
+ <property name="enableSubPackages" value="true" />
+ </javaClientGenerator>
+
+ <table schema="mybatis_example" tableName="ad" domainObjectName="Ad">
+ <property name="useActualColumnNames" value="false" />
+ <property name="ignoreQualifiersAtRuntime" value="true" />
+ <generatedKey column="id" sqlStatement="MySql" identity="false" type="pre" />
+ </table>
+ <table schema="mybatis_example" tableName="ad_description" domainObjectName="AdDescription">
+ <property name="useActualColumnNames" value="false" />
+ <property name="ignoreQualifiersAtRuntime" value="true" />
+ <generatedKey column="id" sqlStatement="MySql" identity="false" type="pre" />
+ </table>
+ </context>
+</generatorConfiguration>
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
+<log4j:configuration>
+ <appender name="stdout" class="org.apache.log4j.ConsoleAppender">
+ <layout class="org.apache.log4j.PatternLayout">
+ <param name="ConversionPattern" value="%d{ABSOLUTE} %5p %c{1}:%L %m%n"/>
+ </layout>
+ </appender>
+ <root>
+ <priority value="debug"></priority>
+ <appender-ref ref="stdout"/>
+ </root>
+</log4j:configuration>
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<beans xmlns="http://www.springframework.org/schema/beans"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:context="http://www.springframework.org/schema/context"
+ xmlns:tx="http://www.springframework.org/schema/tx"
+ xmlns:aop="http://www.springframework.org/schema/aop"
+ xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
+ xsi:schemaLocation="http://www.springframework.org/schema/beans
+ http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
+ http://www.springframework.org/schema/context
+ http://www.springframework.org/schema/context/spring-context-3.2.xsd
+ http://www.springframework.org/schema/tx
+ http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
+ http://www.springframework.org/schema/aop
+ http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
+ http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd">
+
+
+ <!-- There is no need to register all your mappers one by one. Instead, you can let MyBatis-Spring scan your classpath for them. -->
+ <mybatis:scan base-package="de.example.mybatis.repository.mapper" />
+
+ <!-- enable the configuration of transactional behavior based on annotations -->
+ <tx:annotation-driven transaction-manager="transactionManager"/>
+
+ <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
+ <property name="user" value="root"/>
+ <property name="password" value="root"/>
+ <property name="driverClass" value="com.mysql.jdbc.Driver"/>
+ <!--
+ If you are dropping like me (by means of some firewall) IPV6 connections and you feel
+ during the first MySLQ connection as if there is a huge lag and you are using
+ *NIX, you could use this system property -Djava.net.preferIPv4Stack=true
+ in order to stop using IPV6 from JVM.
+ -->
+ <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mybatis_example?autoReconnect=true&characterEncoding=UTF-8"/>
+ <property name="initialPoolSize" value="5"/>
+ <property name="maxPoolSize" value="20"/>
+ <property name="minPoolSize" value="10"/>
+ <property name="acquireIncrement" value="1"/>
+ <property name="acquireRetryAttempts" value="5"/>
+ <property name="acquireRetryDelay" value="1000"/>
+ <property name="automaticTestTable" value="con_test"/>
+ <property name="checkoutTimeout" value="5000"/>
+ </bean>
+
+ <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
+ <property name="dataSource" ref="dataSource"/>
+ </bean>
+
+ <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
+ <property name="dataSource" ref="dataSource" />
+ <property name="configLocation" value="classpath:config/mybatis-config.xml" />
+ </bean>
+
+ <!--
+ The <mybatis:scan/> XML element will search for mappers in a very similar way than the
+ Spring built-in element <context:component-scan/> searches for beans.
+
+ The base-package attribute lets you set the base package for your mapper interface files.
+ You can set more than one package by using a semicolon or comma as a separator. Mappers
+ will be searched for recursively starting in the specified package(s).
+
+ Notice that there is no need to specify a SqlSessionFactory or SqlSessionTemplate as an
+ attribute in the <mybatis:scan/> element because it will create MapperFactoryBeans that can
+ be autowired. But if you are using more than one DataSource autowire may not work for you.
+ In this case you can use the factory-ref or template-ref attributes to set the right bean
+ name to use.
+
+ <mybatis:scan/> supports filtering the mappers created by either specifying a marker
+ interface or an annotation. The annotation property specifies an annotation to
+ search for. The marker-interface attribute specifies a parent interface to search for.
+ If both properties are specified, mappers are added for interfaces that match either
+ criteria. By default, these two properties are null, so all interfaces in the given
+ base package(s) will be loaded as mappers.
+
+ Discovered mappers will be named using Spring default naming strategy for autodetected
+ components (see section 3.14.4 of the Spring manual). That is, if no annotation is
+ found, it will use the uncapitalized non-qualified class name of the mapper. But if
+ either a @Component or a JSR-330 @Named annotation is found it will get the name from
+ the annotation. Notice that you can set the annotation attribute
+ to org.springframework.stereotype.Component, javax.inject.Named (if you have JSE 6)
+ or to your own annotation (that must be itself annotated) so the annotation will work
+ both as a marker and as a name provider.
+
+ NOTE <context:component-scan/> won't be able to scan and register mappers. Mappers
+ are interfaces and, in order to register them to Spring, the scanner must know how
+ to create a MapperFactoryBean for each interface it finds.
+
+ <bean id="adMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
+ <property name="mapperInterface" value="de.example.mybatis.repository.mapper.AdMapper" />
+ <property name="sqlSessionFactory" ref="sqlSessionFactory" />
+ </bean>
+
+ <bean id="adDescriptionMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
+ <property name="mapperInterface" value="de.example.mybatis.repository.mapper.AdDescriptionMapper" />
+ <property name="sqlSessionFactory" ref="sqlSessionFactory" />
+ </bean>
+ -->
+
+ <bean id="exampleService" class="de.example.mybatis.spring.service.ExampleService">
+ <property name="adMapper" ref="adMapper" />
+ </bean>
+
+</beans>