diff --git a/.gitignore b/.gitignore
deleted file mode 100644
index b757522..0000000
--- a/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-target/
-*~
\ No newline at end of file
diff --git a/README.md b/README.md
index 6b87867..4f13ad6 100644
--- a/README.md
+++ b/README.md
@@ -1,37 +1,36 @@
# sql2java #
-This is a fork of an abandoned project on SourceForge by the same name . It is heavily modified from the original version. I started using this around 2005 as a quick & dirty way to generate Java beans and data access managers from a SQL database. I still use it, as I have found many ORM tools like Hibernate to be unweildy and more trouble than they're worth.
+This is a fork of an abandoned project on SourceForge by the same name . It is heavily modified from the original version. I started using this around 2005 as a quick & dirty way to generate Java beans and data access managers from a SQL database. I still use it, as I have found many ORM tools like Hibernate to be unweildy and more trouble than they're worth. Other things that look interesting to me these days are JDBI which puts nice Java idioms on top of SQL and JDBC, ActiveJDBC which walks a nice line between JDBC and the active record pattern, and Ebean which is an ORM, but feels right.
This differs from the original project in the following ways:
-- Build uses Maven. Packaged as a Maven plugin. sql2java-maven-plugin and sql2java-lib are in Maven Central.
-- New Maven plugin (sqlfile) for sourcing a SQL DDL before generation.
-- sql2java-lib runtime library is now a mandatory dependency.
+- Build uses Maven. Packaged as a Maven plugin.
- No more web widgets or factories. Just beans and managers.
- *Managers return Lists instead of arrays.
- Manager class is gone. BaseManager now takes a DataSource directly.
- Generates a (SchemaName)Database.java factory with get*Manager() methods for all managers. Intended as an easy entry point to extend as your application's DAO.
-- Management of transactions from the (SchemaName)Database.java class.
- Uses generics to make the code more concise (and requires Java 1.5)
- Not sure if anything but MySQL and HSQL support works anymore. PostgreSQL did work a while ago, but haven't checked in a bit.
To do in the future:
-- Add an interface for a cache providing a few convenience methods on top of a *Manager: T get(Id), List get(List), List get(Key). Add optional runtime library with cache implementations.
-- The CodeWriter and Database classes are messy and fragile. Port to use SchemaCrawler . Also look at jOOQ and see what they're doing.
-- Do something with foreign key mappings that is sane against bad definitions.
-- Do something better with compound primary keys (despite thinking they're a bad design decision).
+- Allow interfaces in globals that don't relate to the schema (DaoManager, BaseManager, DaoBean) to be skipped so they can be elsewhere in the user's project or in an imported runtime library.
+- Add an interface for a cache providing a few convenience methods on top of a *Manager: T get(Id), List get(List), List get(Key)
+- Provide a optional runtime library with cache implementations.
+- The CodeWriter and Database classes are messy and fragile. Port to use SchemaCrawler
+- Transactions?
+- Do something with foreign key mappings that is sane against bad definitions?
- Move the properties defined in the file into the Maven plugin definition. Allow a list of tables to be specified for generation.
-### Using the generator: ###
-Easiest way to try it out is to copy the structure in sql2java-test/.
+### Using: ###
+To try it out, copy src/test/config/test.properties into your project and edit to reflect your databases's properties.
Add the following to your POM file's build section:
- com.github.xgp
+ net.sourceforgesql2java-maven-plugin
- ${sql2java.version}
+ 1.0-SNAPSHOTsql2java
@@ -41,24 +40,11 @@ Add the following to your POM file's build section:
- ${project.build.directory}/generated-sources/sql2java
- ${project.basedir}/src/main/resources/sql2java.properties
- org.hsqldb.jdbc.JDBCDriver
- jdbc:hsqldb:file:${project.build.directory}/databases/test
- SA
-
- PUBLIC
- com.test
+ ${project.basedir}/src/main/java
+ ${project.basedir}/src/main/resources/sql2java.properties
-
-
-
- org.hsqldb
- hsqldb
- ${hsqldb.version}
-
-
-
+
+ ...
@@ -68,45 +54,13 @@ And run:
There is a log at target/velocity.log that will tell you if anything failed, and running Maven with the -e flag should be somewhat informative.
-### Using the generated code: ###
-Given the schema example in sql2java-test/src/main/sql/00-test.sql:
-
- // Create a Database from your DataSource
- PublicDatabase db = new PublicDatabase(ds);
-
- // Transactionally create some rows
- try {
- db.beginTransaction(Txn.Isolation.REPEATABLE_READ);
- Person s0 = db.createBean(Person.class);
- s0.setUsername("hansolo");
- s0.setFirstName("Harrison");
- s0.setLastName("Ford");
- s0.setCreateDate(new Date());
- s0 = db.save(s0);
- Phone m0 = db.createBean(Phone.class);
- m0.setPersonId(s0.getId());
- m0.setPhoneType(1);
- m0.setPhoneNumber("+14105551212");
- m0.setCreateDate(new Date());
- m0 = db.save(m0);
- db.commitTransaction();
- } finally {
- db.endTransaction();
- }
-
- // Find the rows
- Person s1 = db.loadUniqueByWhere(Person.class, "WHERE USERNAME='hansolo'");
- Phone m1 = db.loadUniqueByWhere(Phone.class, "WHERE PHONE_NUMBER='+14105551212'");
-
- // Delete the rows (auto-commit)
- db.deleteByWhere(Phone.class, "WHERE PHONE_NUMBER='+14105551212'");
- db.deleteByWhere(Person.class, "WHERE USERNAME='hansolo'");
-
### Customizing: ###
The Velocity templates used by the code generator are in src/main/resources. If you add a new template, you must specify it in your properties file under mgrwriter.templates.perschema or mgrwriter.templates.pertable.
### Dependencies: ###
-Runtime dependencies for the generated code are sql2java-lib, slf4j for logging, and whatever JDBC driver you need for your database.
+Runtime dependencies for the generated code are slf4j for logging, and whatever JDBC driver you need for your database.
### Feedback: ###
Please submit a pull request if you'd like to see something changed.
+
+Does anyone else use this? Let me know if you are a user (of this or some sql2java variant). The occasion of meeting users of old/obscure projects that I use has been known to produce free beer in San Francisco.
diff --git a/pom.xml b/pom.xml
index 7e72278..685ed3f 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1,82 +1,81 @@
-
+4.0.0
- com.github.xgp
- sql2java
- pom
- 0.9.1-SNAPSHOT
- sql2java
- sql2java code generator
- https://github.com/xgp/sql2java
+ net.sourceforge
+ sql2java-maven-plugin
+ maven-plugin
+ 1.0-SNAPSHOT
+ sql2java-maven-plugin
+
+
+
+
+ org.apache.maven.wagon
+ wagon-webdav
+ 1.0-beta-2
+
+
+
+
+ maven-compiler-plugin
+ 2.0.2
+
+ 1.5
+ 1.5
+
+
+
+
+
+
+
+ org.apache.ant
+ ant
+ [1.7.0,)
+
+
+ java2html
+ j2h
+ [1.2,)
+
+
+ velocity
+ velocity
+ 1.5
+
+
+ velocity
+ velocity-dep
+ 1.4
+
+
+ hsqldb
+ hsqldb
+ 1.8.0.10
+ runtime
+
+
+ mysql
+ mysql-connector-java
+ [5.1,)
+ runtime
+
+
+ org.apache.maven
+ maven-plugin-api
+ 2.0
+
+
+ junit
+ junit
+ 3.8.1
+ test
+
+
-
- com.github.xgp
- oss-parent
- 0.1
-
-
UTF-8
- UTF-8
- 1.5
- 2.3.4
- 1.7.22
-
- https://github.com/xgp/sql2java
- scm:git:git://github.com/xgp/sql2java.git
- scm:git:git@github.com:xgp/sql2java.git
- master
-
-
-
-
- GNU Library General Public License version 2.0 (LGPLv2)
- https://www.gnu.org/licenses/lgpl-2.0.txt
-
-
-
-
-
- Garth
- https://github.com/xgp
-
-
-
-
- sql2java-lib
- sql2java-maven-plugin
-
-
-
-
-
- org.slf4j
- slf4j-api
- ${slf4j.version}
-
-
- org.slf4j
- slf4j-simple
- ${slf4j.version}
-
-
- org.hsqldb
- hsqldb
- ${hsqldb.version}
-
-
- org.hsqldb
- sqltool
- ${hsqldb.version}
-
-
- junit
- junit
- 4.12
-
-
-
-
diff --git a/sql2java-lib/pom.xml b/sql2java-lib/pom.xml
deleted file mode 100644
index c4a5333..0000000
--- a/sql2java-lib/pom.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-
-
- 4.0.0
- com.github.xgp
- sql2java-lib
- jar
- sql2java-lib
-
-
- com.github.xgp
- sql2java
- 0.9.1-SNAPSHOT
-
-
-
-
- org.slf4j
- slf4j-api
- compile
-
-
-
-
diff --git a/sql2java-lib/src/main/java/net/sourceforge/sql2java/lib/BaseManager.java b/sql2java-lib/src/main/java/net/sourceforge/sql2java/lib/BaseManager.java
deleted file mode 100644
index e95ad01..0000000
--- a/sql2java-lib/src/main/java/net/sourceforge/sql2java/lib/BaseManager.java
+++ /dev/null
@@ -1,1121 +0,0 @@
-package net.sourceforge.sql2java.lib;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.StringReader;
-import java.math.BigDecimal;
-import java.sql.Clob;
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.sql.Types;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.Collections;
-import java.util.List;
-import javax.sql.DataSource;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Base data access manager.
- */
-public abstract class BaseManager implements DaoManager {
- private static final Logger log = LoggerFactory.getLogger(BaseManager.class);
-
- /* set =QUERY for loadUsingTemplate */
- static public final int SEARCH_EXACT = 0;
- /* set %QUERY% for loadLikeTemplate */
- static public final int SEARCH_LIKE = 1;
- /* set %QUERY for loadLikeTemplate */
- static public final int SEARCH_STARTING_LIKE = 2;
- /* set QUERY% for loadLikeTemplate */
- static public final int SEARCH_ENDING_LIKE = 3;
-
- protected BaseManager(DataSource dataSource) {
- this.dataSource = dataSource;
- }
-
- protected DataSource dataSource;
-
- /**
- * Contains all the full fields of the table.
- */
- protected abstract String[] getFullFieldNames();
-
- /**
- * Contains all the fields of the table.
- */
- protected abstract String[] getFieldNames();
-
- /**
- * Field that contains the comma separated fields of the table.
- */
- protected abstract String getAllFullFields();
-
- /**
- * Field that contains the comma separated fields of the table.
- */
- protected abstract String getAllFields();
-
- /**
- * Loads an object from the table using its key field.
- *
- * @return a unique object
- */
- public T loadByPrimaryKey(Integer primaryKey) throws SQLException {
- throw new UnsupportedOperationException();
- }
-
- /**
- * Creates a new bean instance.
- *
- * @return the new bean
- */
- public abstract T createBean();
-
- /**
- * Table managed by this manager
- *
- * @return tablename
- */
- public abstract String getTableName();
-
- /**
- * Deletes rows according to its keys.
- *
- * @return the number of deleted rows
- */
- public int deleteByPrimaryKey(Integer id) throws SQLException {
- throw new UnsupportedOperationException();
- }
-
- /**
- * Loads all the rows from table.
- *
- * @return a List of beans
- */
- public List loadAll() throws SQLException {
- return loadUsingTemplate(null);
- }
-
- /**
- * Loads the given number of rows from table, given the start row.
- *
- * @param startRow the start row to be used (first row = 1, last row = -1)
- * @param numRows the number of rows to be retrieved (all rows = a negative number)
- * @return a List of beans
- */
- public List loadAll(int startRow, int numRows) throws SQLException {
- return loadUsingTemplate(null, startRow, numRows);
- }
-
- /**
- * Retrieves a List of beans given a sql 'where' clause.
- *
- * @param where the sql 'where' clause
- * @return the resulting bean
- */
- public List loadByWhere(String where) throws SQLException {
- return loadByWhere(where, 1, -1);
- }
-
- /**
- * Retrieves a List of beans given a sql where clause and startRow and numRows.
- * It is up to you to pass the 'WHERE' in your where clausis.
- *
- * @param where the sql 'where' clause
- * @param startRow the start row to be used (first row = 1, last row = -1)
- * @param numRows the number of rows to be retrieved (all rows = a negative number)
- * @return the resulting bean List
- */
- public List loadByWhere(String where, int startRow, int numRows) throws SQLException {
- StringBuilder sql = new StringBuilder();
- sql.append("SELECT ").append(getAllFields()).append(" FROM ").append(getTableName()).append(" ").append(where);
- Connection c = null;
- Statement st = null;
- ResultSet rs = null;
- if (log.isTraceEnabled()) log.trace("loadByWhere: {}", sql);
- try {
- c = getConnection();
- st = c.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
- rs = st.executeQuery(sql.toString());
- return decodeResultSet(rs, startRow, numRows);
- } finally {
- close(st, rs);
- releaseConnection(c);
- }
- }
-
- /**
- * Retrieves a List of beans given a sql where clause and array of fields values
- *
- * @param where the sql 'where' clause
- * @param fields object array of fields
- * @return the resulting bean List
- */
- public List loadByWhere(String where, Object... fields) throws SQLException {
- StringBuilder sql = new StringBuilder();
- sql.append("SELECT ").append(getAllFields()).append(" FROM ").append(getTableName()).append(" ").append(where);
- Connection c = null;
- PreparedStatement ps = null;
- ResultSet rs = null;
- if (log.isTraceEnabled()) log.trace("loadByWhere: {}", sql);
- try {
- c = getConnection();
- ps = c.prepareStatement(sql.toString(),
- ResultSet.TYPE_SCROLL_INSENSITIVE,
- ResultSet.CONCUR_READ_ONLY);
- fillPreparedStatement(ps, fields);
- rs = ps.executeQuery();
- return decodeResultSet(rs, 1, -1);
- } finally {
- close(ps, rs);
- releaseConnection(c);
- }
- }
-
- /**
- * Retrieves the unique object given a sql 'where' clause.
- *
- * @param where The sql 'where' clause
- * @return The resulting bean
- */
- public T loadUniqueByWhere(String where) throws SQLException {
- List os = loadByWhere(where);
- if (os != null && os.size() > 0) {
- return os.get(0);
- } else {
- return null;
- }
- }
-
- /**
- * Retrieves the unique object given a sql 'where' clause and a array of field values
- *
- * @param where The sql 'where' clause
- * @param fields object array of fields
- * @return The resulting bean
- */
- public T loadUniqueByWhere(String where, Object... fields) throws SQLException {
- List os = loadByWhere(where, fields);
- if (os != null && os.size() > 0) {
- return os.get(0);
- } else {
- return null;
- }
- }
-
- /**
- * Deletes all rows from table.
- * @return the number of deleted rows.
- */
- public int deleteAll() throws SQLException {
- return deleteByWhere("");
- }
-
- /**
- * Deletes rows from the table using a 'where' clause.
- * It is up to you to pass the 'WHERE' in your where clausis.
- * Attention, if 'WHERE' is omitted it will delete all records.
- *
- * @param where the sql 'where' clause
- * @return the number of deleted rows
- */
- public int deleteByWhere(String where) throws SQLException {
- Connection c = null;
- PreparedStatement ps = null;
- try {
- c = getConnection();
- StringBuilder sql = new StringBuilder("DELETE FROM ").append(getTableName()).append(" ").append(where);
- if (log.isTraceEnabled()) log.trace("deleteByWhere: {}", sql);
- ps = c.prepareStatement(sql.toString());
- return ps.executeUpdate();
- } finally {
- close(ps);
- releaseConnection(c);
- }
- }
-
- public int deleteByWhere(String where, Object... fields) throws SQLException {
- StringBuilder sql = new StringBuilder("DELETE FROM ").append(getTableName()).append(" ").append(where);
- Connection c = null;
- PreparedStatement ps = null;
- if (log.isTraceEnabled()) log.trace("deleteByWhere: {}", sql);
- try {
- c = getConnection();
- ps = c.prepareStatement(sql.toString());
- fillPreparedStatement(ps, fields);
- return ps.executeUpdate();
- } finally {
- close(ps);
- releaseConnection(c);
- }
-
- }
-
- /**
- * Saves the bean into the database.
- *
- * @param bean the bean to be saved
- */
- public T save(T bean) throws SQLException {
- if (bean.isNew())
- return insert(bean);
- else
- return update(bean);
- }
-
- /**
- * Insert the bean into the database.
- *
- * @param bean the bean to be saved
- */
- public T insert(T bean) throws SQLException {
- return insert(bean, false);
- }
-
- /**
- * Insert the bean into the database.
- *
- * @param bean the bean to be saved
- * @param orUpdate on duplicate key update
- */
- public T insert(T bean, boolean orUpdate) throws SQLException {
- return insert(bean, orUpdate, false);
- }
-
- /**
- * Insert the bean into the database.
- *
- * @param bean the bean to be saved
- * @param orUpdate on duplicate key update
- * @param delayed use INSERT DELAYED and don't get generated keys
- */
- public abstract T insert(T bean, boolean orUpdate, boolean delayed) throws SQLException;
-
- /**
- * Update the bean record in the database according to the changes.
- *
- * @param bean the bean to be updated
- */
- public abstract T update(T bean) throws SQLException;
-
- /**
- * Saves a List of beans into the database.
- *
- * @param beans to be saved
- * @return the saved bean List.
- */
- public List save(List beans) throws SQLException {
- for (T bean:beans) {
- save(bean);
- }
- return beans;
- }
-
- /**
- * Insert a List of beans into the database.
- *
- * @param beans to be inserted
- * @return the saved bean List.
- */
- public List insert(List beans) throws SQLException {
- return save(beans);
- }
-
- /**
- * Updates an List of beans into the database.
- *
- * @param beans to be inserted
- * @return the saved bean List.
- */
- public List update(List beans) throws SQLException {
- return save(beans);
- }
-
- /**
- * Loads a unique bean from a template one giving a c
- *
- * @param bean the bean to look for
- * @return the bean matching the template
- */
- public T loadUniqueUsingTemplate(T bean) throws SQLException {
- List beans = loadUsingTemplate(bean);
- if (beans.size() == 0)
- return null;
- if (beans.size() > 1)
- throw new SQLException("More than one element !!");
- return beans.get(0);
- }
-
- /**
- * Loads a List of from a template one.
- *
- * @param bean the template to look for
- * @return all the matching the template
- */
- public List loadUsingTemplate(T bean) throws SQLException {
- return loadUsingTemplate(bean, 1, -1);
- }
-
- /**
- * Loads a List of from a template one, given the start row and number of rows.
- *
- * @param bean the template to look for
- * @param startRow the start row to be used (first row = 1, last row=-1)
- * @param numRows the number of rows to be retrieved (all rows = a negative number)
- * @return all the matching the template
- */
- public List loadUsingTemplate(T bean, int startRow, int numRows) throws SQLException {
- return loadUsingTemplate(bean, startRow, numRows, SEARCH_EXACT);
- }
-
- /**
- * Loads a List of beans from a template one, given the start row and number of rows.
- *
- * @param bean the bean template to look for
- * @param startRow the start row to be used (first row = 1, last row=-1)
- * @param numRows the number of rows to be retrieved (all rows = a negative number)
- * @param searchType exact ? like ? starting like ?
- * @return all the beans matching the template
- */
- public List loadUsingTemplate(T bean, int startRow, int numRows, int searchType) throws SQLException {
- if (log.isTraceEnabled()) log.trace("loadUsingTemplate startRow:{}, numRows:{}, searchType:{}", new Object[] { startRow, numRows, searchType });
- Connection c = null;
- PreparedStatement ps = null;
- StringBuilder sql = new StringBuilder("SELECT " + getAllFields() + " FROM " + getTableName() + " ");
- StringBuilder sqlWhere = new StringBuilder("");
-
- try {
- if (fillWhere(sqlWhere, bean, searchType) == 0) {
- if (log.isTraceEnabled()) log.trace("The bean to look is not initialized... loading all");
- } else {
- sql.append(" WHERE ").append(sqlWhere);
- }
- if (log.isTraceEnabled()) log.trace("loadUsingTemplate: {}", sql);
- c = getConnection();
- int scrollType = ResultSet.TYPE_SCROLL_INSENSITIVE;
- if (startRow != 1) scrollType = ResultSet.TYPE_SCROLL_SENSITIVE;
- ps = c.prepareStatement(sql.toString(),
- scrollType,
- ResultSet.CONCUR_READ_ONLY);
- fillPreparedStatement(ps, bean, searchType);
- return loadByPreparedStatement(ps, startRow, numRows);
- } finally {
- close(ps);
- releaseConnection(c);
- sql = null;
- sqlWhere = null;
- }
- }
-
- /**
- * Deletes rows using a bean template.
- *
- * @param bean the bean object(s) to be deleted
- * @return the number of deleted objects
- */
- public abstract int deleteUsingTemplate(T bean) throws SQLException;
-
- /**
- * Retrieves the number of rows of the table.
- *
- * @return the number of rows returned
- */
- public int countAll() throws SQLException {
- return countWhere("");
- }
-
- /**
- * Retrieves the number of rows of the table with a 'where' clause.
- * It is up to you to pass the 'WHERE' in your where clause.
- *
- * @param where the restriction clause
- * @return the number of rows returned
- */
- public int countWhere(String where) throws SQLException {
- StringBuilder sql = new StringBuilder("SELECT COUNT(*) AS MCOUNT FROM ").append(getTableName()).append(" ").append(where);
- if (log.isTraceEnabled()) log.trace("countWhere: {}", sql);
- Connection c = null;
- Statement st = null;
- ResultSet rs = null;
- try {
- int iReturn = -1;
- c = getConnection();
- st = c.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
- rs = st.executeQuery(sql.toString());
- if (rs.next()) {
- iReturn = rs.getInt("MCOUNT");
- }
- if (iReturn != -1) return iReturn;
- } finally {
- close(st, rs);
- releaseConnection(c);
- }
- throw new SQLException("Error in countWhere");
- }
-
- /**
- * Retrieves the number of rows of the table with a 'where' clause and a fields array.
- *
- * @param where the restriction clause
- * @param fields object array of fields
- * @return the number of rows returned
- */
- public int countWhere(String where, Object... fields) throws SQLException {
- StringBuilder sql = new StringBuilder("SELECT COUNT(*) AS MCOUNT FROM ").append(getTableName()).append(" ").append(where);
- Connection c = null;
- PreparedStatement ps = null;
- ResultSet rs = null;
- if (log.isTraceEnabled()) log.trace("countWhere: {}", sql);
- try {
- int iReturn = -1;
- c = getConnection();
- ps = c.prepareStatement(sql.toString());
- fillPreparedStatement(ps, fields);
- rs = ps.executeQuery();
- if (rs.next()) {
- iReturn = rs.getInt("MCOUNT");
- }
- if (iReturn != -1) return iReturn;
- } finally {
- close(ps, rs);
- releaseConnection(c);
- }
- throw new SQLException("Error in countWhere");
- }
-
- /**
- * Count the number of elements of a specific bean
- *
- * @param bean the bean to look for ant count
- * @return the number of rows returned
- */
- public int countUsingTemplate(T bean) throws SQLException {
- return countUsingTemplate(bean, -1, -1);
- }
-
- /**
- * Count the number of elements of a specific bean, given the start row and number of rows.
- *
- * @param bean the template to look for and count
- * @param startRow the start row to be used (first row = 1, last row=-1)
- * @param numRows the number of rows to be retrieved (all rows = a negative number)
- * @return the number of rows returned
- */
- public int countUsingTemplate(T bean, int startRow, int numRows) throws SQLException {
- return countUsingTemplate(bean, startRow, numRows, SEARCH_EXACT);
- }
-
- /**
- * Count the number of elements of a specific bean given the start row and number of rows and the search type
- *
- * @param bean the template to look for
- * @param startRow the start row to be used (first row = 1, last row=-1)
- * @param numRows the number of rows to be retrieved (all rows = a negative number)
- * @param searchType exact ? like ? starting like ?
- * @return the number of rows returned
- */
- public int countUsingTemplate(T bean, int startRow, int numRows, int searchType) throws SQLException {
- Connection c = null;
- PreparedStatement ps = null;
- StringBuilder sql = new StringBuilder("SELECT COUNT(*) AS MCOUNT FROM " + getTableName());
- StringBuilder sqlWhere = new StringBuilder("");
- try {
- if (fillWhere(sqlWhere, bean, SEARCH_EXACT) == 0) {
- if (log.isTraceEnabled()) log.trace("The bean to look is not initialized... counting all...");
- } else {
- sql.append(" WHERE ").append(sqlWhere);
- }
- if (log.isTraceEnabled()) log.trace("countUsingTemplate: {}", sql);
- c = getConnection();
- ps = c.prepareStatement(sql.toString(),
- ResultSet.TYPE_SCROLL_INSENSITIVE,
- ResultSet.CONCUR_READ_ONLY);
- fillPreparedStatement(ps, bean, searchType);
- return countByPreparedStatement(ps);
- } finally {
- close(ps);
- releaseConnection(c);
- sql = null;
- sqlWhere = null;
- }
- }
-
- /**
- * Retrieves the number of rows of the table with a prepared statement.
- *
- * @param ps the PreparedStatement to be used
- * @return the number of rows returned
- */
- protected int countByPreparedStatement(PreparedStatement ps) throws SQLException {
- ResultSet rs = null;
- try {
- int iReturn = -1;
- rs = ps.executeQuery();
- if (rs.next()) iReturn = rs.getInt("MCOUNT");
- if (iReturn != -1) return iReturn;
- } finally {
- close(rs);
- }
- throw new SQLException("Error in countByPreparedStatement");
- }
-
- /**
- * Decode a ResultSet in a List of objects
- *
- * @param rs the resultset to decode
- * @param startRow the start row to be used (first row = 1, last row = -1)
- * @param numRows the number of rows to be retrieved (all rows = a negative number)
- * @return the resulting bean List
- */
- public List decodeResultSet(ResultSet rs, int startRow, int numRows) throws SQLException {
- List v = new ArrayList();
- int count = 0;
- if (rs.absolute(startRow) && numRows!=0) {
- do {
- v.add(decodeRow(rs));
- count++;
- } while ( (count loadByPreparedStatement(PreparedStatement ps) throws SQLException {
- return loadByPreparedStatement(ps, 1, -1);
- }
-
- /**
- * Loads all the elements using a prepared statement specifying the start row and the number of rows.
- *
- * @param ps the PreparedStatement to be used
- * @param startRow the start row to be used (first row = 1, last row = -1)
- * @param numRows the number of rows to be retrieved (all rows = a negative number)
- * @return a List of beans
- */
- public List loadByPreparedStatement(PreparedStatement ps, int startRow, int numRows) throws SQLException {
- ResultSet rs = null;
- try {
- rs = ps.executeQuery();
- return decodeResultSet(rs, startRow, numRows);
- } finally {
- close(rs);
- }
- }
-
- /**
- * Fills the given StringBuilder with the sql where clausis constructed using the bean and the search type
- * @param sqlWhere the stringbuffer that will be filled
- * @param bean the bean to use for creating the where clausis
- * @param searchType exact ? like ? starting like ?
- * @return the number of clause is returned
- */
- protected abstract int fillWhere(StringBuilder sqlWhere, T bean, int searchType) throws SQLException;
-
- /**
- * Fill the given PreparedStatement with the bean values and a search type
- * @param ps the preparedStatement that will be filled
- * @param bean the bean to use for creating the where clausis
- * @param searchType exact ? like ? starting like ?
- * @return the number of clause is returned
- */
- protected abstract int fillPreparedStatement(PreparedStatement ps, T bean, int searchType) throws SQLException;
-
- /**
- * Fill the given PreparedStatement with the given fields
- * @param ps the preparedStatement that will be filled
- * @param fields the Object array of fields to be filled
- * @return the number of fields filled
- */
- protected int fillPreparedStatement(PreparedStatement ps, Object... fields) throws SQLException {
- for (int i=0;i getDictionary();
- public Map getPkDictionary();
- public String toString(String delim);
-}
diff --git a/sql2java-lib/src/main/java/net/sourceforge/sql2java/lib/DaoManager.java b/sql2java-lib/src/main/java/net/sourceforge/sql2java/lib/DaoManager.java
deleted file mode 100644
index e5c8ad0..0000000
--- a/sql2java-lib/src/main/java/net/sourceforge/sql2java/lib/DaoManager.java
+++ /dev/null
@@ -1,50 +0,0 @@
-package net.sourceforge.sql2java.lib;
-
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.util.List;
-
-/**
- * Data access manager.
- */
-public interface DaoManager {
- public T createBean();
- public String getTableName();
- public T loadByPrimaryKey(Integer id) throws SQLException;
- public int deleteByPrimaryKey(Integer id) throws SQLException;
- public List loadAll() throws SQLException;
- public List loadAll(int startRow, int numRows) throws SQLException;
- public List loadByWhere(String where) throws SQLException;
- public List loadByWhere(String where, Object... fields) throws SQLException;
- public List loadByWhere(String where, int startRow, int numRows) throws SQLException;
- public T loadUniqueByWhere(String where) throws SQLException;
- public T loadUniqueByWhere(String where, Object... fields) throws SQLException;
- public int deleteAll() throws SQLException;
- public int deleteByWhere(String where) throws SQLException;
- public int deleteByWhere(String where, Object... fields) throws SQLException;
- public T save(T bean) throws SQLException;
- public T insert(T bean) throws SQLException;
- public T insert(T bean, boolean orUpdate) throws SQLException;
- public T insert(T bean, boolean orUpdate, boolean delayed) throws SQLException;
- public T update(T bean) throws SQLException;
- public List save(List beans) throws SQLException;
- public List insert(List beans) throws SQLException;
- public List update(List beans) throws SQLException;
- public T loadUniqueUsingTemplate(T bean) throws SQLException;
- public List loadUsingTemplate(T bean) throws SQLException;
- public List loadUsingTemplate(T bean, int startRow, int numRows) throws SQLException;
- public List loadUsingTemplate(T bean, int startRow, int numRows, int searchType) throws SQLException;
- public int deleteUsingTemplate(T bean) throws SQLException;
- public int countAll() throws SQLException;
- public int countWhere(String where) throws SQLException;
- public int countWhere(String where, Object... fields) throws SQLException;
- public int countUsingTemplate(T bean) throws SQLException;
- public int countUsingTemplate(T bean, int startRow, int numRows) throws SQLException;
- public int countUsingTemplate(T bean, int startRow, int numRows, int searchType) throws SQLException;
- public List decodeResultSet(ResultSet rs, int startRow, int numRows) throws SQLException;
- public T decodeRow(ResultSet rs) throws SQLException;
- public T metaDataDecodeRow(ResultSet rs) throws SQLException;
- public List loadByPreparedStatement(PreparedStatement ps) throws SQLException;
- public List loadByPreparedStatement(PreparedStatement ps, int startRow, int numRows) throws SQLException;
-}
diff --git a/sql2java-lib/src/main/java/net/sourceforge/sql2java/lib/Database.java b/sql2java-lib/src/main/java/net/sourceforge/sql2java/lib/Database.java
deleted file mode 100644
index e96f29e..0000000
--- a/sql2java-lib/src/main/java/net/sourceforge/sql2java/lib/Database.java
+++ /dev/null
@@ -1,274 +0,0 @@
-package net.sourceforge.sql2java.lib;
-
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import javax.sql.DataSource;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public abstract class Database {
-
- private static final Logger log = LoggerFactory.getLogger(Database.class);
-
- protected Database(DataSource dataSource) {
- this.dataSource = dataSource;
- this.classMap = new HashMap();
- }
-
- private final DataSource dataSource;
- private final Map classMap;
-
- protected void registerManager(DaoManager manager) {
- Class beanClass = manager.createBean().getClass();
- log.trace("Added mapping for {} : {}", beanClass.getName(), manager.getClass().getName());
- classMap.put(beanClass, manager);
- }
-
- public DaoManager managerForClass(Class type) {
- return (DaoManager)getManagerForClass(type);
- }
-
- public DaoManager getManagerForClass(Class type) {
- DaoManager daoManager = classMap.get(type);
- if (daoManager == null) throw new IllegalArgumentException("No DaoManager found for "+type.getClass().getName());
- return daoManager;
- }
-
- // DAO conveniences
-
- public T createBean(Class type) {
- return (T)getManagerForClass(type).createBean();
- }
-
- public String getTableName(Class> type) {
- return getManagerForClass(type).getTableName();
- }
-
- public T loadByPrimaryKey(Class type, Integer id) throws SQLException {
- return (T)getManagerForClass(type).loadByPrimaryKey(id);
- }
-
- public int deleteByPrimaryKey(Class> type, Integer id) throws SQLException {
- return getManagerForClass(type).deleteByPrimaryKey(id);
- }
-
- public List loadAll(Class type) throws SQLException {
- return (List)getManagerForClass(type).loadAll();
- }
-
- public List loadAll(Class type,int startRow, int numRows) throws SQLException {
- return (List)getManagerForClass(type).loadAll(startRow, numRows);
- }
-
- public List loadByWhere(Class type, String where) throws SQLException {
- return (List)getManagerForClass(type).loadByWhere(where);
- }
-
- public List loadByWhere(Class type, String where, Object... fields) throws SQLException {
- return (List)getManagerForClass(type).loadByWhere(where, fields);
- }
-
- public List loadByWhere(Class type, String where, int startRow, int numRows) throws SQLException {
- return (List)getManagerForClass(type).loadByWhere(where, startRow, numRows);
- }
-
- public T loadUniqueByWhere(Class type, String where) throws SQLException {
- return (T)getManagerForClass(type).loadUniqueByWhere(where);
- }
-
- public T loadUniqueByWhere(Class type, String where, Object... fields) throws SQLException {
- return (T)getManagerForClass(type).loadUniqueByWhere(where, fields);
- }
-
- public int deleteAll(Class> type) throws SQLException {
- return getManagerForClass(type).deleteAll();
- }
-
- public int deleteByWhere(Class> type, String where) throws SQLException {
- return getManagerForClass(type).deleteByWhere(where);
- }
-
- public int deleteByWhere(Class> type, String where, Object... fields) throws SQLException {
- return getManagerForClass(type).deleteByWhere(where, fields);
- }
-
- public T save(T bean) throws SQLException {
- return (T)getManagerForClass(bean.getClass()).save(bean);
- }
-
- public T insert(T bean) throws SQLException {
- return (T)getManagerForClass(bean.getClass()).insert(bean);
- }
-
- public T insert(T bean, boolean orUpdate) throws SQLException {
- return (T)getManagerForClass(bean.getClass()).insert(bean, orUpdate);
- }
-
- public T insert(T bean, boolean orUpdate, boolean delayed) throws SQLException {
- return (T)getManagerForClass(bean.getClass()).insert(bean, orUpdate, delayed);
- }
-
- public T update(T bean) throws SQLException {
- return (T)getManagerForClass(bean.getClass()).update(bean);
- }
-
- public List save(List beans) throws SQLException {
- if (beans == null || beans.size() < 1) return beans;
- Class type = beans.get(0).getClass();
- return (List)getManagerForClass(type).save(beans);
- }
-
- public List insert(List beans) throws SQLException {
- if (beans == null || beans.size() < 1) return beans;
- Class type = beans.get(0).getClass();
- return (List)getManagerForClass(type).insert(beans);
- }
-
- public List update(List beans) throws SQLException {
- if (beans == null || beans.size() < 1) return beans;
- Class type = beans.get(0).getClass();
- return (List)getManagerForClass(type).update(beans);
- }
-
- public T loadUniqueUsingTemplate(T bean) throws SQLException {
- return (T)getManagerForClass(bean.getClass()).loadUniqueUsingTemplate(bean);
- }
-
- public List loadUsingTemplate(Class type, T bean) throws SQLException {
- return (List)getManagerForClass(type).loadUsingTemplate(bean);
- }
-
- public List loadUsingTemplate(T bean, int startRow, int numRows) throws SQLException {
- return (List)getManagerForClass(bean.getClass()).loadUsingTemplate(bean, startRow, numRows);
- }
-
- public List loadUsingTemplate(T bean, int startRow, int numRows, int searchType) throws SQLException {
- return (List)getManagerForClass(bean.getClass()).loadUsingTemplate(bean, startRow, numRows, searchType);
- }
-
- public boolean delete(T bean) throws SQLException {
- if (bean instanceof DaoBean) {
- if (((DaoBean)bean).isNew()) return false;
- else return (getManagerForClass(bean.getClass()).deleteUsingTemplate(bean) > 0);
- } else {
- throw new IllegalArgumentException("Not a DaoBean "+bean.getClass().getName());
- }
- }
-
- public int deleteUsingTemplate(T bean) throws SQLException {
- return getManagerForClass(bean.getClass()).deleteUsingTemplate(bean);
- }
-
- public int countAll(Class> type) throws SQLException {
- return getManagerForClass(type).countAll();
- }
-
- public int countWhere(Class> type, String where) throws SQLException {
- return getManagerForClass(type).countWhere(where);
- }
-
- public int countWhere(Class> type, String where, Object... fields) throws SQLException {
- return getManagerForClass(type).countWhere(where, fields);
- }
-
- public int countUsingTemplate(T bean) throws SQLException {
- return getManagerForClass(bean.getClass()).countUsingTemplate(bean);
- }
-
- public int countUsingTemplate(T bean, int startRow, int numRows) throws SQLException {
- return getManagerForClass(bean.getClass()).countUsingTemplate(bean, startRow, numRows);
- }
-
- public int countUsingTemplate(T bean, int startRow, int numRows, int searchType) throws SQLException {
- return getManagerForClass(bean.getClass()).countUsingTemplate(bean, startRow, numRows, searchType);
- }
-
- public List decodeResultSet(Class type, ResultSet rs, int startRow, int numRows) throws SQLException {
- return (List)getManagerForClass(type).decodeResultSet(rs, startRow, numRows);
- }
-
- public T decodeRow(Class type, ResultSet rs) throws SQLException {
- return (T)getManagerForClass(type).decodeRow(rs);
- }
-
- public T metaDataDecodeRow(Class type, ResultSet rs) throws SQLException {
- return (T)getManagerForClass(type).metaDataDecodeRow(rs);
- }
-
- public List loadByPreparedStatement(Class type, PreparedStatement ps) throws SQLException {
- return (List)getManagerForClass(type).loadByPreparedStatement(ps);
- }
-
- public List loadByPreparedStatement(Class type, PreparedStatement ps, int startRow, int numRows) throws SQLException {
- return (List)getManagerForClass(type).loadByPreparedStatement(ps, startRow, numRows);
- }
-
- // Transactions
-
- private static final ThreadLocal transaction =
- new ThreadLocal() {
- @Override protected Txn initialValue() {
- return null;
- }
- };
-
- static public Txn beginTransaction() {
- if (transaction.get() == null) {
- transaction.set(new Txn());
- } else {
- throw new IllegalStateException("Transaction already begun.");
- }
- return transaction.get();
- }
-
- static public Txn beginTransaction(Txn.Isolation isolation) {
- if (transaction.get() == null) {
- transaction.set(new Txn(isolation));
- } else {
- throw new IllegalStateException("Transaction already begun.");
- }
- return transaction.get();
- }
-
- static public Txn currentTransaction() {
- return transaction.get();
- }
-
- static public void commitTransaction() {
- if (transaction.get() == null) {
- throw new IllegalStateException("No transaction to commit.");
- } else {
- try {
- transaction.get().commit();
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- }
-
- static public void endTransaction() {
- if (transaction.get() == null) {
- throw new IllegalStateException("No transaction to commit.");
- } else if (transaction.get().isActive()) {
- rollbackTransaction();
- }
- transaction.remove();
- }
-
- static public void rollbackTransaction() {
- if (transaction.get() == null) {
- throw new IllegalStateException("No transaction to rollback.");
- } else {
- try {
- transaction.get().rollback();
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- }
-
-}
diff --git a/sql2java-lib/src/main/java/net/sourceforge/sql2java/lib/Txn.java b/sql2java-lib/src/main/java/net/sourceforge/sql2java/lib/Txn.java
deleted file mode 100644
index 8b0c231..0000000
--- a/sql2java-lib/src/main/java/net/sourceforge/sql2java/lib/Txn.java
+++ /dev/null
@@ -1,86 +0,0 @@
-package net.sourceforge.sql2java.lib;
-
-import java.sql.Connection;
-import java.sql.SQLException;
-import javax.sql.DataSource;
-
-public class Txn {
-
- public enum Isolation {
- DEFAULT(-1),
- READ_COMMITTED(java.sql.Connection.TRANSACTION_READ_COMMITTED),
- READ_UNCOMMITTED(java.sql.Connection.TRANSACTION_READ_UNCOMMITTED),
- REPEATABLE_READ(java.sql.Connection.TRANSACTION_REPEATABLE_READ),
- SERIALIZABLE(java.sql.Connection.TRANSACTION_SERIALIZABLE);
- Isolation(int i) {
- this.level = i;
- }
- final int level;
- public int getLevel() { return this.level; }
- }
-
- private final Isolation isolation;
- private DataSource dataSource;
- private boolean active;
- private Connection connection;
-
- public Txn() {
- this.isolation = Isolation.DEFAULT;
- this.active = false;
- }
-
- public Txn(Isolation isolation) {
- this.isolation = isolation;
- this.active = false;
- }
-
- public Txn(DataSource dataSource, Isolation isolation) {
- this.dataSource = dataSource;
- this.isolation = isolation;
- this.active = true;
- }
-
- public void setDataSource(DataSource dataSource) {
- if (this.dataSource != null) throw new IllegalStateException();
- this.dataSource = dataSource;
- this.active = true;
- }
-
- public boolean isDefault() {
- return (isolation == Isolation.DEFAULT);
- }
-
- public boolean isActive() {
- return active;
- }
-
- public void commit() throws SQLException {
- if (connection == null || !active) throw new IllegalStateException();
- try {
- connection.commit();
- } finally {
- active = false;
- connection.close();
- }
- }
-
- public void rollback() throws SQLException {
- if (connection == null || !active) throw new IllegalStateException();
- try {
- connection.rollback();
- } finally {
- active = false;
- connection.close();
- }
- }
-
- public Connection getConnection() throws SQLException {
- if (dataSource == null || !active) throw new IllegalStateException();
- if (connection != null) return connection;
- connection = dataSource.getConnection();
- connection.setAutoCommit(false);
- connection.setTransactionIsolation(isolation.getLevel());
- return connection;
- }
-
-}
diff --git a/sql2java-maven-plugin/pom.xml b/sql2java-maven-plugin/pom.xml
deleted file mode 100644
index f7faa59..0000000
--- a/sql2java-maven-plugin/pom.xml
+++ /dev/null
@@ -1,92 +0,0 @@
-
-
- 4.0.0
- com.github.xgp
- sql2java-maven-plugin
- maven-plugin
- sql2java-maven-plugin
-
-
- com.github.xgp
- sql2java
- 0.9.1-SNAPSHOT
-
-
-
-
-
- org.apache.maven.plugins
- maven-plugin-plugin
- 3.5
-
-
- default-descriptor
-
- descriptor
-
- process-classes
-
-
- help-descriptor
-
- helpmojo
-
- process-classes
-
-
-
-
-
-
-
-
- org.apache.ant
- ant
- 1.10.0
-
-
- java2html
- j2h
- 1.3.1
-
-
- velocity
- velocity
- 1.4
-
-
- velocity
- velocity-dep
- 1.4
-
-
- org.hsqldb
- sqltool
-
-
- org.hsqldb
- hsqldb
- runtime
- true
-
-
- mysql
- mysql-connector-java
- 6.0.5
- runtime
- true
-
-
- org.apache.maven
- maven-plugin-api
- 3.3.9
-
-
- org.apache.maven.plugin-tools
- maven-plugin-annotations
- 3.5
- provided
-
-
-
-
diff --git a/sql2java-maven-plugin/src/main/java/net/sourceforge/sql2java/Database.java b/sql2java-maven-plugin/src/main/java/net/sourceforge/sql2java/Database.java
deleted file mode 100755
index 265885e..0000000
--- a/sql2java-maven-plugin/src/main/java/net/sourceforge/sql2java/Database.java
+++ /dev/null
@@ -1,361 +0,0 @@
-//$Id: Database.java,v 1.1 2005/10/12 18:44:24 framiere Exp $
-
-package net.sourceforge.sql2java;
-
-import java.sql.*;
-import java.util.*;
-import java.io.*;
-import java.util.Vector;
-import java.util.Hashtable;
-
-public class Database
-{
- private String tableTypes[];
- private Connection pConnection;
- private DatabaseMetaData meta;
- private Vector tables;
- private Hashtable tableHash;
- private String driver, url, username, password, catalog, schema, tablenamepattern;
- private boolean retrieveRemarks = true;
-
- public void setOracleRetrieveRemarks(boolean retrieveRemarks) { this.retrieveRemarks = retrieveRemarks;}
- public void setDriver(String driver) { this.driver = driver; }
- public void setUrl(String url) { this.url = url; }
- public void setUsername(String username) { this.username = username; }
- public void setPassword(String password) { this.password = password; }
- public void setCatalog(String catalog) { this.catalog = catalog; }
- public void setTableNamePattern(String tablenamepattern) { this.tablenamepattern = tablenamepattern; }
- public void setTableTypes(String[] tt) { this.tableTypes = tt; }
-
- public boolean getOracleRetrieveRemarks() { return this.retrieveRemarks; }
- public String getDriver() { return driver; }
- public String getUrl() { return url; }
- public String getUsername() { return username; }
- public String getPassword() { return password; }
- public String getCatalog() { return catalog; }
- public String getSchema() { return schema; }
- public String getTableNamePattern() { return tablenamepattern; }
- public String[] getTableTypes() { return tableTypes; }
-
- public void setSchema(String schema)
- {
- if ("null".equalsIgnoreCase(schema))
- this.schema = null;
- else
- this.schema = schema;
- }
-
- public void cleanup() {
- if (pConnection != null) {
- try {
- //HACK
- if (url.contains("jdbc:hsqldb:file")) {
- Statement statement = pConnection.createStatement();
- statement.executeUpdate("SHUTDOWN");
- statement.close();
- }
- } catch (SQLException ignore) {}
- try {
- pConnection.close();
- } catch (SQLException ignore) {}
- }
- }
-
- /**
- * Return an array of tables having foreign key pointing to the
- * passed table.
- */
- public Table[] getRelationTable(Table table)
- {
- Vector vector = new Vector();
-
- for (int iIndex = 0; iIndex < tables.size(); iIndex ++)
- {
- Table tempTable = (Table)tables.get(iIndex);
-
- // skip itself
- if (table.equals(tempTable))
- continue;
-
- // check only for relation table
- if (tempTable.isRelationTable())
- {
- if (tempTable.relationConnectsTo(table))
- {
- if (!vector.contains(tempTable))
- vector.add(tempTable);
- }
- }
- }
- return (Table[])vector.toArray(new Table[0]);
- }
-
- public void load() throws SQLException, ClassNotFoundException
- {
- // Connect to the database
- Class.forName(driver);
-
-
- System.out.println("Connecting to " + username + " on " + url + " ...");
- pConnection = DriverManager.getConnection(url, username, password);
- System.out.println(" Connected.");
- // if (pConnection instanceof oracle.jdbc.driver.OracleConnection)
- // ((oracle.jdbc.driver.OracleConnection)pConnection).setRemarksReporting(getOracleRetrieveRemarks());
-
- meta = pConnection.getMetaData();
- System.out.println(" Database server :" + meta.getDatabaseProductName() + ".");
- tables = new Vector();
- tableHash = new Hashtable();
-
- loadTables();
- loadColumns();
- loadPrimaryKeys();
-
- // loadImportedKeys();
- // loadManyToMany();
- // loadIndexes(); // experimental
- }
-
- public Table[] getTables()
- {
- return (Table[])tables.toArray(new Table[0]);
- }
-
- private void addTable(Table t) {
- tables.addElement(t);
- tableHash.put(t.getName(), t);
- }
-
- public Table getTable(String name) {
- return (Table)tableHash.get(name);
- }
-
- /**
- * Load all the tables for this schema.
- */
- private void loadTables() throws SQLException
- {
- System.out.println("Loading table list according to pattern " + tablenamepattern + " ...");
-
- // tablenamepattern is now a comma-separated list of patterns
- java.util.StringTokenizer st = new java.util.StringTokenizer(tablenamepattern, ",; \t");
- while(st.hasMoreTokens()) {
- String pattern = ((String)st.nextToken()).trim();
- ResultSet resultSet = meta.getTables(catalog, schema, pattern, tableTypes);
- while(resultSet.next())
- {
- Table table = new Table();
- table.setDatabase(this);
- table.setCatalog(resultSet.getString("TABLE_CAT"));
-
- String sch = resultSet.getString("TABLE_SCHEM");
- System.out.println(sch);
- // table.setSchema(resultSet.getString("TABLE_SCHEM"));
- table.setSchema(sch);
-
- table.setName(resultSet.getString("TABLE_NAME"));
- table.setType(resultSet.getString("TABLE_TYPE"));
- table.setRemarks(resultSet.getString("REMARKS"));
- addTable(table);
- System.out.println(" table " + table.getName() + " found");
- }
- resultSet.close();
- }
- }
-
- /**
- * For each table, load all the columns.
- */
- private void loadColumns() throws SQLException
- {
- Table tables[] = getTables();
-
- System.out.println("Loading columns ...");
- boolean b = false;
- for(int i = 0; i < tables.length; i++)
- {
- Table table = tables[i];
- ResultSet resultSet = meta.getColumns(catalog, schema, table.getName(), "%");
- Column c = null;
-
- while(resultSet.next())
- {
- c = new Column();
- c.setDatabase(this);
- c.setCatalog(resultSet.getString("TABLE_CAT"));
- c.setSchema(resultSet.getString("TABLE_SCHEM"));
- c.setTableName(resultSet.getString("TABLE_NAME"));
- c.setName(resultSet.getString("COLUMN_NAME"));
- c.setType(resultSet.getShort("DATA_TYPE"));
- c.setSize(resultSet.getInt("COLUMN_SIZE"));
- c.setDecimalDigits(resultSet.getInt("DECIMAL_DIGITS"));
- c.setRadix(resultSet.getInt("NUM_PREC_RADIX"));
- c.setNullable(resultSet.getInt("NULLABLE"));
- c.setRemarks(resultSet.getString("REMARKS"));
- c.setDefaultValue(resultSet.getString("COLUMN_DEF"));
- c.setOrdinalPosition(resultSet.getInt("ORDINAL_POSITION"));
- table.addColumn(c);
- }
- System.out.println(" " + table.getName() + " found " + table.countColumns() + " columns");
-
- resultSet.close();
- }
- }
-
- /**
- * For each table, load the primary keys.
- */
- private void loadPrimaryKeys() throws SQLException
- {
- System.out.println("Loading primary keys ...");
- Table tables[] = getTables();
-
- for(int i = 0; i < tables.length; i++)
- {
- Table table = tables[i];
- ResultSet resultSet = meta.getPrimaryKeys(catalog, schema, table.getName());
-
- while(resultSet.next())
- {
- Column col = table.getColumn(resultSet.getString("COLUMN_NAME"));
- table.addPrimaryKey(col);
- System.out.println(" " + col.getFullName() + " found");
- }
-
- resultSet.close();
- }
- }
-
- /**
- * For each table, load the imported key.
- *
- * An imported key is the other's table column clone. Its
- * ForeignKeyColName corresponds to the table's column name that
- * points to the other's table.
- */
- private void loadImportedKeys() throws SQLException
- {
- System.out.println("Loading imported keys ...");
- Table tables[] = getTables();
-
- for(int i = 0; i < tables.length; i++)
- {
- Table table = tables[i];
- ResultSet resultSet = meta.getImportedKeys(catalog, schema, table.getName());
- while(resultSet.next())
- {
- String tabName = resultSet.getString("FKTABLE_NAME");
- String colName = resultSet.getString("FKCOLUMN_NAME");
-
- String foreignTabName= resultSet.getString("PKTABLE_NAME");
- String foreignColName= resultSet.getString("PKCOLUMN_NAME");
-
- Column col = getTable(tabName).getColumn(colName);
- Column foreignCol = getTable(foreignTabName).getColumn(foreignColName);
-
- col.addForeignKey(foreignCol);
- foreignCol.addImportedKey(col);
- //getTable(foreignTabName).addImportedKey(col);
-
- System.out.println(" " + col.getFullName() + " -> " + foreignCol.getFullName() + " found ");
- }
-
- resultSet.close();
- }
- }
-
- //
- // could avoid db call.
- // In each current table an entry is:
- // other table column (that points to current table) | current pk column
- // [other table has nb col. == pk length]
- private void loadManyToMany() throws SQLException
- {
- System.out.println("Loading many to many relationships...");
- Table tables[] = getTables();
-
- for(int i = 0; i < tables.length; i++)
- {
- Table table = tables[i];
-
- // if(table.getColumns().length == table.getPrimaryKeys().length)
- {
- ResultSet resultSet = meta.getImportedKeys(catalog, schema, table.getName());
-
- while(resultSet.next())
- {
- String tabName = resultSet.getString("PKTABLE_NAME");
- String colName = resultSet.getString("PKCOLUMN_NAME");
- System.out.println(" many to many " + tabName + " " + colName);
-
- Table pkTable = getTable(tabName);
- Column fkCol = table.getColumn(resultSet.getString("FKCOLUMN_NAME"));
-
- if(pkTable != null)
- {
- Column pkCol = pkTable.getColumn(colName);
-
- if(pkCol != null && fkCol != null)
- {
- pkTable.addManyToManyKey(fkCol, pkCol);
- }
- }
- }
-
- resultSet.close();
- }
- }
- }
-
- /**
- * For each table, load the indexes.
- */
- private void loadIndexes() throws SQLException
- {
- System.out.println("Loading indexes ...");
- Table tables[] = getTables();
-
- for(int i = 0; i < tables.length; i++)
- {
- Table table = tables[i];
- ResultSet resultSet = meta.getIndexInfo(catalog,
- schema,
- table.getName(),
- true,
- true);
- while(resultSet.next())
- {
- String colName = resultSet.getString("COLUMN_NAME");
- String indName = resultSet.getString("INDEX_NAME");
-
- if (colName != null && indName != null) {
- Column col = table.getColumn(colName);
- if (!col.isPrimaryKey())
- System.out.println(" Found interesting index " + indName + " on " +
- colName + " for table " + table.getName());
- }
- }
-
- resultSet.close();
- }
- }
-
- public String[] getAllPackages()
- {
- Vector vector = new Vector();
- for (int iIndex = 0; iIndex < tables.size(); iIndex ++)
- {
- Table table = (Table)tables.get(iIndex);
- String packages[] = table.getLinkedPackages();
- for (int i = 0; i < packages.length; i++)
- {
- if (vector.contains(packages[i]) == false)
- {
- vector.add(packages[i]);
- }
- }
- }
- return (String[])vector.toArray(new String[0]);
- }
-
-}
diff --git a/sql2java-maven-plugin/src/main/java/net/sourceforge/sql2java/maven/AbstractDbMojo.java b/sql2java-maven-plugin/src/main/java/net/sourceforge/sql2java/maven/AbstractDbMojo.java
deleted file mode 100644
index a44d489..0000000
--- a/sql2java-maven-plugin/src/main/java/net/sourceforge/sql2java/maven/AbstractDbMojo.java
+++ /dev/null
@@ -1,48 +0,0 @@
-package net.sourceforge.sql2java.maven;
-
-import org.apache.maven.plugin.AbstractMojo;
-import org.apache.maven.plugins.annotations.Parameter;
-
-/**
- * Common abstract Mojo for plugins with db props.
- * @author garth
- */
-public abstract class AbstractDbMojo extends AbstractMojo {
-
- /**
- * JDBC driver class name.
- */
- @Parameter(property = "driver", defaultValue = "org.hsqldb.jdbcDriver", required = true)
- protected String driver;
-
- /**
- * Database connection string.
- */
- @Parameter(property = "url", defaultValue = "jdbc:hsqldb:file:${project.build.directory}/databases/test", required = true)
- protected String url;
-
- /**
- * Database connection user name.
- */
- @Parameter(property = "user", defaultValue = "SA", required = true)
- protected String user;
-
- /**
- * Database connection user password.
- */
- @Parameter(property = "password", defaultValue = "")
- protected String password;
-
- /**
- * Database catalog
- */
- @Parameter(property = "catalog")
- protected String catalog;
-
- /**
- * Database schema
- */
- @Parameter(property = "schema", defaultValue = "PUBLIC")
- protected String schema;
-
-}
diff --git a/sql2java-maven-plugin/src/main/java/net/sourceforge/sql2java/maven/SqlFileMojo.java b/sql2java-maven-plugin/src/main/java/net/sourceforge/sql2java/maven/SqlFileMojo.java
deleted file mode 100644
index 6577b2e..0000000
--- a/sql2java-maven-plugin/src/main/java/net/sourceforge/sql2java/maven/SqlFileMojo.java
+++ /dev/null
@@ -1,80 +0,0 @@
-package net.sourceforge.sql2java.maven;
-
-import java.io.File;
-import java.io.FilenameFilter;
-import java.io.IOException;
-import java.sql.Connection;
-import java.sql.DriverManager;
-import java.sql.Statement;
-import java.sql.SQLException;
-import java.util.Arrays;
-import net.sourceforge.sql2java.*;
-import org.apache.maven.plugin.MojoExecutionException;
-import org.apache.maven.plugins.annotations.Mojo;
-import org.apache.maven.plugins.annotations.Parameter;
-import org.hsqldb.cmdline.SqlFile;
-
-/**
- * Goal which uses hsqldb's SqlFile to source scripts to a db.
- * @author garth
- */
-@Mojo(name="sqlfile", requiresDirectInvocation=true)
-public class SqlFileMojo extends AbstractDbMojo {
-
- /**
- * Wipe all data and table definitions if they already exist?
- */
- @Parameter(property="deleteData", defaultValue="false")
- private boolean deleteData;
-
- /**
- * The script directory.
- */
- @Parameter(property="scriptDirectory", defaultValue="${project.basedir}/src/main/sql", required=true)
- private File scriptDirectory;
-
- protected File getScriptDirectory() {
- return scriptDirectory;
- }
-
- public void execute() throws MojoExecutionException {
- Connection connection = null;
- try {
- Class.forName(driver);
- connection = DriverManager.getConnection(url, user, password);
-
- //deleteData?
- //hsql:DROP SCHEMA PUBLIC CASCADE
-
- File[] files = scriptDirectory.listFiles(new FilenameFilter() {
- public boolean accept(File dir, String name) {
- return name.toLowerCase().endsWith(".sql");
- }
- });
- Arrays.sort(files);
- for (File file : files) {
- getLog().info(String.format("Processing %s", file));
- SqlFile sqlFile = new SqlFile(file, null, false);
- sqlFile.setConnection(connection);
- sqlFile.execute();
- }
- } catch (Exception e) {
- getLog().error("", e);
- } finally {
- if (connection != null) {
- try {
- //HACK
- if (url.contains("jdbc:hsqldb:file")) {
- Statement statement = connection.createStatement();
- statement.executeUpdate("SHUTDOWN");
- statement.close();
- }
- } catch (SQLException ignore) {}
- try {
- connection.close();
- } catch (SQLException ignore) {}
- }
- }
- }
-
-}
diff --git a/sql2java-test/README b/sql2java-test/README
deleted file mode 100644
index 65c0176..0000000
--- a/sql2java-test/README
+++ /dev/null
@@ -1,18 +0,0 @@
-# Test of sqlfile and sql2java plugins
-
-Use this as a model for how to use the plugin in your environment. E.g.
-- Put your SQL in src/main/sql/NN-blah.sql
-- Use sqlfile plugin in build->plugins to source it into a temporary hsqldb
-- Use sql2java plugin in build->plugins to generate managers and beans to generated source dir
-- Test, etc.
-
-Currently known problem:
-
- [WARNING] Some problems were encountered while building the effective model for net.sourceforge:sql2java-test:jar:1.0-SNAPSHOT
- [WARNING] 'build.plugins.plugin.(groupId:artifactId)' must be unique but found duplicate declaration of plugin net.sourceforge:sql2java-maven-plugin @ net.sourceforge:sql2java-test:[unknown-version], /Users/xgp/projects/sql2java/github/sql2java-test/pom.xml, line 74, column 15
- [WARNING]
- [WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
- [WARNING]
- [WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
-
-This is because, for some reason, my plugin mojos aren't picking up all the properties when they are specified in separate s of the same plugin. Will fix later.
diff --git a/sql2java-test/pom.xml b/sql2java-test/pom.xml
deleted file mode 100644
index 5aaffc0..0000000
--- a/sql2java-test/pom.xml
+++ /dev/null
@@ -1,133 +0,0 @@
-
-
- 4.0.0
- com.github.xgp
- sql2java-test
- jar
- sql2java-test
-
-
- com.github.xgp
- sql2java
- 0.9.1-SNAPSHOT
-
-
-
-
- org.slf4j
- slf4j-api
-
-
- com.github.xgp
- sql2java-lib
- ${project.parent.version}
-
-
- org.slf4j
- slf4j-simple
- test
-
-
- org.hsqldb
- hsqldb
- test
-
-
- org.hsqldb
- sqltool
- test
-
-
- junit
- junit
- test
-
-
-
-
-
-
- com.github.xgp
- sql2java-maven-plugin
- ${project.parent.version}
-
-
- sqlfile
- initialize
-
- sqlfile
-
-
-
-
- true
- ${project.basedir}/src/main/sql
- org.hsqldb.jdbc.JDBCDriver
- jdbc:hsqldb:file:${project.build.directory}/databases/test
- SA
-
- PUBLIC
-
-
-
- org.hsqldb
- hsqldb
- ${hsqldb.version}
-
-
-
-
- com.github.xgp
- sql2java-maven-plugin
- ${project.parent.version}
-
-
- sql2java
- generate-sources
-
- sql2java
-
-
-
-
- ${project.build.directory}/generated-sources/sql2java
- ${project.basedir}/src/main/resources/sql2java.properties
- org.hsqldb.jdbc.JDBCDriver
- jdbc:hsqldb:file:${project.build.directory}/databases/test
- SA
-
- PUBLIC
- com.test
-
-
-
- org.hsqldb
- hsqldb
- ${hsqldb.version}
-
-
-
-
- org.codehaus.mojo
- build-helper-maven-plugin
- 1.12
-
-
- add-source
- generate-sources
-
- add-source
-
-
-
- ${project.build.directory}/generated-sources/sql2java
-
-
-
-
-
-
-
-
-
diff --git a/sql2java-test/src/main/resources/sql2java.properties b/sql2java-test/src/main/resources/sql2java.properties
deleted file mode 100644
index bd7fdd3..0000000
--- a/sql2java-test/src/main/resources/sql2java.properties
+++ /dev/null
@@ -1,116 +0,0 @@
-#
-# PROPERTIES FILE FOR SQL2JAVA
-#
-
-
-#-------------------------------------------------
-# (2/6) CONFIGURE RETRIEVAL OF AUTO GENERATED KEY
-#-------------------------------------------------
-# For those who do not want to read below, please simply pick up the
-# configuration associated with your database.
-#
-# More explanation:
-# When you save a bean whose primary key is numeric and has no value set,
-# we assume that you want sql2java to retrieve a key's value generated
-# on the database side.
-#
-# generatedkey.retrieve can take 4 values:
-#
-# auto - the standard approach when you have a JDBC 3.0 driver.
-#
-# before - the key's value is retrieved before inserting the record.
-#
-# after - the key's value is retrieved after inserting the record
-#
-# none - the key's value is never retrieved, frankly I doubt you
-# want this configuration
-#
-# If you set it to before or after you also need to configure the
-# autogeneratedkey.statement properties.
-#
is replaced at code generation time by the table name.
-# You may adjust this properties to fit your own naming convention.
-#
-# PICK THE CONFIGURATION ASSOCIATED WITH YOUR DATABASE
-# (or create one, but in that case let us know so we can add it here... :-)
-#
-#-- HSQL ------
-#generatedkey.retrieve=after
-#generatedkey.statement=CALL IDENTITY()
-
-#-- IF YOU USE A JDBC 3.0 DRIVER (works with mysql, ORACLE 9, etc..) ------
-generatedkey.retrieve=auto
-generatedkey.statement=
-
-#----------------------------------------------
-# (3/6) GENERATED SOURCE CODE
-#----------------------------------------------
-
-# Package name for the generated source code
-mgrwriter.package=com.test
-
-# Property file to use when initializing Velocity
-#mgrwriter.velocityprops=somefile
-
-# templates (you can generate java files, jsp, etc...)
-
-mgrwriter.templates.loadingpath=templates/velocity/global, \
- templates/velocity/table, \
- templates/velocity/includes
-
-mgrwriter.templates.perschema= database.java.vm
-
-mgrwriter.templates.pertable= bean.java.vm, \
- manager.java.vm
-
-#-----------------------------------------------
-# (4/6) JDBC TYPES Mapping
-#-----------------------------------------------
-#
-# jdbc DATE mapping can be:
-# java.sql.Date
-# java.util.Date
-jdbc2java.date=java.util.Date
-
-# jdbc TIME mapping can be:
-# java.sql.Time
-# java.util.Date
-jdbc2java.time=java.util.Date
-
-# jdbc TIMESTAMP mappning can be:
-# java.sql.Timestamp
-# java.util.Date
-jdbc2java.timestamp=java.util.Date
-
-#-----------------------------------------------
-# (5/6) FILTER OUT CERTAIN TABLES
-#-----------------------------------------------
-#
-# COMMA SEPARATED list of table types to be mapped
-# Commonly seen types are TABLE, VIEW, SYSTEM TABLE, SYNONYM
-jdbc.tabletypes=TABLE
-
-# Table name pattern of tables to be mapped to classes.
-# available wildcard: %
-# defaults to %
-# You can specify several patterns separated by commas.
-jdbc.tablenamepattern=%
-
-# SPACE SEPARATED list of tables to include or exclude. If you specify both,
-# the include list will take priority. If these fields are left commented out,
-# all tables in the specified schema will get mapped to classes
-#mgrwriter.include=Testing
-#mgrwriter.exclude=
-
-#-----------------------------------------------
-# (6/6) CONFIGURE OPTIMISTIC LOCK
-#-----------------------------------------------
-# optimisticlock.type can take 2 values:
-# none - the optimistic lock mechanism is disabled (default).
-# timestamp - the optimistic lock column contains the System.currentTimeMillis() value.
-#
-# optimisticlock.column takes the column name used by optimistic lock mechanism in your database.
-# If this column is not present in some table the optimistic lock is not applied there.
-# the column mapping can be java.lang.Long or java.lang.String.
-# (jdbc type size >= 13 characters)
-optimisticlock.type=timestamp
-optimisticlock.column=version_time
diff --git a/sql2java-test/src/main/resources/sqltool.rc b/sql2java-test/src/main/resources/sqltool.rc
deleted file mode 100644
index ce9728a..0000000
--- a/sql2java-test/src/main/resources/sqltool.rc
+++ /dev/null
@@ -1,4 +0,0 @@
-urlid test
-url jdbc:hsqldb:file:target/databases/test
-username SA
-password
diff --git a/sql2java-test/src/main/sql/00-test.sql b/sql2java-test/src/main/sql/00-test.sql
deleted file mode 100644
index 5e1b542..0000000
--- a/sql2java-test/src/main/sql/00-test.sql
+++ /dev/null
@@ -1,19 +0,0 @@
-CREATE TABLE person (
- id integer GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- username varchar(255) NOT NULL,
- first_name varchar(255) NOT NULL,
- last_name varchar(255) NOT NULL,
- create_date datetime NOT NULL,
- update_date timestamp DEFAULT CURRENT_TIMESTAMP NOT NULL,
- UNIQUE (username)
-);
-
-CREATE TABLE phone (
- id integer GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
- phone_number varchar(30) NOT NULL,
- phone_type integer NOT NULL,
- person_id integer NOT NULL,
- create_date datetime NOT NULL,
- FOREIGN KEY (person_id) REFERENCES person(id),
- UNIQUE (phone_number)
-);
diff --git a/sql2java-test/src/main/sql/01-test.sql b/sql2java-test/src/main/sql/01-test.sql
deleted file mode 100644
index 446e8b0..0000000
--- a/sql2java-test/src/main/sql/01-test.sql
+++ /dev/null
@@ -1,2 +0,0 @@
-insert into person (username, first_name, last_name, create_date) values ('farkhan', 'Farkhan', 'Parambulator', now());
-insert into phone (phone_number, phone_type, person_id, create_date) values ('+12125551212', 1, identity(), now());
diff --git a/sql2java-test/src/test/java/com/test/TransactionTest.java b/sql2java-test/src/test/java/com/test/TransactionTest.java
deleted file mode 100644
index 88e0a9d..0000000
--- a/sql2java-test/src/test/java/com/test/TransactionTest.java
+++ /dev/null
@@ -1,87 +0,0 @@
-package com.test;
-
-import java.io.File;
-import java.util.Date;
-import javax.sql.DataSource;
-import net.sourceforge.sql2java.lib.*;
-import org.hsqldb.jdbc.JDBCDataSource;
-import org.junit.*;
-
-public class TransactionTest {
-
- @Test public void twoTableCommitTransactionTest() throws Exception {
- JDBCDataSource ds = new JDBCDataSource();
- ds.setDatabase("jdbc:hsqldb:file:target/databases/test");
- ds.setUser("SA");
- ds.setPassword("");
-
- PublicDatabase db = new PublicDatabase(ds);
- //clean up
- db.deleteByWhere(Phone.class, "WHERE PHONE_NUMBER='+14105551212'");
- db.deleteByWhere(Person.class, "WHERE USERNAME='hansolo'");
-
- try {
- db.beginTransaction(Txn.Isolation.REPEATABLE_READ);
- Person s0 = db.createBean(Person.class);
- s0.setUsername("hansolo");
- s0.setFirstName("Harrison");
- s0.setLastName("Ford");
- s0.setCreateDate(new Date());
- s0 = db.save(s0);
- Phone m0 = db.createBean(Phone.class);
- m0.setPersonId(s0.getId());
- m0.setPhoneType(1);
- m0.setPhoneNumber("+14105551212");
- m0.setCreateDate(new Date());
- m0 = db.save(m0);
- db.commitTransaction();
- } finally {
- db.endTransaction();
- }
-
- Person s1 = db.loadUniqueByWhere(Person.class, "WHERE USERNAME='hansolo'");
- Assert.assertNotNull(s1);
-
- Phone m1 = db.loadUniqueByWhere(Phone.class, "WHERE PHONE_NUMBER='+14105551212'");
- Assert.assertNotNull(m1);
- }
-
-
- @Test public void twoTableRollbackTransactionTest() throws Exception {
- JDBCDataSource ds = new JDBCDataSource();
- ds.setDatabase("jdbc:hsqldb:file:target/databases/test");
- ds.setUser("SA");
- ds.setPassword("");
-
- PublicDatabase db = new PublicDatabase(ds);
- //clean up
- db.deleteByWhere(Phone.class, "WHERE PHONE_NUMBER='+14105551212'");
- db.deleteByWhere(Person.class, "WHERE USERNAME='hansolo'");
-
- try {
- db.beginTransaction(Txn.Isolation.REPEATABLE_READ);
- Person s0 = db.createBean(Person.class);
- s0.setUsername("hansolo");
- s0.setFirstName("Harrison");
- s0.setLastName("Ford");
- s0.setCreateDate(new Date());
- s0 = db.save(s0);
- Phone m0 = db.createBean(Phone.class);
- m0.setPersonId(s0.getId());
- m0.setPhoneType(1);
- m0.setPhoneNumber("+14105551212");
- m0.setCreateDate(new Date());
- m0 = db.save(m0);
- db.rollbackTransaction();
- } finally {
- db.endTransaction();
- }
-
- Person s1 = db.loadUniqueByWhere(Person.class, "WHERE USERNAME='hansolo'");
- Assert.assertNull(s1);
-
- Phone m1 = db.loadUniqueByWhere(Phone.class, "WHERE PHONE_NUMBER='+14105551212'");
- Assert.assertNull(m1);
- }
-
-}
diff --git a/sql2java-test/src/test/resources/sqltool.rc b/sql2java-test/src/test/resources/sqltool.rc
deleted file mode 100644
index ce9728a..0000000
--- a/sql2java-test/src/test/resources/sqltool.rc
+++ /dev/null
@@ -1,4 +0,0 @@
-urlid test
-url jdbc:hsqldb:file:target/databases/test
-username SA
-password
diff --git a/sql2java-maven-plugin/src/main/java/net/sourceforge/sql2java/CodeWriter.java b/src/main/java/net/sourceforge/sql2java/CodeWriter.java
similarity index 97%
rename from sql2java-maven-plugin/src/main/java/net/sourceforge/sql2java/CodeWriter.java
rename to src/main/java/net/sourceforge/sql2java/CodeWriter.java
index 8f50d9a..72db26e 100755
--- a/sql2java-maven-plugin/src/main/java/net/sourceforge/sql2java/CodeWriter.java
+++ b/src/main/java/net/sourceforge/sql2java/CodeWriter.java
@@ -41,9 +41,6 @@ public class CodeWriter
public Table table;
protected VelocityContext current_vc;
- protected boolean useLibrary = false;
- protected String libraryPackage;
-
///////////////////////////////////////////////////////
// CODE WRITER INIT
///////////////////////////////////////////////////////
@@ -64,6 +61,7 @@ public CodeWriter (Database db, Properties props) {
// Set properties
basePackage = props.getProperty("mgrwriter.package");
classPrefix = props.getProperty("mgrwriter.classprefix");
+ setDestinationFolder(props.getProperty("mgrwriter.destdir"));
excludeHash = setHash(props.getProperty("mgrwriter.exclude"));
if (excludeHash.size() != 0)
@@ -83,10 +81,6 @@ public CodeWriter (Database db, Properties props) {
}
}
- public void setUseLibrary(String libraryPackage) {
- this.useLibrary = true;
- this.libraryPackage = libraryPackage;
- }
public void setDestinationFolder(String destDir) throws Exception
{
@@ -190,11 +184,6 @@ public void checkDatabase() throws Exception
System.out.println(" Passed.");
}
- public void cleanup() {
- if (db != null) db.cleanup();
- // velocity?
- }
-
///////////////////////////////////////////////////////
// CODE WRITER CORE
///////////////////////////////////////////////////////
@@ -225,20 +214,14 @@ public synchronized void process() throws Exception
vc.put("codewriter", this );
vc.put("pkg", basePackage);
vc.put("pkgPath", basePackage.replace('.', '/'));
- vc.put("useLib", useLibrary);
- vc.put("libPath", libraryPackage);
vc.put("strUtil", StringUtilities.getInstance());
- vc.put("db", db);
-
current_vc = new VelocityContext(vc);
System.out.println("Generation in folder " + destDir + " ...");
String[] schema_templates = getPropertyExploded("mgrwriter.templates.perschema");
- //if (!useLibrary) {
- for(int i=0; i
+ * An imported key is the other's table column clone. Its
+ * ForeignKeyColName corresponds to the table's column name that
+ * points to the other's table.
+ */
+ private void loadImportedKeys() throws SQLException
+ {
+ System.out.println("Loading imported keys ...");
+ Table tables[] = getTables();
+
+ for(int i = 0; i < tables.length; i++)
+ {
+ Table table = tables[i];
+ ResultSet resultSet = meta.getImportedKeys(catalog, schema, table.getName());
+ while(resultSet.next())
+ {
+ String tabName = resultSet.getString("FKTABLE_NAME");
+ String colName = resultSet.getString("FKCOLUMN_NAME");
+
+ String foreignTabName= resultSet.getString("PKTABLE_NAME");
+ String foreignColName= resultSet.getString("PKCOLUMN_NAME");
+
+ Column col = getTable(tabName).getColumn(colName);
+ Column foreignCol = getTable(foreignTabName).getColumn(foreignColName);
+
+ col.addForeignKey(foreignCol);
+ foreignCol.addImportedKey(col);
+ //getTable(foreignTabName).addImportedKey(col);
+
+ System.out.println(" " + col.getFullName() + " -> " + foreignCol.getFullName() + " found ");
+ }
+
+ resultSet.close();
+ }
+ }
+
+ //
+ // could avoid db call.
+ // In each current table an entry is:
+ // other table column (that points to current table) | current pk column
+ // [other table has nb col. == pk length]
+ private void loadManyToMany() throws SQLException
+ {
+ System.out.println("Loading many to many relationships...");
+ Table tables[] = getTables();
+
+ for(int i = 0; i < tables.length; i++)
+ {
+ Table table = tables[i];
+
+// if(table.getColumns().length == table.getPrimaryKeys().length)
+ {
+ ResultSet resultSet = meta.getImportedKeys(catalog, schema, table.getName());
+
+ while(resultSet.next())
+ {
+ String tabName = resultSet.getString("PKTABLE_NAME");
+ String colName = resultSet.getString("PKCOLUMN_NAME");
+ System.out.println(" many to many " + tabName + " " + colName);
+
+ Table pkTable = getTable(tabName);
+ Column fkCol = table.getColumn(resultSet.getString("FKCOLUMN_NAME"));
+
+ if(pkTable != null)
+ {
+ Column pkCol = pkTable.getColumn(colName);
+
+ if(pkCol != null && fkCol != null)
+ {
+ pkTable.addManyToManyKey(fkCol, pkCol);
+ }
+ }
+ }
+
+ resultSet.close();
+ }
+ }
+ }
+
+ /**
+ * For each table, load the indexes.
+ */
+ private void loadIndexes() throws SQLException
+ {
+ System.out.println("Loading indexes ...");
+ Table tables[] = getTables();
+
+ for(int i = 0; i < tables.length; i++)
+ {
+ Table table = tables[i];
+ ResultSet resultSet = meta.getIndexInfo(catalog,
+ schema,
+ table.getName(),
+ true,
+ true);
+ while(resultSet.next())
+ {
+ String colName = resultSet.getString("COLUMN_NAME");
+ String indName = resultSet.getString("INDEX_NAME");
+
+ if (colName != null && indName != null) {
+ Column col = table.getColumn(colName);
+ if (!col.isPrimaryKey())
+ System.out.println(" Found interesting index " + indName + " on " +
+ colName + " for table " + table.getName());
+ }
+ }
+
+ resultSet.close();
+ }
+ }
+
+ public String[] getAllPackages()
+ {
+ Vector vector = new Vector();
+ for (int iIndex = 0; iIndex < tables.size(); iIndex ++)
+ {
+ Table table = (Table)tables.get(iIndex);
+ String packages[] = table.getLinkedPackages();
+ for (int i = 0; i < packages.length; i++)
+ {
+ if (vector.contains(packages[i]) == false)
+ {
+ vector.add(packages[i]);
+ }
+ }
+ }
+ return (String[])vector.toArray(new String[0]);
+ }
+
+}
diff --git a/sql2java-maven-plugin/src/main/java/net/sourceforge/sql2java/Main.java b/src/main/java/net/sourceforge/sql2java/Main.java
similarity index 100%
rename from sql2java-maven-plugin/src/main/java/net/sourceforge/sql2java/Main.java
rename to src/main/java/net/sourceforge/sql2java/Main.java
diff --git a/sql2java-maven-plugin/src/main/java/net/sourceforge/sql2java/StringUtilities.java b/src/main/java/net/sourceforge/sql2java/StringUtilities.java
similarity index 99%
rename from sql2java-maven-plugin/src/main/java/net/sourceforge/sql2java/StringUtilities.java
rename to src/main/java/net/sourceforge/sql2java/StringUtilities.java
index 6e47358..6e4c98a 100755
--- a/sql2java-maven-plugin/src/main/java/net/sourceforge/sql2java/StringUtilities.java
+++ b/src/main/java/net/sourceforge/sql2java/StringUtilities.java
@@ -363,8 +363,8 @@ public String convertName(Table table) {
*/
public static String convertName(String name, boolean wimpyCaps) {
StringBuffer buffer = new StringBuffer(name.length());
- char list[] = name.toLowerCase().toCharArray();
- //char list[] = name.toCharArray();
+ //char list[] = name.toLowerCase().toCharArray();
+ char list[] = name.toCharArray();
for(int i = 0; i < list.length; i++) {
if(i == 0 && !wimpyCaps) {
buffer.append(Character.toUpperCase(list[i]));
diff --git a/sql2java-maven-plugin/src/main/java/net/sourceforge/sql2java/Table.java b/src/main/java/net/sourceforge/sql2java/Table.java
similarity index 100%
rename from sql2java-maven-plugin/src/main/java/net/sourceforge/sql2java/Table.java
rename to src/main/java/net/sourceforge/sql2java/Table.java
diff --git a/sql2java-maven-plugin/src/main/java/net/sourceforge/sql2java/UserCodeParser.java b/src/main/java/net/sourceforge/sql2java/UserCodeParser.java
similarity index 100%
rename from sql2java-maven-plugin/src/main/java/net/sourceforge/sql2java/UserCodeParser.java
rename to src/main/java/net/sourceforge/sql2java/UserCodeParser.java
diff --git a/sql2java-maven-plugin/src/main/java/net/sourceforge/sql2java/ant/GenerationTask.java b/src/main/java/net/sourceforge/sql2java/ant/GenerationTask.java
similarity index 100%
rename from sql2java-maven-plugin/src/main/java/net/sourceforge/sql2java/ant/GenerationTask.java
rename to src/main/java/net/sourceforge/sql2java/ant/GenerationTask.java
diff --git a/sql2java-maven-plugin/src/main/java/net/sourceforge/sql2java/ant/SchemaCheckTask.java b/src/main/java/net/sourceforge/sql2java/ant/SchemaCheckTask.java
similarity index 100%
rename from sql2java-maven-plugin/src/main/java/net/sourceforge/sql2java/ant/SchemaCheckTask.java
rename to src/main/java/net/sourceforge/sql2java/ant/SchemaCheckTask.java
diff --git a/sql2java-maven-plugin/src/main/java/net/sourceforge/sql2java/ant/TableGenerationTask.java b/src/main/java/net/sourceforge/sql2java/ant/TableGenerationTask.java
similarity index 100%
rename from sql2java-maven-plugin/src/main/java/net/sourceforge/sql2java/ant/TableGenerationTask.java
rename to src/main/java/net/sourceforge/sql2java/ant/TableGenerationTask.java
diff --git a/sql2java-maven-plugin/src/main/java/net/sourceforge/sql2java/ant/UtilsGenerationTask.java b/src/main/java/net/sourceforge/sql2java/ant/UtilsGenerationTask.java
similarity index 100%
rename from sql2java-maven-plugin/src/main/java/net/sourceforge/sql2java/ant/UtilsGenerationTask.java
rename to src/main/java/net/sourceforge/sql2java/ant/UtilsGenerationTask.java
diff --git a/sql2java-maven-plugin/src/main/java/net/sourceforge/sql2java/maven/Sql2JavaMojo.java b/src/main/java/net/sourceforge/sql2java/maven/Sql2JavaMojo.java
similarity index 63%
rename from sql2java-maven-plugin/src/main/java/net/sourceforge/sql2java/maven/Sql2JavaMojo.java
rename to src/main/java/net/sourceforge/sql2java/maven/Sql2JavaMojo.java
index 013b46b..deb2bcd 100644
--- a/sql2java-maven-plugin/src/main/java/net/sourceforge/sql2java/maven/Sql2JavaMojo.java
+++ b/src/main/java/net/sourceforge/sql2java/maven/Sql2JavaMojo.java
@@ -1,62 +1,51 @@
package net.sourceforge.sql2java.maven;
+import net.sourceforge.sql2java.*;
+import org.apache.maven.plugin.AbstractMojo;
+import org.apache.maven.plugin.MojoExecutionException;
+
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Properties;
import java.util.StringTokenizer;
-import net.sourceforge.sql2java.*;
-import org.apache.maven.plugin.AbstractMojo;
-import org.apache.maven.plugin.MojoExecutionException;
-import org.apache.maven.plugins.annotations.Mojo;
-import org.apache.maven.plugins.annotations.Parameter;
/**
- * Goal which uses sql2java to generate Java files from a SQL database.
+ * Goal which uses a sql2java to generate Java files from a SQL database.
+ * @goal sql2java
+ * @requiresDirectInvocation true
* @author garth
*/
-@Mojo(name="sql2java", requiresDirectInvocation=true)
-public class Sql2JavaMojo extends AbstractDbMojo {
+public class Sql2JavaMojo extends AbstractMojo
+{
/**
* The working directory where the generated Java source files are created.
+ *
+ * @parameter default-value="${project.build.directory}/generated-sources/sql2java"
+ * @required
*/
- @Parameter(property="outputDirectory", defaultValue="${project.build.directory}/generated-sources/sql2java", required=true)
private File outputDirectory;
- protected File getOutputDirectory() {
+ protected File getOutputDirectory()
+ {
return outputDirectory;
}
/**
* The location of the properties file.
+ *
+ * @parameter default-value="${project.basedir}/src/main/resources/sql2java.properties"
+ * @required
*/
- @Parameter(property="propertiesFile", defaultValue="${project.basedir}/src/main/resources/sql2java.properties", required=true)
private File propertiesFile;
- protected File getPropertiesFile() {
+ protected File getPropertiesFile()
+ {
return propertiesFile;
}
- /**
- * Database schema alias
- */
- @Parameter(property="schemaAlias", defaultValue="test")
- private String schemaAlias;
-
- /**
- * Package name
- */
- @Parameter(property="packageName", required=true)
- private String packageName;
-
- /**
- * Class prefix
- */
- @Parameter(property="classPrefix", required=false)
- private String classPrefix;
-
public void execute() throws MojoExecutionException {
File f = outputDirectory;
if ( !f.exists() ) {
@@ -69,19 +58,17 @@ public void execute() throws MojoExecutionException {
//properties already here ?
Properties prop = new Properties();
- CodeWriter writer = null;
try {
prop.load(new FileInputStream(propertiesFile));
Database db = new Database();
- db.setDriver(driver);
- db.setUrl(url);
- db.setUsername(user);
- db.setPassword(password);
- db.setCatalog(catalog);
- db.setSchema(schema);
- //db.setSchemaAlias(schemaAlias);
+ db.setDriver(getProperty(prop, "jdbc.driver"));
+ db.setUrl(getProperty(prop, "jdbc.url"));
+ db.setUsername(getProperty(prop, "jdbc.username"));
+ db.setPassword(getProperty(prop, "jdbc.password"));
+ db.setCatalog(getProperty(prop, "jdbc.catalog"));
+ db.setSchema(getProperty(prop, "jdbc.schema"));
db.setTableNamePattern(getProperty(prop, "jdbc.tablenamepattern"));
-
+
if ("false".equalsIgnoreCase(getProperty(prop, "jdbc.oracle.retrieve.remarks")))
db.setOracleRetrieveRemarks(false);
else
@@ -99,21 +86,13 @@ public void execute() throws MojoExecutionException {
db.load();
- //HACK
- if (packageName != null) prop.setProperty("mgrwriter.package", packageName);
- if (classPrefix != null) prop.setProperty("mgrwriter.classprefix", classPrefix);
- writer = new CodeWriter(db, prop);
+ CodeWriter writer = new CodeWriter(db, prop);
// override destdir if given
- writer.setUseLibrary("net.sourceforge.sql2java.lib");
writer.setDestinationFolder(outputDirectory.getPath());
writer.process();
} catch(Exception e) {
throw new MojoExecutionException("Error executing plugin", e);
- } finally {
- if (writer != null) {
- writer.cleanup();
- }
- }
+ }
}
diff --git a/sql2java-maven-plugin/src/main/resources/basemanager.java.vm b/src/main/resources/basemanager.java.vm
similarity index 100%
rename from sql2java-maven-plugin/src/main/resources/basemanager.java.vm
rename to src/main/resources/basemanager.java.vm
diff --git a/sql2java-maven-plugin/src/main/resources/bean.java.vm b/src/main/resources/bean.java.vm
similarity index 99%
rename from sql2java-maven-plugin/src/main/resources/bean.java.vm
rename to src/main/resources/bean.java.vm
index 4ea9855..024c846 100755
--- a/sql2java-maven-plugin/src/main/resources/bean.java.vm
+++ b/src/main/resources/bean.java.vm
@@ -10,9 +10,6 @@ import java.io.Serializable;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
-#if ($useLib)
-import $libPath.*;
-#end
/**
* $beanClass is a mapping of $table.getName() Table.
diff --git a/sql2java-maven-plugin/src/main/resources/daobean.java.vm b/src/main/resources/daobean.java.vm
similarity index 100%
rename from sql2java-maven-plugin/src/main/resources/daobean.java.vm
rename to src/main/resources/daobean.java.vm
diff --git a/sql2java-maven-plugin/src/main/resources/daomanager.java.vm b/src/main/resources/daomanager.java.vm
similarity index 100%
rename from sql2java-maven-plugin/src/main/resources/daomanager.java.vm
rename to src/main/resources/daomanager.java.vm
diff --git a/sql2java-maven-plugin/src/main/resources/database.java.vm b/src/main/resources/database.java.vm
similarity index 75%
rename from sql2java-maven-plugin/src/main/resources/database.java.vm
rename to src/main/resources/database.java.vm
index 4a09019..a39cd8b 100644
--- a/sql2java-maven-plugin/src/main/resources/database.java.vm
+++ b/src/main/resources/database.java.vm
@@ -7,20 +7,16 @@ package $pkg;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-#if ($useLib)
-import $libPath.*;
-#end
/**
- * ${strUtil.convertName($db.schema)}Database is a mapping of the $db.schema schema.
+ * ${className}Database is a mapping of the $schema schema.
*/
-public class ${strUtil.convertName($db.schema)}Database extends Database {
+public class ${className}Database {
public ${className}Database(DataSource dataSource) {
- super(dataSource);
+ this.dataSource = dataSource;
#foreach ( $table in $tables )
this.$strUtil.getManagerObjectName($table) = new $strUtil.getManagerClass($table)(dataSource);
- registerManager(this.$strUtil.getManagerObjectName($table));
#end
}
diff --git a/sql2java-maven-plugin/src/main/resources/header.include.vm b/src/main/resources/header.include.vm
similarity index 100%
rename from sql2java-maven-plugin/src/main/resources/header.include.vm
rename to src/main/resources/header.include.vm
diff --git a/sql2java-maven-plugin/src/main/resources/manager.java.vm b/src/main/resources/manager.java.vm
similarity index 99%
rename from sql2java-maven-plugin/src/main/resources/manager.java.vm
rename to src/main/resources/manager.java.vm
index 71c5b6a..ebdc6b9 100644
--- a/sql2java-maven-plugin/src/main/resources/manager.java.vm
+++ b/src/main/resources/manager.java.vm
@@ -18,9 +18,6 @@ import org.slf4j.LoggerFactory;
#foreach ($linkedPackage in $linkedPackages)
import ${linkedPackage}.*;
#end
-#if ($useLib)
-import $libPath.*;
-#end
/**
* Handles database calls (save, load, count, etc...) for the $tablename table.
diff --git a/sql2java-maven-plugin/src/main/resources/table.variables.include.vm b/src/main/resources/table.variables.include.vm
similarity index 100%
rename from sql2java-maven-plugin/src/main/resources/table.variables.include.vm
rename to src/main/resources/table.variables.include.vm
diff --git a/sql2java-maven-plugin/src/test/config/test.properties b/src/test/config/test.properties
similarity index 100%
rename from sql2java-maven-plugin/src/test/config/test.properties
rename to src/test/config/test.properties