This is really hectic to create "Data Model" for each table where there are more than 50 tables in the database. I did search in Google but couldn't find such off the self solution. So I have dig down examples from different source add some extra flavor and created this tutorial . Here is a bare bone structure.
Though I have done this as per my requirement, but you can modify this as per your needs.
Main.Java
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class Main {
public static void main(String[] args) throws Exception {
HashMap<String,String> dataType = new HashMap<String,String>();
dataType.put("bit","boolean");
dataType.put("numeric","int");
dataType.put("bigint","int");
dataType.put("nchar","String");
dataType.put("int","int");
dataType.put("datetime","Date");
dataType.put("smallint","int");
dataType.put("nvarchar","String");
dataType.put("timestamp","Timestamp");
ArrayList<Table> tblArray = new ArrayList<Table>();
String userName = "[username]";
String password = "[password]";
String url = "jdbc:sqlserver:[server path];databaseName=[database name]";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection m_Connection = DriverManager.getConnection(url, userName,
password);
Statement m_Statement = m_Connection.createStatement();
String query = "SELECT * FROM sys.Tables";
ResultSet m_ResultSet = m_Statement.executeQuery(query);
while (m_ResultSet.next()) {
Table tbl = new Table();
tbl.tableName = m_ResultSet.getString(1);
if(!"sysdiagrams".equals(tbl.tableName))
tblArray.add(tbl);
}
for (Table tbl : tblArray) {
// System.out.println("retrieved element: " + tbl.tableName);
String queryBasicTableInfoWithPK = "Select C.COLUMN_NAME, C.DATA_TYPE, Case When Z.CONSTRAINT_NAME Is "
+ "Null Then 0 Else 1 End As IsPartOfPrimaryKey From INFORMATION_SCHEMA.COLUMNS "
+ "As C Outer Apply (Select CCU.CONSTRAINT_NAME From INFORMATION_SCHEMA.TABLE_CONSTRAINTS "
+ "As TC Join INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE As CCU On "
+ "CCU.CONSTRAINT_NAME = TC.CONSTRAINT_NAME Where TC.TABLE_SCHEMA = C.TABLE_SCHEMA "
+ "And TC.TABLE_NAME = C.TABLE_NAME And TC.CONSTRAINT_TYPE = 'PRIMARY KEY' "
+ "And CCU.COLUMN_NAME = C.COLUMN_NAME ) As Z Where C.TABLE_NAME = '"
+ tbl.tableName + "'";
ResultSet queryBasicTableInfoWithPK_ResultSet = m_Statement
.executeQuery(queryBasicTableInfoWithPK);
while (queryBasicTableInfoWithPK_ResultSet.next()) {
// System.out.println(queryBasicTableInfoWithPK_ResultSet.getString(1)+"::"+queryBasicTableInfoWithPK_ResultSet.getString(2)+"::"+queryBasicTableInfoWithPK_ResultSet.getString(3));
tbl.hm.put(queryBasicTableInfoWithPK_ResultSet.getString(1),
queryBasicTableInfoWithPK_ResultSet.getString(2));
if (queryBasicTableInfoWithPK_ResultSet.getString(3)
.equals("1")) {
tbl.pk = queryBasicTableInfoWithPK_ResultSet.getString(1);
}
}
queryBasicTableInfoWithPK_ResultSet.close();
}
for (Table tbl : tblArray) {
//System.out.print("retrieved element: " + tbl.tableName);
Set set = tbl.hm.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while (i.hasNext()) {
Map.Entry me = (Map.Entry) i.next();
// if (me.getKey().equals(tbl.pk))
// System.out.println("=> Primary Key ::: " + tbl.pk);
// System.out.print(me.getKey() + ": ");
// System.out.println(me.getValue());
String queryBasicTableInfoWithFK = "SELECT PK_Table = PK.TABLE_NAME FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS "
+ "C INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME INNER JOIN "
+ "INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME INNER JOIN "
+ "INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME INNER JOIN ( "
+ "SELECT i1.TABLE_NAME, i2.COLUMN_NAME FROM "
+ "INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1 INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 "
+ "ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY' "
+") PT ON PT.TABLE_NAME = PK.TABLE_NAME WHERE FK.TABLE_NAME = '"+tbl.tableName+"' and "
+"CU.COLUMN_NAME = '"+me.getKey()+"'";
ResultSet queryBasicTableInfoWithFK_ResultSet = m_Statement
.executeQuery(queryBasicTableInfoWithFK);
while (queryBasicTableInfoWithFK_ResultSet.next()) {
i.remove();
tbl.hmFK.put(queryBasicTableInfoWithFK_ResultSet.getString(1),"FK");
//System.out.println("FK Table Name "+queryBasicTableInfoWithFK_ResultSet.getString(1));
}
queryBasicTableInfoWithFK_ResultSet.close();
}
}
for (Table tbl : tblArray) {
System.out.println("retrieved element: " + tbl.tableName);
String headerPart = "package com.android.syngenta.db.dao; \r\n";
headerPart += "import java.io.Serializable; \r\n";
headerPart += "import java.sql.Timestamp; \r\n";
headerPart +="import java.sql.Date; \n\r";
headerPart +="import com.j256.ormlite.field.DatabaseField; \r\n";
headerPart +="import com.j256.ormlite.table.DatabaseTable; \r\n";
headerPart +="\r\n \r\n";
headerPart +="@DatabaseTable \r\n";
headerPart +="public class "+tbl.tableName+" implements Serializable \r\n";
headerPart +="{ \r\n";
headerPart +="\r\n \r\n";
headerPart +="private static final long serialVersionUID = 1L; \r\n";
headerPart +="\r\n \r\n";
Set set = tbl.hm.entrySet();
// Get an iterator
Iterator i = set.iterator();
System.out.println("Column: ");
while (i.hasNext()) {
Map.Entry me = (Map.Entry) i.next();
if (me.getKey().equals(tbl.pk))
{
System.out.println("=> Primary Key ::: " + tbl.pk);
if(dataType.get(me.getValue()).equalsIgnoreCase("String"))
headerPart +="@DatabaseField (id = true) \r\n";
else
headerPart +="@DatabaseField (generatedId = true) \r\n";
headerPart +="public "+dataType.get(me.getValue())+" "+me.getKey()+"; \r\n";
headerPart +="\r\n \r\n";
}
else
{
headerPart +="@DatabaseField \r\n";
headerPart +="public "+dataType.get(me.getValue())+" "+me.getKey()+"; \r\n";
headerPart +="\r\n \r\n";
}
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
Set setFK = tbl.hmFK.entrySet();
// Get an iterator
Iterator iFK = setFK.iterator();
System.out.println("Column FK: ");
while (iFK.hasNext()) {
Map.Entry me = (Map.Entry) iFK.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
String tblname = (String) me.getKey();
headerPart +="@DatabaseField (foreign = true) \r\n";
headerPart +="public "+me.getKey()+" "+Character.toLowerCase(tblname.charAt(0)) + tblname.substring(1)+"; \r\n";
headerPart +="\r\n \r\n";
}
System.out.println("============================");
headerPart +="}";
FileWriter fileWriter = null;
try {
File newTextFile = new File("./dao/"+tbl.tableName+".java");
fileWriter = new FileWriter(newTextFile);
fileWriter.write(headerPart);
fileWriter.close();
} catch (IOException ex) {
// Logger.getLogger(WriteStringToFile.class.getName()).log(Level.SEVERE,
// null, ex);
} finally {
try {
if(fileWriter != null)
fileWriter.close();
} catch (IOException ex) {
// Logger.getLogger(WriteStringToFile.class.getName()).log(Level.SEVERE,
// null, ex);
}
}
}
}
}
Table.java
import java.util.HashMap;
public class Table {
String tableName;
HashMap hm = new HashMap();
HashMap hmFK = new HashMap();
String pk;
}
Hope this helps.
Though I have done this as per my requirement, but you can modify this as per your needs.
Main.Java
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class Main {
public static void main(String[] args) throws Exception {
HashMap<String,String> dataType = new HashMap<String,String>();
dataType.put("bit","boolean");
dataType.put("numeric","int");
dataType.put("bigint","int");
dataType.put("nchar","String");
dataType.put("int","int");
dataType.put("datetime","Date");
dataType.put("smallint","int");
dataType.put("nvarchar","String");
dataType.put("timestamp","Timestamp");
ArrayList<Table> tblArray = new ArrayList<Table>();
String userName = "[username]";
String password = "[password]";
String url = "jdbc:sqlserver:[server path];databaseName=[database name]";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection m_Connection = DriverManager.getConnection(url, userName,
password);
Statement m_Statement = m_Connection.createStatement();
String query = "SELECT * FROM sys.Tables";
ResultSet m_ResultSet = m_Statement.executeQuery(query);
while (m_ResultSet.next()) {
Table tbl = new Table();
tbl.tableName = m_ResultSet.getString(1);
if(!"sysdiagrams".equals(tbl.tableName))
tblArray.add(tbl);
}
for (Table tbl : tblArray) {
// System.out.println("retrieved element: " + tbl.tableName);
String queryBasicTableInfoWithPK = "Select C.COLUMN_NAME, C.DATA_TYPE, Case When Z.CONSTRAINT_NAME Is "
+ "Null Then 0 Else 1 End As IsPartOfPrimaryKey From INFORMATION_SCHEMA.COLUMNS "
+ "As C Outer Apply (Select CCU.CONSTRAINT_NAME From INFORMATION_SCHEMA.TABLE_CONSTRAINTS "
+ "As TC Join INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE As CCU On "
+ "CCU.CONSTRAINT_NAME = TC.CONSTRAINT_NAME Where TC.TABLE_SCHEMA = C.TABLE_SCHEMA "
+ "And TC.TABLE_NAME = C.TABLE_NAME And TC.CONSTRAINT_TYPE = 'PRIMARY KEY' "
+ "And CCU.COLUMN_NAME = C.COLUMN_NAME ) As Z Where C.TABLE_NAME = '"
+ tbl.tableName + "'";
ResultSet queryBasicTableInfoWithPK_ResultSet = m_Statement
.executeQuery(queryBasicTableInfoWithPK);
while (queryBasicTableInfoWithPK_ResultSet.next()) {
// System.out.println(queryBasicTableInfoWithPK_ResultSet.getString(1)+"::"+queryBasicTableInfoWithPK_ResultSet.getString(2)+"::"+queryBasicTableInfoWithPK_ResultSet.getString(3));
tbl.hm.put(queryBasicTableInfoWithPK_ResultSet.getString(1),
queryBasicTableInfoWithPK_ResultSet.getString(2));
if (queryBasicTableInfoWithPK_ResultSet.getString(3)
.equals("1")) {
tbl.pk = queryBasicTableInfoWithPK_ResultSet.getString(1);
}
}
queryBasicTableInfoWithPK_ResultSet.close();
}
for (Table tbl : tblArray) {
//System.out.print("retrieved element: " + tbl.tableName);
Set set = tbl.hm.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while (i.hasNext()) {
Map.Entry me = (Map.Entry) i.next();
// if (me.getKey().equals(tbl.pk))
// System.out.println("=> Primary Key ::: " + tbl.pk);
// System.out.print(me.getKey() + ": ");
// System.out.println(me.getValue());
String queryBasicTableInfoWithFK = "SELECT PK_Table = PK.TABLE_NAME FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS "
+ "C INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME INNER JOIN "
+ "INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME INNER JOIN "
+ "INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME INNER JOIN ( "
+ "SELECT i1.TABLE_NAME, i2.COLUMN_NAME FROM "
+ "INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1 INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 "
+ "ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY' "
+") PT ON PT.TABLE_NAME = PK.TABLE_NAME WHERE FK.TABLE_NAME = '"+tbl.tableName+"' and "
+"CU.COLUMN_NAME = '"+me.getKey()+"'";
ResultSet queryBasicTableInfoWithFK_ResultSet = m_Statement
.executeQuery(queryBasicTableInfoWithFK);
while (queryBasicTableInfoWithFK_ResultSet.next()) {
i.remove();
tbl.hmFK.put(queryBasicTableInfoWithFK_ResultSet.getString(1),"FK");
//System.out.println("FK Table Name "+queryBasicTableInfoWithFK_ResultSet.getString(1));
}
queryBasicTableInfoWithFK_ResultSet.close();
}
}
for (Table tbl : tblArray) {
System.out.println("retrieved element: " + tbl.tableName);
String headerPart = "package com.android.syngenta.db.dao; \r\n";
headerPart += "import java.io.Serializable; \r\n";
headerPart += "import java.sql.Timestamp; \r\n";
headerPart +="import java.sql.Date; \n\r";
headerPart +="import com.j256.ormlite.field.DatabaseField; \r\n";
headerPart +="import com.j256.ormlite.table.DatabaseTable; \r\n";
headerPart +="\r\n \r\n";
headerPart +="@DatabaseTable \r\n";
headerPart +="public class "+tbl.tableName+" implements Serializable \r\n";
headerPart +="{ \r\n";
headerPart +="\r\n \r\n";
headerPart +="private static final long serialVersionUID = 1L; \r\n";
headerPart +="\r\n \r\n";
Set set = tbl.hm.entrySet();
// Get an iterator
Iterator i = set.iterator();
System.out.println("Column: ");
while (i.hasNext()) {
Map.Entry me = (Map.Entry) i.next();
if (me.getKey().equals(tbl.pk))
{
System.out.println("=> Primary Key ::: " + tbl.pk);
if(dataType.get(me.getValue()).equalsIgnoreCase("String"))
headerPart +="@DatabaseField (id = true) \r\n";
else
headerPart +="@DatabaseField (generatedId = true) \r\n";
headerPart +="public "+dataType.get(me.getValue())+" "+me.getKey()+"; \r\n";
headerPart +="\r\n \r\n";
}
else
{
headerPart +="@DatabaseField \r\n";
headerPart +="public "+dataType.get(me.getValue())+" "+me.getKey()+"; \r\n";
headerPart +="\r\n \r\n";
}
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
Set setFK = tbl.hmFK.entrySet();
// Get an iterator
Iterator iFK = setFK.iterator();
System.out.println("Column FK: ");
while (iFK.hasNext()) {
Map.Entry me = (Map.Entry) iFK.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
String tblname = (String) me.getKey();
headerPart +="@DatabaseField (foreign = true) \r\n";
headerPart +="public "+me.getKey()+" "+Character.toLowerCase(tblname.charAt(0)) + tblname.substring(1)+"; \r\n";
headerPart +="\r\n \r\n";
}
System.out.println("============================");
headerPart +="}";
FileWriter fileWriter = null;
try {
File newTextFile = new File("./dao/"+tbl.tableName+".java");
fileWriter = new FileWriter(newTextFile);
fileWriter.write(headerPart);
fileWriter.close();
} catch (IOException ex) {
// Logger.getLogger(WriteStringToFile.class.getName()).log(Level.SEVERE,
// null, ex);
} finally {
try {
if(fileWriter != null)
fileWriter.close();
} catch (IOException ex) {
// Logger.getLogger(WriteStringToFile.class.getName()).log(Level.SEVERE,
// null, ex);
}
}
}
}
}
Table.java
import java.util.HashMap;
public class Table {
String tableName;
HashMap hm = new HashMap();
HashMap hmFK = new HashMap();
String pk;
}
Hope this helps.
No comments:
Post a Comment