Messing around with MyBatis.
authorGustavo Martin Morcuende <gustavo@supergusarapo.(none)>
Mon, 26 Aug 2013 19:18:58 +0000 (21:18 +0200)
committerGustavo Martin Morcuende <gustavo@supergusarapo.(none)>
Mon, 26 Aug 2013 19:18:58 +0000 (21:18 +0200)
MyBatis/README.txt [new file with mode: 0644]
MyBatis/createdatabase.sh [new file with mode: 0755]
MyBatis/pom.xml [new file with mode: 0644]
MyBatis/src/main/java/de/example/ibatis/TestMain.java [new file with mode: 0644]
MyBatis/src/main/resources/generator/generatorConfig.xml [new file with mode: 0644]

diff --git a/MyBatis/README.txt b/MyBatis/README.txt
new file mode 100644 (file)
index 0000000..8291f62
--- /dev/null
@@ -0,0 +1,6 @@
+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
diff --git a/MyBatis/createdatabase.sh b/MyBatis/createdatabase.sh
new file mode 100755 (executable)
index 0000000..ef2bb57
--- /dev/null
@@ -0,0 +1,9 @@
+#!/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"
diff --git a/MyBatis/pom.xml b/MyBatis/pom.xml
new file mode 100644 (file)
index 0000000..a38961e
--- /dev/null
@@ -0,0 +1,101 @@
+<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>mybatisexample</artifactId>
+  <packaging>jar</packaging>
+  <version>1.0-SNAPSHOT</version>
+  <name>mybatisexample</name>
+  <url>http://gumartinm.name</url>
+  <properties>
+    <mybatis.generator.outputdirectory>${project.build.directory}/generated-sources/mybatis-generator/</mybatis.generator.outputdirectory>
+  </properties>
+  <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>Gnerate 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>
+  <dependencies>
+    <dependency>
+      <groupId>junit</groupId>
+      <artifactId>junit</artifactId>
+      <version>3.8.1</version>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+        <groupId>org.mybatis</groupId>
+        <artifactId>mybatis</artifactId>
+        <version>3.2.2</version>
+    </dependency>
+    <dependency>
+        <groupId>mysql</groupId>
+        <artifactId>mysql-connector-java</artifactId>
+        <version>5.1.9</version>
+    </dependency>
+    <dependency>
+        <groupId>log4j</groupId>
+        <artifactId>log4j</artifactId>
+        <version>1.2.17</version>
+    </dependency>
+  </dependencies>
+</project>
diff --git a/MyBatis/src/main/java/de/example/ibatis/TestMain.java b/MyBatis/src/main/java/de/example/ibatis/TestMain.java
new file mode 100644 (file)
index 0000000..4c2b11b
--- /dev/null
@@ -0,0 +1,147 @@
+package de.example.ibatis;
+
+import java.io.IOException;
+import java.util.Date;
+
+import org.apache.ibatis.io.Resources;
+import org.apache.ibatis.session.SqlSession;
+import org.apache.ibatis.session.SqlSessionFactory;
+import org.apache.ibatis.session.SqlSessionFactoryBuilder;
+
+import de.example.mybatis.model.Ad;
+import de.example.mybatis.repository.mapper.AdMapper;
+
+//import de.example.ibatis.demo.dao.UserDao;
+//import de.example.ibatis.demo.dao.UserDaoIbatis;
+//import de.example.ibatis.dto.UserTEO;
+
+public class TestMain {
+
+       public static void main(String[] args) throws IOException {
+               //Initialize dao
+               //UserDao manager = new UserDaoIbatis();
+
+//             File file = new File("sql-maps-config.xml");
+//             FileInputStream fileInputStream = new FileInputStream(file);
+               // AL FINAL NO NECESITABA TODO ESTO DE FILECHANNEL Y BYTEBUFFERS xD se me fue la pinza :(
+               // al menos mira lo del FileChannel.size() porque es interesante recordarlo
+               // y saber que si el archivo puede cambiar el metodo FileChannel.size() no te vale :(
+               // y tendrias que usar algo como lo que hiciste en AxisC3 driver :)
+//             FileChannel fileChannel = fileInputStream.getChannel();
+               
+               // FileChannel.size() internamente usa fstat64 recuperando st_size
+               // asi puede saber el tamaño del archivo antes de leerlo. Esto puede
+               // ser un problema si el archivo puede cambiar por alguna razon desconocida
+               // mientras lo estoy leyendo.
+               // ver: FileChannelImpl.c (la implementacion nativa de FileChannel)
+               // otra solucion es lo que hice para AxisC3, un array de byes mutable
+               // que se incrementa tanto como haga falta hasta que haya leido todos los bytes
+               // Por tanto si a priori no puedo saber el tamaño del archivo a leer deberia
+               // usar un array de bytes mutables cuyo tamaño puede incrementarse si hace falta
+               // como hice con el AxisC3 :)
+               
+               //fileInputStream.read(new byte[(int)fileChannel.size()]); <----- puedo leer tambien asi pero me apetece usar byte buffers
+               // de java.nio :)
+               
+               
+               //joer.size devuelve long!!!! hago casta int pierdo datos :(  ¿solucion?
+//             ByteBuffer gus = ByteBuffer.allocate((int)fileChannel.size());
+//             int result = 0;
+//             while (result != -1) {
+//                     result = fileChannel.read(gus);
+//             }
+//             TestMain.class.getResourceAsStream("sql-maps-config.xml");
+//             Reader reader = Resources.getResourceAsReader("sql-maps-config.xml");
+               
+               // Desde el Javadoc de org.xml.sax.InputSource:
+//              <p>The SAX parser will use the InputSource object to determine how
+//              to read XML input.  If there is a character stream available, the
+//              parser will read that stream directly, disregarding any text
+//              encoding declaration found in that stream.
+//              If there is no character stream, but there is
+//              a byte stream, the parser will use that byte stream, using the
+//              encoding specified in the InputSource or else (if no encoding is
+//              specified) autodetecting the character encoding using an algorithm
+//              such as the one in the XML specification.  If neither a character
+//              stream nor a
+//              byte stream is available, the parser will attempt to open a URI
+//              connection to the resource identified by the system
+//              identifier.</p>
+               
+               // LUEGO SI LE PASO UN FileInputStream/InputStream (no es un character stream) y no especifico el encoding
+               // se deberia autodetectar el encoding usando la especificacion XML (leyendo
+               // la cabecera del archivo xml) GUAY!!!! JUSTO LO QUE ME GUSTA :)
+//             SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(fileInputStream);
+               
+               // JOER NO HACIA FALTA TANTO LIO PARA CONSEGUIR UN INPUTSTREAM. DE HECHO LA MEJOR
+               // FORMA ES HACERLO ASI SIEMPRE (con el getResourceAsStream) ASÍ NO DEPENDES
+               // DE PATHS ABSOLUTIOS NI NADA, TE SIRVE PARA .jars, O DIRECTORIOS FISICOS, LO QUE SEA QUE ESTE
+               // EN EL CLASSPATH:
+               SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
+                               .build(/**TestMain.class.getResourceAsStream("sql-maps-config.xml")**/
+                                               Resources.getResourceAsStream("mybatis-sql-maps-config.xml"));
+               SqlSession session = sqlSessionFactory.openSession();
+               // EN MYBATIS HAY UNA FORMA MEJOR QUE ESTA
+//             try {
+//             Ad ad = session.selectOne("de.example.mybatis.model.Ad.selectByPrimaryKey", 101);
+//             } finally {
+//                     session.close();
+//             }
+               // ESTA FORMA ES MUCHO MEJOR :)
+               try {
+                       AdMapper mapper = session.getMapper(AdMapper.class);
+                       Ad adprueba = new Ad();
+                       adprueba.setCompanyCategId(200L);
+                       adprueba.setCreatedAt(new Date());
+                       adprueba.setCompanyId(2L);
+                       adprueba.setUpdatedAt(new Date());
+                       mapper.insert(adprueba);
+//                     Ad ad = mapper.selectByPrimaryKey(1000L);
+               } finally {
+                       session.close();
+               }
+               
+               // De esa forma consigo que el encoding dependa del valor puesto en la cabecera del xml :)
+               
+//             SqlSession session = sqlSessionFactory.openSession();
+//             try {
+//               Blog blog = session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);
+//             } finally {
+//               session.close();
+//             }
+//             
+//             SqlSession session = sqlSessionFactory.openSession();
+//             try {
+//               BlogMapper mapper = session.getMapper(BlogMapper.class);
+//               Blog blog = mapper.selectBlog(101);
+//             } finally {
+//               session.close();
+//             }
+//             SqlMapClient sqlmapClient = SqlMapClientBuilder.buildSqlMapClient (reader);
+//
+//             //Create a new user to persist
+//             UserTEO user = new UserTEO();
+//             user.setId(1);
+//             user.setName("Demo User");
+//             user.setPassword("password");
+//             user.setEmail("demo-user@howtodoinjava.com");
+//             user.setStatus(1);
+//
+//             //Add the user
+//             manager.addUser(user,sqlmapClient);
+//
+//             //Fetch the user detail
+//             UserTEO createdUser = manager.getUserById(4, sqlmapClient);
+//             System.out.println(createdUser.getEmail());
+//
+//             //Lets delete the user
+//             manager.deleteUserById(1, sqlmapClient);
+//             try {
+//                     Thread.sleep(100000);
+//             } catch (InterruptedException e) {
+//                     // TODO Auto-generated catch block
+//                     e.printStackTrace();
+//             }
+       }
+
+}
diff --git a/MyBatis/src/main/resources/generator/generatorConfig.xml b/MyBatis/src/main/resources/generator/generatorConfig.xml
new file mode 100644 (file)
index 0000000..946fd15
--- /dev/null
@@ -0,0 +1,54 @@
+<?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">
+        <commentGenerator>
+            <property name="suppressAllComments" value="true" />
+            <property name="suppressDate" value="true" />
+        </commentGenerator>
+        
+        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
+            connectionURL="jdbc:mysql://localhost:3306/mybatis_example" 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="true" />
+        </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>