Programming Posts

Connecting a Servlet, iBatis and Glassfish 3

This time im trying to change my programming style, from a simple JDBC connection to a bit more complicated JDBC Connection Pool so i could increase my application’s response time. Btw, what is a Connection Pools? Basically, it’s a cached connections that are kept in a runtime object pool and can be used and reused as needed by the application. For a more complete explanation, you can check here.

Im planning to deploy my application on a Glassfish v3 and change my iBatis’ setting from simple JDBC to JNDI connection, but first i have create a MySql DataSource on m Glassfish. In order to create a connection pool, i put my MySQL JDBC Jar in <glassfish installation folder>/lib.

From my Glassfish console (http://localhost:4848/), i create a new Connection pools,

Start by giving its name, and selecting resource and database vendor type,

Connection type,

Dont forget adding these properties, so you can connect to your MySql Database,

you can test your connection by pinging it,

Btw, if you cant find the which resource type you need, here are some hints

  1. javax.sql.DataSource: is a non-pooled direct connection
  2. javax.sql.ConnectionPoolDataSource: connection is coming from pool
  3. javax.sql.XADataSource: is for distributed transactions

Create a new JDBC Resources using your new Connection Pool,

Next step is creating a simple web application using NetBeans 6.9. As usual, i create a simple table

CREATE DATABASE 'test'
USE 'test'

CREATE TABLE `contoh` (
  `nama` varchar(30) NOT NULL DEFAULT '',
  `alamat` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`nama`)
)

insert into contoh (nama, alamat) values ('edwin', 'jakarta');
insert into contoh (nama, alamat) values ('kamplenk', 'ciledug');
insert into contoh (nama, alamat) values ('nugie', 'pamulang');
insert into contoh (nama, alamat) values ('samsu', 'dago');
insert into contoh (nama, alamat) values ('tebek', 'jayapura');

next step is creating a java bean for database mapping

package com.edw.bean;

/**
 *
 * @author edw
 */
public class Contoh {

    private String nama;
    private String alamat;

    public Contoh(String nama, String alamat) {
        this.nama = nama;
        this.alamat = alamat;
    }

    public Contoh() {
    }

    public String getAlamat() {
        return alamat;
    }

    public void setAlamat(String alamat) {
        this.alamat = alamat;
    }

    public String getNama() {
        return nama;
    }

    public void setNama(String nama) {
        this.nama = nama;
    }

    @Override
    public String toString() {
        return "Contoh{" + "nama=" + nama + " and alamat=" + alamat + '}';
    }        
}

and an xml mapping for database queries, i named it contoh.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd" >
<sqlMap namespace="contoh" >

    <!--alias-->
    <typeAlias alias="Contoh" type="com.edw.bean.Contoh" />

    <resultMap id="result" class="Contoh">
        <result property="nama" column="NAMA" columnIndex="1"/>
        <result property="alamat" column="ALAMAT" columnIndex="2"/>
    </resultMap>

    <insert id="insertContoh" parameterClass="Contoh" >
    insert into contoh (nama, alamat)
    values (#nama:VARCHAR#, #alamat:VARCHAR#)
    </insert>

    <!--query select all-->
    <select id="selectAllContoh" resultMap="result">
    select nama, alamat
    from contoh
    </select>

    <!--query with Bean parameter-->
    <select id="selectContohWithPKfromBean" resultClass="Contoh" parameterClass="Contoh">
    select nama, alamat
    from contoh
    where nama like #nama:VARCHAR#
    </select>

    <!--query with String parameter-->
    <select id="selectContohWithPKfromString" resultClass="Contoh" parameterClass="java.lang.String">
    select nama, alamat
    from contoh
    where nama like #nama#
    </select>

    <!--query with Map parameter-->
    <select id="selectContohWithPKfromMap" resultClass="Contoh" parameterClass="java.util.Map">
    select nama, alamat
    from contoh
    where nama like #nama#
    </select>

</sqlMap>

and ibatis’ main xml configuration, sqlmapconfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig
PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">

<sqlMapConfig>
    <settings
        useStatementNamespaces="true"
        lazyLoadingEnabled="true"
        enhancementEnabled="true"
        />

    <transactionManager type="JDBC" commitRequired="false">
        <dataSource type="JNDI">
            <property name="DataSource" value="mysqljndi"/>
        </dataSource>
    </transactionManager>

    <sqlMap resource="com/edw/sqlmap/contoh.xml"/>
</sqlMapConfig>

next step is creating a simple java class to load all iBatis’ configuration file.

package com.edw.config;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import java.io.IOException;
import java.io.Reader;


/**
 *
 * @author edw
 */
public class SqlMapConfig {

    protected static final SqlMapClient sqlMap;

    static {
        try {
            Reader reader = Resources.getResourceAsReader("com/edw/sqlmap/sqlmapconfig.xml");
            sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
        } catch (IOException e) {
            throw new RuntimeException("Fatal Error, ga dapet sqlmapconfignya.  Cause: " + e, e);
        } catch (Exception e){
            throw new RuntimeException("Fatal Error.  Cause: " + e, e);
        }
    }

    public static SqlMapClient getSqlMap() {
        return sqlMap;
    }
}

a simple Servlet

package com.edw.servlet;

import com.edw.bean.Contoh;
import com.edw.config.SqlMapConfig;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

/**
 *
 * @author edw
 */
public class Main extends HttpServlet {

    private Logger logger = Logger.getLogger(this.getClass());

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
          
            out.println("<html>");
            out.println("<head>");
            out.println("<title>iBatis Test</title>");
            out.println("</head>");
            out.println("<body>");

            out.println("-----------------------");
            out.println("select all <br />");

            List<Contoh> contohs = SqlMapConfig.getSqlMap().queryForList("contoh.selectAllContoh");
            for (Contoh contoh : contohs) {
                out.println(contoh+"<br />");
            }

            out.println("<br />");
            out.println("<br />");
            
            out.println("-----------------------");
            out.println("select with Parameter Bean");
            out.println("<br />"+SqlMapConfig.getSqlMap().queryForObject("contoh.selectContohWithPKfromBean", new Contoh("samsu", null))+"<br /><br />");

            out.println("-----------------------");
            out.println("select with Parameter String");
            out.println("<br />"+SqlMapConfig.getSqlMap().queryForObject("contoh.selectContohWithPKfromString", "kamplenk")+"<br /><br />");

            out.println("-----------------------");
            out.println("select with Parameter Map");
            Map<String, String> map = new HashMap<String, String>();
            map.put("nama", "tebek");
            out.println("<br />"+SqlMapConfig.getSqlMap().queryForObject("contoh.selectContohWithPKfromMap", map)+"<br /><br />");
            
            out.println("</body>");
            out.println("</html>");

        } catch(Exception ex){
            logger.error(ex.getMessage(),ex);
        } finally {
            out.close();
        }
    } 

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 
   
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
  
    @Override
    public String getServletInfo() {
        return "My Main Servlet";
    }
}

and my web.xml configuration

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>Main</servlet-name>
        <servlet-class>com.edw.servlet.Main</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Main</servlet-name>
        <url-pattern>/Main</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>Main</welcome-file>
    </welcome-file-list>
</web-app>

this is the result on my browser when i run my application

this is my netbeans project structure

Again, i hope this simple tutorial could be useful for others. Cheers (B)
nb. im using Netbeans 6.9, iBatis 2.3.4 and Glassfish 3.

A Simple Java Client Server Application using EJB3 and Glassfish3

Well, in this tutorial i want to show you how to create a simple client server application using java. Actually java has dozens of different network protocols, from a simple socket, hessian, burlap, SpringHttpInvoker, SOAP, XML and so on. But in this example, i will try to create a very simple client server application with EJB 3, using Glassfish 3 as JavaEE Container. As usual, i use Netbeans 6.9 with its default Glassfish3 installation.

First, i create a new JavaEE, EJB Module project, named CompressedEJBServer, and create a simple Stateless Session Bean in it

package com.edw.facade;

import javax.ejb.Remote;

/**
 *
 * @author edw
 */
@Remote
public interface ConnectionFacadeRemote {
    String sayHello(String string);
    int sayAge(int age);  
}

and its implementation

package com.edw.facade;

import javax.ejb.Stateless;

/**
 *
 * @author edw
 */
@Stateless
public class ConnectionFacade implements ConnectionFacadeRemote {

    public String sayHello(String string) {
        System.out.println("im at " + this.getClass().getName() + " method sayHello()");
        return "hello " + string;
    }

    public int sayAge(int age) {
        System.out.println("im at " + this.getClass().getName() + " method sayAge()");
        return age * 2;
    }
}

and that’s my EJB3 Server side files. Simple isn’t it?

Next step is creating a Standard Java Application project, for my EJB3 client application. It consist only 1 java file, for testing connection to the server.

package com.edw.main;

import com.edw.facade.ConnectionFacadeRemote;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import org.apache.log4j.Logger;

/**
 *
 * @author edw
 */
public class Main {

    private Logger logger = Logger.getLogger(Main.class);

    private void connect() {
        try {
            Properties props = new Properties();
            props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.enterprise.naming.SerialInitContextFactory");
            props.setProperty("org.omg.CORBA.ORBInitialHost", "localhost");
            
            // glassfish default port value will be 3700, 
            // but im using tcpviewer to redirect my 50005 port to 3700
            props.setProperty("org.omg.CORBA.ORBInitialPort", "50005");

            InitialContext ctx = new InitialContext(props);
            ConnectionFacadeRemote connectionFacadeRemote = (ConnectionFacadeRemote) ctx.lookup("com.edw.facade.ConnectionFacadeRemote");
            logger.debug(connectionFacadeRemote.sayHello("edwin "));
            logger.debug("my age is " + connectionFacadeRemote.sayAge(12) + " years");
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }
    }

    public static void main(String[] args) {
        Main x = new Main();
        x.connect();
    }
}

include these jars to your client side’s application,

auto-depends.jar
common-util.jar
config.jar
config-api.jar
config-types.jar
connectors-internal-api.jar
container-common.jar
deployment-common.jar
dol.jar
ejb.security.jar
ejb-container.jar
glassfish-api.jar
glassfish-corba-asm.jar
glassfish-corba-codegen.jar
glassfish-corba-csiv2-idl.jar
glassfish-corba-newtimer.jar
glassfish-corba-omgapi.jar
glassfish-corba-orb.jar
glassfish-corba-orbgeneric.jar
glassfish-naming.jar
gmbal.jar
hk2-core.jar
internal-api.jar
javax.ejb.jar
javax.jms.jar
javax.resource.jar
javax.servlet.jar
javax.transaction.jar
jta.jar
kernel.jar
management-api.jar
orb-connector.jar
orb-iiop.jar
security.jar
tiger-types-osgi.jar
transaction-internal-api.jar 

and dont forget to add CompressedEJBServer project into CompressEJBClient’s project

this is what happen if i run my client side’s application

[Main] DEBUG com.edw.main.Main:30 - hello edwin 
[Main] DEBUG com.edw.main.Main:31 - my age is 24 years

this is my Server side’s project structures

and this is my Client side’s project structures
My Client Side's Project Structure

and this is my TCP Viewer logs, i try to redirect my localhost’s port 50005 into my localhost’s port 3700 (Glassfish’s port), so i can see what is passing through my 50005 port via TCP Viewer’s console.

Hope this can help, have fun and good luck. May the Source be with You.
(*)

How to Convert Java List or ArrayList into ResultSet

At this project i found an obstacle, which i need to convert a reporting module from fetching data from database into fetching data from Webservices. At first I think it was easy, I just fetch strings from Webservice, and put it in a bean or in a map and put it all in an ArrayList, just like JasperReport. But I forgot, this isn’t JasperReport I’m using, I’m using bloody hell CrystalReport. And my Crystal-Report-calling method only accepting ResultSet for parameter, so somehow I need to convert strings from webservice into ResultSet.

My idea is adding strings from webservices into an ArrayList<Object> and adding this ArrayList into ArrayList<ArrayList<Object>> and converting it into rows of ResultSet. And im using MockRunner library to help me. This is how I do it :

I create a class to convert a list into result set

package com.edw.rs;

import com.mockrunner.mock.jdbc.MockResultSet;
import java.sql.ResultSet;
import java.util.List;

/**
 *
 * @author edw
 */
public class MyResultSet {

    public ResultSet getResultSet(List<String> headers, List<List<Object>> data) throws Exception {

        // validation
        if (headers == null || data == null) {
            throw new Exception("null parameters");
        }

        if (headers.size() != data.size()) {
            throw new Exception("parameters size are not equals");
        }

        // create a mock result set
        MockResultSet mockResultSet = new MockResultSet("myResultSet");

        // add header
        for (String string : headers) {          
            mockResultSet.addColumn(string);
        }

        // add data
        for (List<Object> list : data) {
            mockResultSet.addRow(list);
        }

        return mockResultSet;
    }
}

and i tested it with my junit class

package com.edw.rs.test;

import com.edw.rs.MyResultSet;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.junit.Test;

/**
 *
 * @author edw
 */
public class MyResultSetTest {

    private Logger logger = Logger.getLogger(MyResultSetTest.class);

    public MyResultSetTest() {
    }

    @Test
    public void testMyResultSet() throws Exception {
        MyResultSet myResultSet = new MyResultSet();
        List<String> headers = new ArrayList<String>();
        headers.add("id");
        headers.add("name");
        headers.add("salary");
        headers.add("age");

        List<List<Object>> data = new ArrayList<List<Object>>();
        for (int i = 0; i < 4; i++) {
            List<Object> objects = new ArrayList<Object>();
            objects.add(new Integer(i));
            objects.add("name " + i);
            objects.add(new Double(i));
            objects.add(new Integer(20 + i));
            data.add(objects);
        }

        ResultSet rs = myResultSet.getResultSet(headers, data);
        while (rs.next()) {
            logger.debug(rs.getString("id"));
            logger.debug(rs.getString(2));
            logger.debug(rs.getDouble("salary"));
            logger.debug(rs.getInt(4));
            logger.debug("------------------------");
        }

    }
}

this is the result on my IDE console

2010-08-18 18:13:09,112 [MyResultSetTest] DEBUG com.edw.rs.test.MyResultSetTest:42 - 0
2010-08-18 18:13:09,131 [MyResultSetTest] DEBUG com.edw.rs.test.MyResultSetTest:43 - name 0
2010-08-18 18:13:09,132 [MyResultSetTest] DEBUG com.edw.rs.test.MyResultSetTest:44 - 0.0
2010-08-18 18:13:09,132 [MyResultSetTest] DEBUG com.edw.rs.test.MyResultSetTest:45 - 20
2010-08-18 18:13:09,133 [MyResultSetTest] DEBUG com.edw.rs.test.MyResultSetTest:46 - ------------------------
2010-08-18 18:13:09,133 [MyResultSetTest] DEBUG com.edw.rs.test.MyResultSetTest:42 - 1
2010-08-18 18:13:09,189 [MyResultSetTest] DEBUG com.edw.rs.test.MyResultSetTest:43 - name 1
2010-08-18 18:13:09,189 [MyResultSetTest] DEBUG com.edw.rs.test.MyResultSetTest:44 - 1.0
2010-08-18 18:13:09,189 [MyResultSetTest] DEBUG com.edw.rs.test.MyResultSetTest:45 - 21
2010-08-18 18:13:09,190 [MyResultSetTest] DEBUG com.edw.rs.test.MyResultSetTest:46 - ------------------------
2010-08-18 18:13:09,190 [MyResultSetTest] DEBUG com.edw.rs.test.MyResultSetTest:42 - 2
2010-08-18 18:13:09,191 [MyResultSetTest] DEBUG com.edw.rs.test.MyResultSetTest:43 - name 2
2010-08-18 18:13:09,218 [MyResultSetTest] DEBUG com.edw.rs.test.MyResultSetTest:44 - 2.0
2010-08-18 18:13:09,219 [MyResultSetTest] DEBUG com.edw.rs.test.MyResultSetTest:45 - 22
2010-08-18 18:13:09,219 [MyResultSetTest] DEBUG com.edw.rs.test.MyResultSetTest:46 - ------------------------
2010-08-18 18:13:09,219 [MyResultSetTest] DEBUG com.edw.rs.test.MyResultSetTest:42 - 3
2010-08-18 18:13:09,220 [MyResultSetTest] DEBUG com.edw.rs.test.MyResultSetTest:43 - name 3
2010-08-18 18:13:09,225 [MyResultSetTest] DEBUG com.edw.rs.test.MyResultSetTest:44 - 3.0
2010-08-18 18:13:09,226 [MyResultSetTest] DEBUG com.edw.rs.test.MyResultSetTest:45 - 23
2010-08-18 18:13:09,226 [MyResultSetTest] DEBUG com.edw.rs.test.MyResultSetTest:46 - ------------------------

this is my project structure, FYI im using Netbeans 6.9.
Netbeans 6.9 Project Structure

all i can say is, Thank You mockrunner, you saved my life.

A Simple Swing and iBatis Integration Example

According to Wikipedia, iBATIS is a persistence framework which automates the mapping between SQL databases and objects in Java, .NET, and Ruby on Rails. In Java, the objects are POJOs (Plain Old Java Objects). The mappings are decoupled from the application logic by packaging the SQL statements in XML configuration files. The result is a significant reduction in the amount of code that a developer needs to access a relational database using lower level APIs like JDBC and ODBC.

Here, we are trying to create a simple java application using iBatis framework. Im using Netbeans as my IDE and MySql for my database. First of all, we create a simple “test” database, and “contoh” table consisting of two varchar fields.

CREATE DATABASE 'test'
USE 'test'

CREATE TABLE 'contoh' (
  'nama' varchar(30) NOT NULL,
  'alamat' varchar(100) DEFAULT NULL,
  PRIMARY KEY ('nama')
) 

next step is creating a java bean for database mapping

package com.edw.bean;

public class Contoh {

    private String nama;
    private String alamat;

    public String getAlamat() {
        return alamat;
    }

    public void setAlamat(String alamat) {
        this.alamat = alamat;
    }

    public String getNama() {
        return nama;
    }

    public void setNama(String nama) {
        this.nama = nama;
    }
    
}

and an xml mapping for database queries, i name it contoh.xml, and place it in

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd" >
<sqlMap namespace="contoh" >

  <insert id="insertContoh" parameterClass="com.edw.bean.Contoh" >
    insert into contoh (nama, alamat)
    values (#nama:VARCHAR#, #alamat:VARCHAR#)
  </insert>
</sqlMap>

and one xml file to contain all of our basic database connection and configuration files

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig
PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">

<sqlMapConfig>
    <settings
        useStatementNamespaces="true"
        lazyLoadingEnabled="true"
        enhancementEnabled="true"
        maxSessions="20"
        />

    <transactionManager type="JDBC" commitRequired="false">
        <dataSource type="SIMPLE">

            <property name="SetAutoCommitAllowed" value="false"/>
            <property name="DefaultAutoCommit" value="false"/>
            
            <property name="JDBC.Driver" value="com.mysql.jdbc.Driver"/>
            <property name="JDBC.ConnectionURL" value="jdbc:mysql://localhost/test"/>
            <property name="JDBC.Username" value="root"/>
            <property name="JDBC.Password" value=""/>
   
        </dataSource>
    </transactionManager>


    <!-- dont forget to register your sql map configs -->
    <sqlMap resource="com/edw/sqlmap/contoh.xml"/>

</sqlMapConfig>

dont forget to register you xml queries here (line 28), or iBatis wont find it. And as you can see, at line 11, we can set our maximum session to database. 20 maxSessions means, there wont be more than 20 concurrent connection to database. Dont worry, iBatis can also connect to your connection pooling or JNDI as Datasource.

next step is, we create a singleton java class, to load our iBatis configuration.

package com.edw.config;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

import java.io.IOException;
import java.io.Reader;

public class SqlMapConfig {

    protected static final SqlMapClient sqlMap;

    static {
        try {
            Reader reader = Resources.getResourceAsReader("com/edw/sqlmap/sqlmapconfig.xml");
            sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
        } catch (IOException e) {
            throw new RuntimeException("Fatal Error, ga dapet sqlmapconfignya.  Cause: " + e, e);
        } catch (Exception e){
            throw new RuntimeException("Fatal Error.  Cause: " + e, e);
        }
    }

    public static SqlMapClient getSqlMap() {
        return sqlMap;
    }
}

and after that, we create our UI Class. Im using a simple Swing class for example.

package com.edw.ui;

import com.edw.bean.Contoh;
import com.edw.config.SqlMapConfig;
import com.ibatis.sqlmap.client.SqlMapClient;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class FrameUtama extends JFrame implements ActionListener {

    private JTextField txtNama = new JTextField();
    private JTextField txtAlamat = new JTextField();
    private JButton cmdButton = new JButton("Save");

    public FrameUtama(){
        setLayout(new GridLayout(3, 3));
        Container con = this.getContentPane();
        con.add(new JLabel("nama : "));
        con.add(txtNama);
        con.add(new JLabel("Alamat : "));
        con.add(txtAlamat);
        con.add(cmdButton);

        cmdButton.addActionListener(this);
    }

    public void actionPerformed(ActionEvent e) {

    }

    public static void main(String[] edw) {
        FrameUtama frameUtama = new FrameUtama();
        frameUtama.setVisible(true);
        frameUtama.setSize(300,150);
        frameUtama.setLocationRelativeTo(null);
    }

}

and we just put this simple snippet code to connect our Swing UI code to database via iBatis.

 public void actionPerformed(ActionEvent e) {
        if(e.getSource() == cmdButton){
            Contoh contoh = new Contoh();
            contoh.setNama(txtNama.getText());
            contoh.setAlamat(txtAlamat.getText());

            SqlMapClient sqlMapClient = SqlMapConfig.getSqlMap();
            try {
                sqlMapClient.insert("contoh.insertContoh", contoh);
                System.out.println("Success");
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }

well, this is the project file structure in NB 6.8.
my ibatis project structure

and this is the UI layout
Application GUI

this is what happen if we submit a data
successfully submit data

the data we submitted is in the database
mysql data

dont forget to download ibatis jars here, im using iBatis 2.3.4 currently.
Thanks.

Random Date Generator dengan Java

Iseng-iseng bikin class sederhana untuk menghasilkan suatu tanggal random yang terletak antara tanggalSebelum (Date) dan tanggalSesudah (Date). Rencananya ini mo gw pakek bwt testing aplikasi. Sorry klo classnya rada berantakan, bikinnya juga buru-buru, sembari nunggu adzan Maghrib.

package com.edw.random;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 
 * @author edwin
 */
public class RandomDateGenerator extends Thread {

	private Date sebelum;
	private Date sesudah;
	private int repetition;

	public Date getSebelum() {
		return sebelum;
	}

	public void setSebelum(Date sebelum) {
		this.sebelum = sebelum;
	}

	public Date getSesudah() {
		return sesudah;
	}

	public void setSesudah(Date sesudah) {
		this.sesudah = sesudah;
	}

	public int getRepetition() {
		return repetition;
	}

	public void setRepetition(int repetition) {
		this.repetition = repetition;
	}

	public RandomDateGenerator() {
	}

	@Override
	public void run() {
		try {
			for (int i = 0; i < repetition; i++) {
				Thread.sleep(1000);
				System.out.println(getRandomDateBetween(sebelum, sesudah));
			}
		} catch (InterruptedException interruptedException) {
			interruptedException.printStackTrace();
		}
	}

	private synchronized Date getRandomDateBetween(Date from, Date to) {
		Calendar cal = Calendar.getInstance();

		cal.setTime(from);
		BigDecimal decFrom = new BigDecimal(cal.getTimeInMillis());

		cal.setTime(to);
		BigDecimal decTo = new BigDecimal(cal.getTimeInMillis());

		BigDecimal selisih = decTo.subtract(decFrom);
		BigDecimal factor = selisih.multiply(new BigDecimal(Math.random()));

		return new Date((factor.add(decFrom)).longValue());
	}

	public static void main(String[] args) throws Exception {
		RandomDateGenerator rdg = new RandomDateGenerator();
		rdg.setSebelum(new SimpleDateFormat("dd MM yyyy").parse("17 08 1978"));
		rdg.setSesudah(new SimpleDateFormat("dd MM yyyy").parse("17 08 1990"));
		rdg.setRepetition(10);
		rdg.start();
	}
}

may the SOURCE be with you.

Wassalam.