Cara Generate Bean dan DAO menggunakan Apache Velocity

Generate bean dan DAO merupakan sebuah cara untuk mempercepat pekerjaan kita. Karena dengan sekali klik saja kita sudah bisa membuat semua file-file bean dan DAO. Untuk generate Bean yang dimaksud pada artikel disini adalah bean yang merepresentasikan tabel pada database.

Dalam hal ini saya menulis artikel Cara Generate Bean dan DAO menggunakan Apache Velocity dengan bahan-bahan sebagai berikut:

1. Eclipse

2. Database menggunakan HSQLDB

3. Lib: hsqldb.jar,  velocity-1.7.jar, velocity-1.7-dep.jar

Cara-cara pembuatan:

1. Langkah pertama adalah membuat database menggunakan HSQLDB

2. Membuat file generatornya. File ini untuk generator nya. Berikut sourcode nya:

import java.io.FileWriter;
import java.io.Writer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

public class Generate {

public static Map<String, String> db2JavaTypeMap = new HashMap<>();

public static void main(String [] args) throws Exception {

prepareTypeMapping();

/**
* initial velocity
*/
Velocity.init();

/**
* initial koneksi ke database
*/
Connection con = getHSQLConnection();

/**
* initial template velocity yang akan di generate
*/
Template beanTemplate = Velocity.getTemplate(“DAO.vm”);

List<String> tables = getTables(con);

for (String table : tables) {

VelocityContext context = new VelocityContext();
context.put( “table”, table);
context.put( “columns”, getColumns(con, table));
context.put( “keys”, getKeys(con, table));
context.put( “su”, new StringUtil());

/**
* Membuat file untuk bean/DAO
*/
Writer w = new FileWriter(“dao/” + StringUtil.toggleString(table) + “DAO.java”);

/**
* Menggabungkan antara context dengan file : meleburkan key context yang ada pada file w
*/
beanTemplate.merge(context,  w);

/**
* menjamin agar object Writer w di tulis di memori
*/
w.flush();

}

con.close();

}

/**
* method untuk mapping column type
*/
private static void prepareTypeMapping() {
db2JavaTypeMap.put(“VARCHAR”, “String”);
db2JavaTypeMap.put(“CHARACTER”, “String”);
db2JavaTypeMap.put(“BOOLEAN”, “Boolean”);
db2JavaTypeMap.put(“TIMESTAMP”, “java.util.Date”);
db2JavaTypeMap.put(“BIGINT”, “Long”);
db2JavaTypeMap.put(“INTEGER”, “Integer”);
db2JavaTypeMap.put(“NUMERIC”, “java.math.BigDecimal”);
db2JavaTypeMap.put(“TIME”, “java.util.Date”);
db2JavaTypeMap.put(“SMALLINT”, “Short”);
db2JavaTypeMap.put(“DATE”, “java.util.Date”);
}

/**
*
* @param con
* @param table
* @return List<Column> list of bean column
* @throws SQLException
*/
private static List<Column> getColumns(Connection con, String table) throws SQLException {
List<Column> result = new ArrayList<>();

PreparedStatement ps = null;
String query = “SELECT COLUMN_NAME, TYPE_NAME FROM INFORMATION_SCHEMA.SYSTEM_COLUMNS WHERE TABLE_SCHEM = ‘PUBLIC’ AND TABLE_NAME = ?”;

ps = con.prepareStatement(query);
ps.setString(1, table);
ResultSet rs = ps.executeQuery();

while (rs.next()) {
Column c  = new Column();
c.name = rs.getString(1);
c.type = (db2JavaTypeMap.get(rs.getString(2))!=null?db2JavaTypeMap.get(rs.getString(2)):rs.getString(2));
result.add(c);
}

return result;
}

/**
*
* @param con
* @param table
* @return List<String> List of Column Name
* @throws SQLException
*/
private static List<String> getKeys(Connection con, String table) throws SQLException {
List<String> result= new ArrayList<>();

PreparedStatement ps = null;
String query = “SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_SCHEMA = ‘PUBLIC’ AND TABLE_NAME = ?”;
ps = con.prepareStatement(query);
ps.setString(1, table);

ResultSet rs = ps.executeQuery();

while (rs.next()) {
result.add(rs.getString(1));
}

return result;

}

/**
*
* @param con
* @return List<String> list of table name
* @throws SQLException
*/
private static List<String> getTables(Connection con) throws SQLException {
List<String> result= new ArrayList<>();

PreparedStatement ps = null;
String query = “SELECT TABLE_NAME FROM INFORMATION_SCHEMA.SYSTEM_TABLES WHERE TABLE_SCHEM = ‘PUBLIC'”;
ps = con.prepareStatement(query);

ResultSet rs = ps.executeQuery();

while (rs.next()) {
result.add(rs.getString(1));
}

return result;

}

/**
* Method untuk membuat koneksi ke database
* @return Connection
* @throws Exception
*/
private static Connection getHSQLConnection() throws Exception {
Class.forName(“org.hsqldb.jdbcDriver”);
System.out.println(“Driver Loaded.”);
String url = “jdbc:hsqldb:file:D:\\Database\\databaseposv1.0”;
return DriverManager.getConnection(url, “SA”, “”);
}

}

3. String Util merupakan kelas bantuan untuk template agar secara penulisan bisa bersifat seperti method setter(mutator) dan getter(accessor)

public class StringUtil {

public static String toggleString(String ori){

StringBuffer sb = new StringBuffer();

for (String segment : ori.split(“_”)) {
sb.append(segment.substring(0, 1).toUpperCase());
if (segment.length() > 1) sb.append(segment.substring(1).toLowerCase());
}

return sb.toString();

}

public static String camelString(String ori){

String toggle = toggleString(ori);

StringBuffer sb = new StringBuffer();

sb.append(toggle.substring(0, 1).toLowerCase());
if (toggle.length() > 1) sb.append(toggle.substring(1));

return sb.toString();

}
}

4.  Template bean.vm

public class ${su.toggleString($table)} {

#foreach( $column in $columns )
$column.type ${su.camelString($column.name)};
#end

#foreach( $column in $columns )
public $column.type get${su.toggleString($column.name)}(){
return ${su.camelString($column.name)};
};

public void set${su.toggleString($column.name)}($column.type ${su.camelString($column.name)}){
this.${su.camelString($column.name)} = ${su.camelString($column.name)};
};

#end

}

5. template DAO.vm

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.RowMapper;

import com.agci.apf.fw.definition.module.DAO;

public class ${su.toggleString($table)}DAO extends DAO<${su.toggleString($table)}> {

static String SQL_INSERT = new StringBuffer(“INSERT INTO $table (” )
#foreach( $column in $columns )
.append(“$column.name #if( $foreach.hasNext ),#end “)
#end
.append(“) VALUES (#foreach( $column in $columns )?#if( $foreach.hasNext ),#end#end)” ).toString();

static String SQL_UPDATE = new StringBuffer(“UPDATE $table SET ” )
#foreach( $column in $columns )
.append(“$column.name #if( $foreach.hasNext ),#end “)
#end
.append(“WHERE #foreach( $key in $keys) $key = ?#if( $foreach.hasNext ),#end “).toString();

static String SQL_DELETE = new StringBuffer(“DELETE FROM $table WHERE 1 = 1 ” )
.append(“AND #foreach( $key in $keys)$key = ?#if( $foreach.hasNext ),#end #end”).toString();

@Override
public ${su.toggleString($table)} retrieve(${su.toggleString($table)} bean) {
List<${su.toggleString($table)}> list = retriveAll(#foreach( $key in $keys) bean.get${su.toggleString($key)}()#if( $foreach.hasNext ),#end #end);
return (list.size()<1 ? null : list.get(0));
}

@Override
public void insert(${su.toggleString($table)} bean) {
try{
jdbcTemplateObject.update( SQL_INSERT,#foreach( $column in $columns ) bean.get${su.toggleString($column.name)}()#if( $foreach.hasNext ),#end #end);
}catch(DataAccessException dae){
throw dae;
}
}

@Override
public void update(${su.toggleString($table)} bean) {
try{
jdbcTemplateObject.update( SQL_UPDATE,#foreach( $column in $columns ) bean.get${su.toggleString($column.name)}(), #end #foreach( $key in $keys ) #end bean.get${su.toggleString($key)}()#if( $foreach.hasNext ),#end #end);
}catch(DataAccessException dae){
throw dae;
}
}

@Override
public void delete(${su.toggleString($table)} bean) {
try{
jdbcTemplateObject.update( SQL_DELETE,#foreach( $key in $keys ) bean.get${su.toggleString($key)}()#if( $foreach.hasNext ),#end #end);
}catch(DataAccessException dae){
throw dae;
}
}

@Override
protected StringBuffer buildQuery(Object… objects) {
StringBuffer SQL = new StringBuffer(“SELECT#foreach( $column in $columns ) $column.name#if( $foreach.hasNext ),#end#end FROM $table WHERE 1 = 1 “);
#set( $count = -1 )
#foreach( $column in $columns )
#set( $count = $count + 1 )
if (objects.length >= $velocityCount && objects[$count] != null) SQL.append(“AND $column.name = ? “);
#end
SQL.append(” ORDER BY#foreach( $key in $keys) $key#if( $foreach.hasNext ),#end #end”);
return SQL;
}

@Override
protected RowMapper<${su.toggleString($table)}> rowMapper() {
return new RowMapper<${su.toggleString($table)}>() {
@Override
public ${su.toggleString($table)} mapRow(ResultSet rs, int arg1) throws SQLException {
${su.toggleString($table)} bean = new ${su.toggleString($table)}();
#foreach( $column in $columns )
bean.set${su.toggleString($column.name)}(rs.get${column.type}(“${column.name}”));
#end
return bean;
}
};
}

}

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s