util

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)

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 😉

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?

Simple Messaging Example using Hessian

According to Wikipedia, Hessian is a binary web service protocol that makes web services usable without requiring a large framework, and without learning a new set of protocols. Because it is a binary protocol, it is well-suited to sending binary data without any need to extend the protocol with attachments.

From what i’ve tested, perhaps it is somekind of light version of remote EJB3 because i dont have to include so many libraries like EJB3. Altough EJB3 and Hessian are not apple-to-apple comparable, because both arent using the same messaging protocol. EJB3 use RMI-IIOP while Hessian use WebService.

So let’s start with the code. First, for the server part (im using tomcat), create a web project on Netbeans 6.9 and creating a simple interface class,

package com.edw.service;

public interface HelloService {
    String sayHelloTo(String target);
}

after that, i create a simple servlet which implements HelloService interface,

package com.edw.servlet;

import com.caucho.hessian.server.HessianServlet;
import com.edw.service.HelloService;

public class HelloServlet extends HessianServlet implements HelloService {

    public String sayHelloTo(String target) {
        return "hello "+target+", have a nice day";
    }
    
}

dont forget to register your 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>HelloServlet</servlet-name>
        <servlet-class>com.edw.servlet.HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>HelloServlet</servlet-name>
        <url-pattern>/HelloServlet</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>

next, is creating the client application. I start with a simple java netbeans project, a main class and an interface, i copied the exact copy of HelloService and then put it on my client project,

package com.edw.service;

public interface HelloService {
    String sayHelloTo(String target);
}

and my main class

package com.edw.main;

import com.caucho.hessian.client.HessianProxyFactory;
import com.edw.service.HelloService;

public class Main {

    String url = "http://localhost:809/HessianServer/HelloServlet";
    HessianProxyFactory factory = new HessianProxyFactory();

    public Main() {
    }

    private void doTest() {
        try {
            HelloService hello = (HelloService) factory.create(HelloService.class, url);
            System.out.println(hello.sayHelloTo("si pepe"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

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

here is the screenshot of my project

This is what the messaging looks like

another good competitor for Spring Http Invoker.
Have fun 😉