Java

java

Create A Database Transaction Using MyBatis

According to Wikipedia, transaction comprises a unit of work performed within a database management system (or similar system) against a database, and treated in a coherent and reliable way independent of other transactions.

Transactions in a database environment have two main purposes:
1. To provide reliable units of work that allow correct recovery from failures and keep a database consistent even in cases of system failure, when execution stops (completely or partially) and many operations upon a database remain uncompleted, with unclear status.
2. To provide isolation between programs accessing a database concurrently. If this isolation is not provided the programs outcome are possibly erroneous.

So basically, the concept of transaction is all-or-nothing. Whether all the query on transaction succesfully executed, or none of them executed.
On this example im trying to insert 5 datas, but on the 5th data i will throw an exception. If the database transaction is running well, none of the datas is on the database.
And dont forget, if you are using MySQL, please make sure that your table engine is InnoDB.

First, as always, i’ll start with a simple MySQL table,

CREATE TABLE `testing` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(30) NOT NULL,
  `address` varchar(255) NOT NULL,
  PRIMARY KEY (`Id`),
  UNIQUE KEY `ix` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Next is a java bean,

package com.edw.bean;

public class Testing {

    private Integer id;
    private String name;
    private String address;
	
	// other setter and getter
	
    @Override
    public String toString() {
        return "testing{" + "id=" + id + ", name=" + name + ", address=" + address + '}';
    }
}

Next is creating xml file for database configuration,

<?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>
    <environments default="development">
       <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="UNPOOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost/test"/>
                <property name="username" value="root"/>
                <property name="password" value=""/>
            </dataSource>
        </environment>          
    </environments>
    <mappers />        		
</configuration>

A java class to load my database configuration

package com.edw.config;

import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisSqlSessionFactory {

    private static final SqlSessionFactory FACTORY;

    static {
        try {
            Reader reader = Resources.getResourceAsReader("com/edw/sqlmap/Configuration.xml");
            FACTORY = new SqlSessionFactoryBuilder().build(reader);
        } catch (Exception e){
            throw new RuntimeException("Fatal Error.  Cause: " + e, e);
        }
    }

    public static SqlSessionFactory getSqlSessionFactory() {
        return FACTORY;
    }
}

And a java interface for insert queries,

package com.edw.mapper;

import com.edw.bean.Testing;
import org.apache.ibatis.annotations.Insert;

public interface TestingMapper {
    
    @Insert("INSERT INTO testing values(null, #{name},#{address})")
    public void insert(Testing testing);
    
}

This is the main class for my application

package com.edw.main;

import com.edw.bean.Testing;
import com.edw.config.MyBatisSqlSessionFactory;
import com.edw.mapper.TestingMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.log4j.Logger;

public class Main {

    private Logger logger = Logger.getLogger(Main.class);
    
    public Main(){        
    }

    private void start(){
        logger.debug("==== BEGIN ====");
        SqlSessionFactory sqlSessionFactory = MyBatisSqlSessionFactory.getSqlSessionFactory();
        sqlSessionFactory.getConfiguration().addMapper(TestingMapper.class);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        TestingMapper testingMapper = sqlSession.getMapper(TestingMapper.class);
        
        try {
            Testing testing = new Testing();
            testing.setName("Edwin");
            testing.setAddress("Ciledug");
            testingMapper.insert(testing);
            
            testing = new Testing();
            testing.setName("Kamplenk");
            testing.setAddress("Karawaci");
            testingMapper.insert(testing);
            
            testing = new Testing();
            testing.setName("Jeklit");
            testing.setAddress("Cibinong");
            testingMapper.insert(testing);
            
            testing = new Testing();
            testing.setName("Nugie");
            testing.setAddress("Pamulang");
            testingMapper.insert(testing);
            
            testing = new Testing();
            testing.setName("Tebek");
            testing.setAddress("Isvil");
            testingMapper.insert(testing);
            
            // try to create an exception
            if(testing.getName().equals("Tebek"))
                throw new Exception("No Tebek allowed");
            
            sqlSession.commit();
            logger.debug("=== END =====");
        } catch (Exception e) {
            logger.error(e,e);
            sqlSession.rollback();
        } finally{
            sqlSession.close();
        }                
    }
    
    public static void main(String[] args) {
        new Main().start();
    }    
}

It supposed to show exception on your Netbeans console, and your data wont be on your database.

and last but not least, my log4j properties

log4j.rootLogger=DEBUG, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %c:%L - %m%n

This is the screenshot for my netbeans project structure,

Cheers (D)

Weird “Unparseable Date” Exception When Using Java’s SimpleDateFormat Class

I found this weird error at my production server, an error which somehow never show up at my testing environment.

java.text.ParseException: Unparseable date: "Thu Oct 11 00:00:00 ICT 2012"
        at java.text.DateFormat.parse(DateFormat.java:337)
        at DateClass.main(DateClass.java:7)

It seems that my application is unable to parse the string i provided. But, what makes me confuse is, i try with the same class on my laptop over and over again but this error is never show up. I tought it has something to do with the server’s JDK version or even the server’s operating system.

This is my java class that i use for testing purpose, it runs very well on both my laptop and development server, but it shows error on my server.

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateClass {
    public static void main(String[] args) throws Exception {
        String date = "Thu Oct 11 00:00:00 ICT 2012";
        Date tanggalku = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy").parse(date);
        System.out.println(tanggalku);
    }
}

After spend several minutes googling, i found out that it happen because of Java’s Date Localization. This is my workaround,

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class DateClass {
    public static void main(String[] args) throws Exception {
        String date = "Thu Oct 11 00:00:00 ICT 2012";
        Date tanggalku = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US).parse(date);
        System.out.println(tanggalku);
    }
}

Another workaround, if you are using Apache Tomcat, is adding this configuration on your Tomcat’s server parameter.

-Duser.language=en 
-Duser.region=US

Hope it helps others 😉

Calling Java Serialized Object from JSP

This article is an answer for my simple assignment i created several weeks ago for my friend, Zainul Iman. Its about creating a simple web application that can persist and retrieve values by putting it values on a java object and serialized it on a plain text file.

Okay, so basically i only create 4 files. Only 1 java files, 2 jsp and 1 servlet. And only adding several lines on web.xml file.
First is a simple java bean to store my inserted value,

package com.edw.bean;

import java.io.Serializable;

public class Student implements Serializable{    
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }    
}

And a simple jsp file to serve as view layer, in here user can insert value which will be persist on java bean.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert Value</title>
    </head>
    <body>
        <form method="post" action="StudentServlet">
        <table>
            <tr>
                <td>Insert Name : </td>
                <td><input type="text" name="name" /> </td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" /></td>                
            </tr>
        </table>
        </form>
    </body>
</html>

This is my servlet class, in this class i handle the serialization of the inserted value into java object

package com.edw.servlet;

import com.edw.bean.Student;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class StudentServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String name = request.getParameter("name");
        Student student = new Student();
        student.setName(name);
		
        FileOutputStream fileOutputStream2 = new FileOutputStream(new File("D:\\test12.txt"), false);
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream2);
        objectOutputStream.writeObject(student);
        response.getWriter().println("Success....!!");
        response.getWriter().println("list of student ---> <a href=\"\">daftar.jsp</a>");
    }
}

And the serialized object will be read from “daftar.jsp” file,

<%@page import="com.edw.bean.Student"%>
<%@page import="java.io.ObjectInputStream"%>
<%@page import="java.io.File"%>
<%@page import="java.io.FileInputStream"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Daftar Nama</title>
    </head>
    <body>
        <h1>Registered Name is : </h1>
        <%
            try{
                FileInputStream fileInputStream = new FileInputStream(new File("D:\\test12.txt"));
                ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
                Student student = (Student)objectInputStream.readObject();
                out.print("<h1>"+student.getName()+"</h1>");
            }catch(Exception ex){                
                out.print(ex);
            }            
        %>
    </body>
</html>

Dont forget to register you servlet to web.xml

<?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>StudentServlet</servlet-name>
        <servlet-class>com.edw.servlet.StudentServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>StudentServlet</servlet-name>
        <url-pattern>/StudentServlet</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

Well it’s not too hard isnt it 😉

MyBatis Caching Using OSCache

In this example im trying to create a simple application using MyBatis cache ability. What is cache anyway? A cache is designed to reduce traffic between your application and the database by conserving data already loaded from the database and put it whether in memory or in file. Database access is necessary only when retrieving data that is not currently available in the cache. So basically not all queries are taken from database, but from cache instead.

As you can see here, MyBatis has lots of caching products. But on this example im using OSCache.
First, as always, a simple mysql table

CREATE TABLE contoh
    (
        nama VARCHAR(10) NOT NULL,
        alamat VARCHAR(200),
        PRIMARY KEY (nama)
    )
	
insert into contoh (nama, alamat) values ('edw', 'Jakarta');
insert into contoh (nama, alamat) values ('danu', 'Ciledug');
insert into contoh (nama, alamat) values ('kamplenk', 'Tangerang');
insert into contoh (nama, alamat) values ('tebek', 'BSD');
insert into contoh (nama, alamat) values ('nugie', 'Pamulang');
insert into contoh (nama, alamat) values ('samsu', 'Bandung');

And a simple java bean to represent my table,

package com.edw.bean;

import java.io.Serializable;

public class Contoh implements Serializable {
    private String nama;
    private String alamat;

	// setter and getter

    @Override
    public String toString(){
        return nama+" : "+alamat;
    }
}

And a simple java interface to create query method

package com.edw.mapper;

import com.edw.bean.Contoh;
import java.util.List;

public interface ContohMapper {    
    List<Contoh> selectAll();
}

My xml query, please take a look at line 5.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.edw.mapper.ContohMapper" >
    
	<cache type="org.mybatis.caches.oscache.OSCache"/>

    <resultMap id="ContohMap" type="com.edw.bean.Contoh" >
        <id column="nama" property="nama" jdbcType="VARCHAR" />
        <result column="alamat" property="alamat" jdbcType="VARCHAR" />
    </resultMap>
    
    <select id="selectAll" resultMap="ContohMap">
        SELECT * FROM contoh
    </select>
</mapper>

And my xml configuration to load all my xml queries,

<?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>
   <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="UNPOOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost/test"/>
                <property name="username" value="root"/>
                <property name="password" value=""/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/edw/xml/ContohMapper.xml" />
    </mappers>
</configuration>

A java class to load all my xml configurations,

package com.edw.config;

import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisSqlSessionFactory {

    protected static final SqlSessionFactory FACTORY;

    static {
        try {
            Reader reader = Resources.getResourceAsReader("com/edw/xml/Configuration.xml");
            FACTORY = new SqlSessionFactoryBuilder().build(reader);
        } catch (Exception e){
            throw new RuntimeException("Fatal Error.  Cause: " + e, e);
        }
    }

    public static SqlSessionFactory getSqlSessionFactory() {
        return FACTORY;
    }
}

Now i create my main java class.

package com.edw.main;

import com.edw.bean.Contoh;
import com.edw.config.MyBatisSqlSessionFactory;
import com.edw.mapper.ContohMapper;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;

public class Main {
    
    private Logger logger = Logger.getLogger(this.getClass());
    
    public Main(){       
    }
    
    private void execute(){
        // test caching by doing select queries for 10 times
        for (int i = 0; i < 10; i++) {
            SqlSession session = MyBatisSqlSessionFactory.getSqlSessionFactory().openSession();
            ContohMapper mapper = session.getMapper(ContohMapper.class);
            List<Contoh> contohs = mapper.selectAll();
            for (Contoh contoh : contohs) {
                logger.debug(contoh);
            }
            session.close();
            
            try {
                logger.debug("sleeping for 3 seconds");
                Thread.sleep(3000);
            } catch (Exception e) {
            }
        }        
    }

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

Last, is create 2 properties file. One is for log4j configuration, and another one for oscache configuration.
This is my log4j.properties

# Global logging configuration
log4j.rootLogger=DEBUG,stdout

# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%c{1}] %-5p %c:%L - %m%n

And this is my oscache.properties

cache.capacity=1000
cache.memory=true
cache.algorithm=com.opensymphony.oscache.base.algorithm.LRUCache

If you run the application, you’ll notice that for the second queries it will take from cache instead of database. This is what written on my log console.

2012-05-20 02:06:11,687 [Connection] DEBUG java.sql.Connection:27 - ooo Connection Opened
2012-05-20 02:06:11,688 [AbstractConcurrentReadCache] DEBUG com.opensymphony.oscache.base.algorithm.AbstractConcurrentReadCache:694 - get called (key=1247278887:1786588787:com.edw.mapper.ContohMapper.selectAll:0:2147483647:SELECT * FROM contoh)
2012-05-20 02:06:11,688 [LoggingCache] DEBUG org.apache.ibatis.cache.decorators.LoggingCache:27 - Cache Hit Ratio [com.edw.mapper.ContohMapper]: 0.6666666666666666
2012-05-20 02:06:11,689 [Main] DEBUG com.edw.main.Main:31 - edw : Jakarta
2012-05-20 02:06:11,689 [Main] DEBUG com.edw.main.Main:31 - danu : Ciledug
2012-05-20 02:06:11,692 [Main] DEBUG com.edw.main.Main:31 - kamplenk : Tangerang
2012-05-20 02:06:11,692 [Main] DEBUG com.edw.main.Main:31 - tebek : BSD
2012-05-20 02:06:11,692 [Main] DEBUG com.edw.main.Main:31 - nugie : Pamulang
2012-05-20 02:06:11,693 [Main] DEBUG com.edw.main.Main:31 - samsu : Bandung
2012-05-20 02:06:11,693 [Connection] DEBUG java.sql.Connection:27 - xxx Connection Closed
2012-05-20 02:06:11,693 [Main] DEBUG com.edw.main.Main:36 - sleeping for 3 seconds
BUILD STOPPED (total time: 8 seconds)

This is my project structure on Netbeans7
mybatis oscache project structure

Why Java? Buat Apa Belajar Java?

Banyak kawan gw yang bertanya, apa sih untungnya gw belajar java? Apa sih yang gw dapet dari belajar java? Kira-kira investasi waktu belajar java, menguntungkan apa engga yah?

Coba gw share apa yang gw dapet dari thread programmer java di kaskus, semoga bisa menjawab kegalauan temen-temen gw semua.

why java?

1. Java adalah bahasa pemrograman yang verbose, static dan normalnya cuma ada 1 cara untuk melakukan sesuatu.
Tidak seperti Perl yang TIMTOWTDI (There Is More Than One Way To Do It) sehingga code yang dibikin pakai Java gampang dipahami oleh orang lain yang tidak bikin code itu. Akibatnya code Java bisa dipelihara dengan mudah oleh suatu team.

2. Dukungan terhadap database dan transaksi yang sangat bagus.
Sebagai contoh Java EE dari sejak awal mendukung declarative transaction management. Ini feature penting buat enterprise yang jarang didukung platform lain.

3. Web Java berjalan dalam suatu app server.
App server ini bisa mengatur dan memonitor pemakaian resource hardware dari applikasi Java. Jadi aplikasi Java berjalan dalam suatu lingkungan yang terkelola (managed environment).

4. Language nya kaku, jadi enak buat sesuatu yang besar.
Karena ke-kaku-an ini bisa di-lihat sebagai fondasi. Name spacingnya Java bagus, portabel, enak bikin library codenya. Kekakuan ini biasanya disebut sebagai “Strong and Static typed”. Ini yang membuat compiler bisa membantu pengecekan kode developer. Jadi salah dikit-dikit error. (kalo PHP, ada salah juga gak tahu si developernya )

5. Java Stable dan robust.
Enterprise butuh sesuatu yang stabil dan handal dimana aplikasi-nya bisa jalan bertahun-tahun.

6. Scalable.
Aplikasi Java dapat dengan mudah di-scale horizontal maupun vertical. Ini sangat penting apabila bisnis yang super sibuk ingin menambah resource mesin ke apps yang sudah jalan. Dan di Java horizontal-vertical scalabity memang benar-benar mudah.

7. Open and Liberal.
Ini sangat penting apabila ada masalah dengan bahasa pemrograman, kita bisa tau dimana permasalahannya dan buka source code-nya, terus kita benerin sendiri. Ya memang gampang sih kalau ada masalah kita bisa telpon vendor-nya. Tapi dalam situasi kritis kadang kita perlu buka dan oprek sendiri. Sedangkan bahasa2 tertutup seperti VB dan Delphi hal seperti itu sangat menyulitkan ketika ada masalah dengan bahasa-nya. Itu makanya di Java ada banyak framework2, karena semua-nya terbuka.

sumber : http://www.kaskus.us/showthread.php?t=10402662

Mungkin ada kawan-kawan gw yang lain yang bersedia untuk menambahkan?