Click here to Skip to main content
12,758,605 members (31,538 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

5.5K views
1 bookmarked
Posted 24 May 2014

Oracle Database Table to JAVA Bean Class Converter

, 24 May 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
Oracle Database Table to JAVA Bean Class Converter

Source Files

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

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

/*
* 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

// 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

If you have any doubts, 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)

Share

About the Author

Debopam Pal
Software Developer National Informatics Centre (NIC)
India India
Hello! Myself Debopam Pal. I've completed my MCA degree from West Bengal University of Technology at 2013. I'm from India. I’ve started to work with MS Technologies in 2013 specially in C# 4.0, ASP.NET 4.0. I've also worked in PHP 5. Now I work in JAVA/J2EE, Struts2. Currently I'm involved in a e-Governance Project since Jan, 2014. In my leisure time I write Blog, Articles as I think that every developer should contribute something otherwise resource will be finished one day. Thank you for your time.

Visit: Linkedin Profile | Facebook Profile | Google+ Profile | CodeProject Profile

You may also be interested in...

Pro

Comments and Discussions

 
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170217.1 | Last Updated 25 May 2014
Article Copyright 2014 by Debopam Pal
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid