Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / database

Oracle Database Table to JAVA Bean Class Converter

0.00/5 (No votes)
25 May 2014CPOL 8.7K  
Oracle database table to Java Beans Class Converter

Introduction

This example shows how you convert Oracle Database table to a JAVA Bean class. It allows you to generate Java Bean classes for your Oracle Database tables. In Java Bean class, Table name, Column name & Datatype name will be mapped into Class name, Data Member name & Datatype name.

Background

This example is dependent on the following libraries:

  1. commons-lang.jar
  2. ojdbc14-10.1.0.2.0.jar

Quick Start

Creating the Class TableBeanMapping

Java
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.lang.WordUtils;

/**
 *
 * @author Debopam
 */
public class TableBeanMapping {

    public static void generateBean(String folderName) {
        try {
            Connection connection = OracleJDBC.GetConnection();
            ColumnDatatypeMapping cdm;
            String sqlSelectTableName = "SELECT TABLE_NAME FROM USER_TABLES";
            PreparedStatement psSelectTable = connection.prepareStatement(sqlSelectTableName);
            ResultSet rsTable = psSelectTable.executeQuery();
            String tableName;
            while (rsTable.next()) {
                cdm = new ColumnDatatypeMapping();
                tableName = rsTable.getString("TABLE_NAME");
                String sqlSelectColumn = "SELECT COLUMN_NAME _
                FROM COLS WHERE TABLE_NAME='" + tableName + "'";
                PreparedStatement psSelectColumn = connection.prepareStatement(sqlSelectColumn);
                ResultSet rsColumn = psSelectColumn.executeQuery();
                String columnName;
                while (rsColumn.next()) {
                    columnName = rsColumn.getString("COLUMN_NAME");
                    String sqlSelectDatatype = "SELECT DATA_TYPE _
                    FROM COLS WHERE TABLE_NAME='" + tableName + "' _
                    AND COLUMN_NAME='" + columnName + "'";
                    PreparedStatement psSelectDatatype = connection.prepareStatement(sqlSelectDatatype);
                    ResultSet rsDatatype = psSelectDatatype.executeQuery();
                    String datatypeName;
                    while (rsDatatype.next()) {
                        datatypeName = rsDatatype.getString("DATA_TYPE");
                        cdm.put(columnName, datatypeName);
                    }
                    psSelectDatatype.close();
                    rsDatatype.close();
                }
                psSelectColumn.close();
                rsColumn.close();
                writeBean(folderName, tableName, cdm);
            }
            psSelectTable.close();
            rsTable.close();
        } catch (SQLException ex) {
            Logger.getLogger(TableBeanMapping.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private static void writeBean(String folderName, String tableName, ColumnDatatypeMapping cdm) {
        FileWriter fileWriter;
        BufferedWriter bufferedWriter;
        StringBuilder fileContent;
        String className = getConventionalClassName(tableName);
        SQLJavaDatatypeMapping sqlJavaDatatypeMapping = new SQLJavaDatatypeMapping();
        try {
            fileWriter = new FileWriter(folderName + "\\" + className + ".java");
            bufferedWriter = new BufferedWriter(fileWriter);
            fileContent = new StringBuilder();
            fileContent.append("/*");
            fileContent.append("\n* File\t\t: ").append(className).append(".java");
            fileContent.append("\n* Date Created\t: ").append(Calendar.getInstance().getTime().toString());
            fileContent.append("\n*/");
            fileContent.append("\n\n");
            fileContent.append("public class ").append(className).append(" {");
            fileContent.append("\n");
            for (ColumnDatatypeEntry entry : cdm.entrySet()) {
                fileContent.append("\n\t");
                fileContent.append("private");
                fileContent.append(" ");
                fileContent.append(sqlJavaDatatypeMapping.getJavaDatatype(entry.getDatatype()));
                fileContent.append(" ");
                fileContent.append(entry.getColumn().toLowerCase());
                fileContent.append(";");
            }

            for (ColumnDatatypeEntry entry : cdm.entrySet()) {
                fileContent.append("\n\n\t");
                fileContent.append("public");
                fileContent.append(" ");
                fileContent.append(sqlJavaDatatypeMapping.getJavaDatatype(entry.getDatatype()));
                fileContent.append(" ");
                fileContent.append(getAccessorMethodName(entry.getColumn().toLowerCase()));
                fileContent.append("() {");
                fileContent.append("\n\t\t").append("return ").append_
                (entry.getColumn().toLowerCase()).append(";");
                fileContent.append("\n\t").append("}");

                fileContent.append("\n\n\t");
                fileContent.append("public");
                fileContent.append(" ");
                fileContent.append("void");
                fileContent.append(" ");
                fileContent.append(getMutatorMethodName(entry.getColumn().toLowerCase()));
                fileContent.append("(");
                fileContent.append(sqlJavaDatatypeMapping.getJavaDatatype(entry.getDatatype()));
                fileContent.append(" ").append(entry.getColumn().toLowerCase());
                fileContent.append(") {");
                fileContent.append("\n\t\t").append("this.").append_
                (entry.getColumn().toLowerCase()).append(" = ").append_
                (entry.getColumn().toLowerCase()).append(";");
                fileContent.append("\n\t").append("}");
            }
            fileContent.append("\n").append("}");

            bufferedWriter.write(fileContent.toString());
            bufferedWriter.close();
        } catch (IOException ex) {
            Logger.getLogger(TableBeanMapping.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static String getConventionalClassName(String str) {
        String conventionalClassName = "";
        String[] splittedStr = str.split("[_]");
        for (int i = 0; i < splittedStr.length; i++) {
            conventionalClassName += WordUtils.capitalizeFully(splittedStr[i]);
        }
        return conventionalClassName;
    }

    public static String getConventionalMethodName(String str) {
        String conventionalClassName = getConventionalClassName(str);
        return Character.toLowerCase(conventionalClassName.charAt(0)) + conventionalClassName.substring(1);
    }

    public static String getAccessorMethodName(String dataMemberName) {
        return "get" + Character.toUpperCase(dataMemberName.charAt(0)) + dataMemberName.substring(1);
    }

    public static String getMutatorMethodName(String dataMemberName) {
        return "set" + Character.toUpperCase(dataMemberName.charAt(0)) + dataMemberName.substring(1);
    }
}

Sample Database Table – MOBILE_VERIFY

Sample Schema

Sample Bean Class – MobileVerify

Java
/*
* File            : MobileVerify.java
* Date Created    : Sun May 25 03:17:00 IST 2014
*/

public class MobileVerify {

    private java.math.BigDecimal otp;
    private String appln_no;
    private java.sql.Timestamp valid_till;
    private java.math.BigDecimal mobile;
    private java.sql.Timestamp log_date;
    private String status;

    public java.math.BigDecimal getOtp() {
        return otp;
    }

    public void setOtp(java.math.BigDecimal otp) {
        this.otp = otp;
    }

    public String getAppln_no() {
        return appln_no;
    }

    public void setAppln_no(String appln_no) {
        this.appln_no = appln_no;
    }

    public java.sql.Timestamp getValid_till() {
        return valid_till;
    }

    public void setValid_till(java.sql.Timestamp valid_till) {
        this.valid_till = valid_till;
    }

    public java.math.BigDecimal getMobile() {
        return mobile;
    }

    public void setMobile(java.math.BigDecimal mobile) {
        this.mobile = mobile;
    }

    public java.sql.Timestamp getLog_date() {
        return log_date;
    }

    public void setLog_date(java.sql.Timestamp log_date) {
        this.log_date = log_date;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }
}

How to Call

Java
// Setting folder path...
String folderPath = "C:\\Users\\Debopam\\Desktop\\JavaBeans";
        
// Generating Java Beans in the specified folder...
TableBeanMapping.generateBean(folderPath);

Limitation

It is just a command line tool now. You can generate Java Beans from Oracle Database only. I hope that I will come up with the next version of this article without these limitations.

Reference

Datatype Mappings.

If you've any doubt, please post your questions. If you really like this article, please share it.

Don’t forget to vote or comment about my writing.


License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)