GAE + Google Cloud SQL + myBatis

gae_cloudsql_mybatis

Requirements

  • Google Cloud SQL
  • Eclipse with GAE Plugin
  • MySql java connector (jar)
  • myBatis (jar)

You can find more information or download required tools using the below links

( 1 ) Cloud SQL settings

Assume Cloud SQL has the following settings:

  • Project ID: hmk-cloudsql
  • Cloud SQL Instance:instance1
  • Database:db1
  •  Table: Persons

cloudsql_settings

( 2 ) Create new (GAE) Web Application Project

GAE_new_project

( 3 ) Jar files

  • Copy myBatis jar file and mysql-connector-java to lib folder
  • Add the two jar files to the build path

mybatis-sqlcloud-jar

( 4 ) Config.xml

<?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>
    <typeAliases>
        <typeAlias alias="Person" type="com.hmkcode.vo.Person"/>        
    </typeAliases>

    <environments default="development">
        <environment id="development">
          <transactionManager type="JDBC"/>
            <!--  connecting to Cloud SQL -->
            <dataSource type="POOLED">
                <property name="driver" value="com.google.appengine.api.rdbms.AppEngineDriver"/>
                <property name="url" value="jdbc:google:rdbms://hmk-cloudsql:instance1/db1"/>

            </dataSource>

       </environment>
    </environments>

    <mappers>
       <mapper resource="com/hmkcode/mybatis/xml/Person.xml"/>
    </mappers>
</configuration>

( 5 ) MyBatisConnectionFactory.java + Person.java + Person.xml + PersonDAO.java

  • MyBatisConnectionFactory.java  -> will establish the connection
  • Person.xml -> Contains all SQL statements
  • Person.java -> Plain Java object
  • PersonDAO.java -> Data access object execute the queries, map and return the results.

mybatis-sqlcloud-files

( 6 ) App Engine Settings for Cloud SQL

Right Click on the project folder  >> Google >> App Engine Settings…

mybatis-sqlcloud-GAE-Settings

  • Check “Google Cloud SQL”
  • Select “Use Google Cloud instance”
  • Click “Configure…”  (the one beside “Use Google Cloud instance”)

mybatis-sqlcloud-GoogleCloudSQL-settings

mybatis-sqlcloud-configure-GoogleCloudSQL-instance

  • Repeat the same step for the last “Configure…” (the one beside “App Engine SQL instance”)
  • OK twice

( 7 ) Test the application

Download the source code