", $tablename) )
373 | #if ( $genKeyRetrieve == "after" )
374 |
375 | if (!bean.$strUtil.getModifiedMethod($pKey)()) {
376 | PreparedStatement ps2 = null;
377 | ResultSet rs = null;
378 | try {
379 | ps2 = c.prepareStatement("$hint");
380 | rs = ps2.executeQuery();
381 | if(rs.next()) {
382 | bean.$strUtil.getSetMethod($pKey)($pKey.getResultSetMethodObject("1"));
383 | } else {
384 | if (delayed || orUpdate) log.trace("Could not retrieve generated key");
385 | else log.warn("Could not retrieve generated key");
386 | }
387 | } finally {
388 | close(ps2, rs);
389 | }
390 | }
391 | #elseif ( $genKeyRetrieve == "auto" )
392 | if (!bean.$strUtil.getModifiedMethod($pKey)() && !delayed) {
393 | ResultSet rs = ps.getGeneratedKeys();
394 | try {
395 | if(rs.next()) {
396 | bean.$strUtil.getSetMethod($pKey)($pKey.getResultSetMethodObject("1"));
397 | } else {
398 | if (delayed || orUpdate) log.trace("Could not retrieve generated key");
399 | else log.warn("Could not retrieve generated key");
400 | }
401 | } finally {
402 | close(rs);
403 | }
404 | }
405 | #end
406 | #end
407 | #end
408 | ##-------------------/writePostInsert
409 |
410 | bean.isNew(false);
411 | bean.resetIsModified();
412 | return bean;
413 | } finally {
414 | close(ps);
415 | releaseConnection(c);
416 | }
417 | }
418 |
419 | /**
420 | * Update the $beanClass bean record in the database according to the changes.
421 | *
422 | * @param bean the $beanClass bean to be updated
423 | */
424 | //14
425 | public $beanClass update($beanClass bean) throws SQLException {
426 | // mini checks
427 | if (!bean.isModified()) {
428 | return bean; // should not we log something ?
429 | }
430 | if (bean.isNew()){
431 | return save(bean);
432 | }
433 | Connection c = null;
434 | PreparedStatement ps = null;
435 | StringBuilder sql = null;
436 | try {
437 | c = getConnection();
438 |
439 | #if ( $primaryKeys.size() == 0 )
440 | $codewriter.log(" WARN : $tablename does not have any primary key...")
441 | #end
442 | #if ( $isPresentLock )
443 | $lockColumn.getJavaType() oldLockValue = bean.$strUtil.getGetMethod($lockColumn)();
444 | bean.$strUtil.getSetMethod($lockColumn))(new $lockColumn.getJavaType()(String.valueOf(System.currentTimeMillis())));
445 |
446 | #end
447 | sql = new StringBuilder("UPDATE $tablename SET ");
448 | boolean useComma=false;
449 | #foreach( $column in $columns )
450 |
451 | if (bean.$strUtil.getModifiedMethod($column)()) {
452 | if (useComma) {
453 | sql.append(",");
454 | } else {
455 | useComma=true;
456 | }
457 | sql.append("$column.getName()").append("=?");
458 | }
459 | #end
460 | #if ( $primaryKeys.size() > 0 )
461 | sql.append(" WHERE ");
462 | #end
463 | #set ($sql = "" )
464 | #macro ( sqlAppend $somestr )
465 | #set ( $sql = "$!sql$somestr" )
466 | #end
467 | #foreach( $primaryKey in $primaryKeys )
468 | #if ( $velocityCount > 1 )#sqlAppend( " AND " )#end
469 | #sqlAppend( "$primaryKey.getName()=?" )
470 | #end
471 | #if ( $isPresentLock )
472 | #if ( $primaryKeys.size() > 0 )#sqlAppend( " AND " )#end
473 | #sqlAppend( "$lockColumn.getName()=?")
474 | #end
475 | sql.append("$sql");
476 | if (log.isTraceEnabled()) log.trace("update : {}", sql);
477 | ps = c.prepareStatement(sql.toString(),
478 | ResultSet.TYPE_SCROLL_INSENSITIVE,
479 | ResultSet.CONCUR_READ_ONLY);
480 |
481 | int _dirtyCount = fillPreparedStatement(ps, bean, SEARCH_EXACT);
482 |
483 | if (_dirtyCount == 0) {
484 | if (log.isTraceEnabled()) log.trace("The bean to look is not initialized... do not update.");
485 | return bean;
486 | }
487 |
488 | #foreach ( $pKey in $primaryKeys )
489 | $pKey.getPreparedStatementMethod("bean.$strUtil.getGetMethod($pKey)()", "++_dirtyCount")
490 | #end
491 | #if ( $isPresentLock )
492 | $lockColumn.getPreparedStatementMethod( "oldLockValue", "++_dirtyCount")
493 | if (ps.executeUpdate()==0) {
494 | throw new SQLException("sql2java.exception.optimisticlock");
495 | }
496 | #else
497 | ps.executeUpdate();
498 | #end
499 | bean.resetIsModified();
500 |
501 | return bean;
502 | } finally {
503 | close(ps);
504 | releaseConnection(c);
505 | }
506 | }
507 |
508 | //_____________________________________________________________________
509 | //
510 | // USING TEMPLATE
511 | //_____________________________________________________________________
512 |
513 | /**
514 | * Deletes rows using a $beanClass template.
515 | *
516 | * @param bean the $beanClass object(s) to be deleted
517 | * @return the number of deleted objects
518 | */
519 | //21
520 | public int deleteUsingTemplate($beanClass bean) throws SQLException {
521 | #if ( $primaryKeys.size() == 1)
522 | if (bean.$strUtil.getInitializedMethod($primaryKeys.get(0))())
523 | return deleteByPrimaryKey(bean.$strUtil.getGetMethod($primaryKeys.get(0))());
524 |
525 | #end
526 | Connection c = null;
527 | PreparedStatement ps = null;
528 | StringBuilder sql = new StringBuilder("DELETE FROM $tablename ");;
529 | StringBuilder sqlWhere = new StringBuilder("");
530 |
531 | try {
532 | if (fillWhere(sqlWhere, bean, SEARCH_EXACT) == 0) {
533 | if (log.isTraceEnabled()) log.trace("The bean to look is not initialized... deleting all");
534 | } else {
535 | sql.append(" WHERE ").append(sqlWhere);
536 | }
537 | if (log.isTraceEnabled()) log.trace("deleteUsingTemplate: {}", sql);
538 |
539 | c = getConnection();
540 | ps = c.prepareStatement(sql.toString(),
541 | ResultSet.TYPE_SCROLL_INSENSITIVE,
542 | ResultSet.CONCUR_READ_ONLY);
543 | fillPreparedStatement(ps, bean, SEARCH_EXACT);
544 |
545 | int _rows = ps.executeUpdate();
546 | return _rows;
547 | } finally {
548 | close(ps);
549 | releaseConnection(c);
550 | }
551 | }
552 |
553 | /**
554 | * fills the given stringbuilder with the sql where clausis constructed using the bean and the search type
555 | * @param sqlWhere the stringbuilder that will be filled
556 | * @param bean the bean to use for creating the where clausis
557 | * @param searchType exact ? like ? starting like ?
558 | * @return the number of clausis returned
559 | */
560 | protected int fillWhere(StringBuilder sqlWhere, $beanClass bean, int searchType) throws SQLException {
561 | if (bean == null)
562 | return 0;
563 | int _dirtyCount = 0;
564 | StringBuilder sqlEqualsOperation = new StringBuilder("=");
565 | StringBuilder sqlOperation = new StringBuilder("=");
566 | if (searchType != SEARCH_EXACT)
567 | sqlOperation = new StringBuilder(" like ");
568 | #foreach( $column in $columns )
569 | if (bean.$strUtil.getModifiedMethod($column)()) {
570 | _dirtyCount ++;
571 | #if ($column.isString())
572 | sqlWhere.append((sqlWhere.length() == 0) ? " " : " AND ").append("$column.getName() ").append(sqlOperation).append("?");
573 | #else
574 | sqlWhere.append((sqlWhere.length() == 0) ? " " : " AND ").append("$column.getName() ").append(sqlEqualsOperation).append("?");
575 | #end
576 | }
577 | #end
578 | return _dirtyCount;
579 | }
580 |
581 | /**
582 | * fill the given prepared statement with the bean values and a search type
583 | * @param ps the preparedStatement that will be filled
584 | * @param bean the bean to use for creating the where clausis
585 | * @param searchType exact ? like ? starting like ?
586 | * @return the number of clausis returned
587 | */
588 | protected int fillPreparedStatement(PreparedStatement ps, $beanClass bean, int searchType) throws SQLException {
589 | if (bean == null)
590 | return 0;
591 | int _dirtyCount = 0;
592 | #foreach ( $column in $columns )
593 | if (bean.$strUtil.getModifiedMethod($column)()) {
594 | #if ($column.isString())
595 | switch (searchType){
596 | case SEARCH_EXACT:
597 | if (log.isTraceEnabled()) log.trace("Setting for {} [{}]", _dirtyCount, bean.$strUtil.getGetMethod($column)());
598 | $column.getPreparedStatementMethod("bean.$strUtil.getGetMethod($column)()", "++_dirtyCount");
599 | break;
600 | case SEARCH_LIKE:
601 | if (log.isTraceEnabled()) log.trace("Setting for {} [%{}%]", _dirtyCount, bean.$strUtil.getGetMethod($column)());
602 | $column.getPreparedStatementMethod("${Q}%${Q} + bean.$strUtil.getGetMethod($column)() + ${Q}%${Q}", "++_dirtyCount");
603 | break;
604 | case SEARCH_STARTING_LIKE:
605 | if (log.isTraceEnabled()) log.trace("Setting for {} [{}%]", _dirtyCount, bean.$strUtil.getGetMethod($column)());
606 | $column.getPreparedStatementMethod("${Q}%${Q} + bean.$strUtil.getGetMethod($column)()", "++_dirtyCount");
607 | break;
608 | case SEARCH_ENDING_LIKE:
609 | if (log.isTraceEnabled()) log.trace("Setting for {} [%{}]", _dirtyCount, bean.$strUtil.getGetMethod($column)());
610 | $column.getPreparedStatementMethod("bean.$strUtil.getGetMethod($column)() + ${Q}%${Q}", "++_dirtyCount");
611 | break;
612 | }
613 | #else
614 | if (log.isTraceEnabled()) log.trace("Setting for {} [{}]", _dirtyCount, bean.$strUtil.getGetMethod($column)());
615 | $column.getPreparedStatementMethod("bean.$strUtil.getGetMethod($column)()", "++_dirtyCount");
616 | #end
617 | }
618 | #end
619 | return _dirtyCount;
620 | }
621 |
622 | /**
623 | * Transforms a ResultSet iterating on the $tablename on a $beanClass bean.
624 | *
625 | * @param rs the ResultSet to be transformed
626 | * @return bean resulting $beanClass bean
627 | */
628 | public $beanClass decodeRow(ResultSet rs) throws SQLException {
629 | $beanClass bean = create$beanClass();
630 | ## the set statement casts $velocityCount to a string
631 | #foreach ( $column in $columns )
632 | #set ($vCount = "$velocityCount" )
633 | bean.$strUtil.getSetMethod($column)($column.getResultSetMethodObject($vCount));
634 | #end
635 | bean.isNew(false);
636 | bean.resetIsModified();
637 | return bean;
638 | }
639 |
640 | /**
641 | * Transforms a ResultSet iterating on the $tablename on a $beanClass bean using the names of the columns
642 | *
643 | * @param rs the ResultSet to be transformed
644 | * @return bean resulting $beanClass bean
645 | */
646 | public $beanClass metaDataDecodeRow(ResultSet rs) throws SQLException {
647 | $beanClass bean = create$beanClass();
648 | #foreach ( $column in $columns )
649 | bean.$strUtil.getSetMethod($column)($column.getResultSetMethodObject("${Q}$column.getName()${Q}"));
650 | #end
651 | bean.isNew(false);
652 | bean.resetIsModified();
653 | return bean;
654 | }
655 |
656 | }
657 |
--------------------------------------------------------------------------------
/sql2java-maven-plugin/src/main/resources/table.variables.include.vm:
--------------------------------------------------------------------------------
1 | ##$Id: table.variables.include.vm,v 1.7 2005/10/10 22:06:26 framiere Exp $
2 | #set ( $tablename = $codewriter.tableName() )
3 | #set ( $tableName = $strUtil.convertName($codewriter.tableName()) )
4 | #set ( $columns = $codewriter.getColumns() )
5 | #set ( $foreignKeys = $codewriter.getForeignKeys() )
6 | #set ( $importedKeys = $codewriter.getImportedKeys() )
7 | #set ( $primaryKeys = $codewriter.getPrimaryKeys() )
8 | #set ( $coreClass = $strUtil.getCoreClass($table) )
9 | #set ( $managerClass = $strUtil.getManagerClass($table) )
10 | #set ( $beanClass = $strUtil.getBeanClass($table) )
11 | #set ( $factoryClass = $strUtil.getFactoryClass($table) )
12 | #set ( $httpFactoryClass = $strUtil.getHttpFactoryClass($table) )
13 | #set ( $comparatorClass = $strUtil.getComparatorClass($table) )
14 | #set ( $listenerClass = $strUtil.getListenerClass($table) )
15 | #set ( $rendererClass = $strUtil.getRendererClass($table) )
16 | #set ( $widgetFactoryClass = $strUtil.getWidgetFactoryClass($table) )
17 | #set ( $widgetClass = $strUtil.getWidgetClass($table) )
18 | #set ( $linkedTables = $table.getLinkedTables())
19 | #set ( $linkedPackages = $table.getLinkedPackages())
20 | #set ( $pkgPath = $table.getPackagePath())
21 | #set ( $Q = '"' )
22 |
--------------------------------------------------------------------------------
/sql2java-maven-plugin/src/test/config/test.properties:
--------------------------------------------------------------------------------
1 | #
2 | # SAMPLE PROPERTIES FILE FOR SQL2JAVA
3 | #
4 |
5 |
6 | #----------------------------------------------
7 | # (1/7) CONFIGURE YOUR DATABASE ACCESS
8 | #----------------------------------------------
9 | #jdbc.driver=org.hsqldb.jdbcDriver
10 | #jdbc.url=jdbc:hsqldb:hsql://localhost
11 | #jdbc.username=sa
12 | #jdbc.password=
13 | #jdbc.schema=
14 |
15 | jdbc.driver=com.mysql.jdbc.Driver
16 | jdbc.url=jdbc:mysql://localhost:3306/schema_here
17 | jdbc.username=
18 | jdbc.password=
19 | jdbc.schema=schema_here
20 |
21 |
22 | #-------------------------------------------------
23 | # (2/7) CONFIGURE RETRIEVAL OF AUTO GENERATED KEY
24 | #-------------------------------------------------
25 | # For those who do not want to read below, please simply pick up the
26 | # configuration associated with your database.
27 | #
28 | # More explanation:
29 | # When you save a bean whose primary key is numeric and has no value set,
30 | # we assume that you want sql2java to retrieve a key's value generated
31 | # on the database side.
32 | #
33 | # generatedkey.retrieve can take 4 values:
34 | #
35 | # auto - the standard approach when you have a JDBC 3.0 driver.
36 | #
37 | # before - the key's value is retrieved before inserting the record.
38 | #
39 | # after - the key's value is retrieved after inserting the record
40 | #
41 | # none - the key's value is never retrieved, frankly I doubt you
42 | # want this configuration
43 | #
44 | # If you set it to before or after you also need to configure the
45 | # autogeneratedkey.statement properties.
46 | #
is replaced at code generation time by the table name.
47 | # You may adjust this properties to fit your own naming convention.
48 | #
49 | # PICK THE CONFIGURATION ASSOCIATED WITH YOUR DATABASE
50 | # (or create one, but in that case let us know so we can add it here... :-)
51 | #
52 | #-- HSQL ------
53 | #generatedkey.retrieve=after
54 | #generatedkey.statement=CALL IDENTITY()
55 | #
56 | #-- IF YOU USE A JDBC 3.0 DRIVER (works with mysql, ORACLE 9, etc..) ------
57 | generatedkey.retrieve=auto
58 | generatedkey.statement=
59 | #
60 | #-- MYSQL (without jdbc 3.0 driver) ------
61 | #generatedkey.retrieve=after
62 | #generatedkey.statement=SELECT last_insert_id()
63 | #
64 | #-- POSTGRESQL ------
65 | #generatedkey.retrieve=before
66 | #generatedkey.statement=SELECT nextval('
_SEQ')
67 | #
68 |
69 |
70 | #----------------------------------------------
71 | # (3/7) GENERATED SOURCE CODE
72 | #----------------------------------------------
73 |
74 | # Package name for the generated source code
75 | mgrwriter.package=net.sql2java.sample.database
76 |
77 | # Destination of the generated source code (package hierarchy is preserved)
78 | mgrwriter.destdir=target/generated-sources
79 |
80 | # Property file to use when initializing Velocity
81 | #mgrwriter.velocityprops=somefile
82 |
83 | # templates (you can generate java files, jsp, etc...)
84 |
85 | mgrwriter.templates.loadingpath=
86 |
87 | mgrwriter.templates.perschema= daobean.java.vm, \
88 | daomanager.java.vm, \
89 | basemanager.java.vm, \
90 | database.java.vm
91 |
92 | mgrwriter.templates.pertable= bean.java.vm, \
93 | manager.java.vm
94 |
95 | # sets a prefix to prepend to all generated classes
96 | # useful if you are worried about namespace collision with reserved words
97 | # or java.lang classes
98 | #mgrwriter.classprefix=
99 |
100 |
101 | #-----------------------------------------------
102 | # (4/7) JDBC TYPES Mapping
103 | #-----------------------------------------------
104 | #
105 | # jdbc DATE mapping can be:
106 | # java.sql.Date
107 | # java.util.Date
108 | jdbc2java.date=java.util.Date
109 |
110 | # jdbc TIME mapping can be:
111 | # java.sql.Time
112 | # java.util.Date
113 | jdbc2java.time=java.util.Date
114 |
115 | # jdbc TIMESTAMP mappning can be:
116 | # java.sql.Timestamp
117 | # java.util.Date
118 | jdbc2java.timestamp=java.util.Date
119 |
120 |
121 | #-----------------------------------------------
122 | # (5/7) FILTER OUT CERTAIN TABLES
123 | #-----------------------------------------------
124 | #
125 | # COMMA SEPARATED list of table types to be mapped
126 | # Commonly seen types are TABLE, VIEW, SYSTEM TABLE, SYNONYM
127 | jdbc.tabletypes=TABLE
128 |
129 | # Table name pattern of tables to be mapped to classes.
130 | # available wildcard: %
131 | # defaults to %
132 | # You can specify several patterns separated by commas.
133 | jdbc.tablenamepattern=%
134 |
135 | # SPACE SEPARATED list of tables to include or exclude. If you specify both,
136 | # the include list will take priority. If these fields are left commented out,
137 | # all tables in the specified schema will get mapped to classes
138 | #mgrwriter.include=Testing
139 | #mgrwriter.exclude=
140 |
141 |
142 | #-----------------------------------------------
143 | # (6/7) CONFIGURE OPTIMISTIC LOCK
144 | #-----------------------------------------------
145 | # optimisticlock.type can take 2 values:
146 | # none - the optimistic lock mechanism is disabled (default).
147 | # timestamp - the optimistic lock column contains the System.currentTimeMillis() value.
148 | #
149 | # optimisticlock.column takes the column name used by optimistic lock mechanism in your database.
150 | # If this column is not present in some table the optimistic lock is not applied there.
151 | # the column mapping can be java.lang.Long or java.lang.String.
152 | # (jdbc type size >= 13 characters)
153 | optimisticlock.type=timestamp
154 | optimisticlock.column=version_time
155 |
156 |
157 | #-----------------------------------------------
158 | # (7/7) ORGANISE YOUR SUBPACKAGES
159 | #-----------------------------------------------
160 | #subpackage.1.name=products.delivery
161 | #subpackage.1.tables=delivery
162 |
163 | #subpackage.2.name=products.product
164 | #subpackage.2.tables=product
165 |
166 | #subpackage.3.name=products.manufacturer
167 | #subpackage.3.tables=manufacturer
168 |
169 | #subpackage.4.name=users
170 | #subpackage.4.tables=customer, shipper,
171 |
172 |
173 |
--------------------------------------------------------------------------------
/sql2java-test/README:
--------------------------------------------------------------------------------
1 | # Test of sqlfile and sql2java plugins
2 |
3 | Use this as a model for how to use the plugin in your environment. E.g.
4 | - Put your SQL in src/main/sql/NN-blah.sql
5 | - Use sqlfile plugin in build->plugins to source it into a temporary hsqldb
6 | - Use sql2java plugin in build->plugins to generate managers and beans to generated source dir
7 | - Test, etc.
8 |
9 | Currently known problem:
10 |
11 | [WARNING] Some problems were encountered while building the effective model for net.sourceforge:sql2java-test:jar:1.0-SNAPSHOT
12 | [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
13 | [WARNING]
14 | [WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
15 | [WARNING]
16 | [WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
17 |
18 | 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.
19 |
--------------------------------------------------------------------------------
/sql2java-test/pom.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 | 4.0.0
5 | com.github.xgp
6 | sql2java-test
7 | jar
8 | sql2java-test
9 |
10 |
11 | com.github.xgp
12 | sql2java
13 | 0.9.1-SNAPSHOT
14 |
15 |
16 |
17 |
18 | org.slf4j
19 | slf4j-api
20 |
21 |
22 | com.github.xgp
23 | sql2java-lib
24 | ${project.parent.version}
25 |
26 |
27 | org.slf4j
28 | slf4j-simple
29 | test
30 |
31 |
32 | org.hsqldb
33 | hsqldb
34 | test
35 |
36 |
37 | org.hsqldb
38 | sqltool
39 | test
40 |
41 |
42 | junit
43 | junit
44 | test
45 |
46 |
47 |
48 |
49 |
50 |
51 | com.github.xgp
52 | sql2java-maven-plugin
53 | ${project.parent.version}
54 |
55 |
56 | sqlfile
57 | initialize
58 |
59 | sqlfile
60 |
61 |
62 |
63 |
64 | true
65 | ${project.basedir}/src/main/sql
66 | org.hsqldb.jdbc.JDBCDriver
67 | jdbc:hsqldb:file:${project.build.directory}/databases/test
68 | SA
69 |
70 | PUBLIC
71 |
72 |
73 |
74 | org.hsqldb
75 | hsqldb
76 | ${hsqldb.version}
77 |
78 |
79 |
80 |
81 | com.github.xgp
82 | sql2java-maven-plugin
83 | ${project.parent.version}
84 |
85 |
86 | sql2java
87 | generate-sources
88 |
89 | sql2java
90 |
91 |
92 |
93 |
94 | ${project.build.directory}/generated-sources/sql2java
95 | ${project.basedir}/src/main/resources/sql2java.properties
96 | org.hsqldb.jdbc.JDBCDriver
97 | jdbc:hsqldb:file:${project.build.directory}/databases/test
98 | SA
99 |
100 | PUBLIC
101 | com.test
102 |
103 |
104 |
105 | org.hsqldb
106 | hsqldb
107 | ${hsqldb.version}
108 |
109 |
110 |
111 |
112 | org.codehaus.mojo
113 | build-helper-maven-plugin
114 | 1.12
115 |
116 |
117 | add-source
118 | generate-sources
119 |
120 | add-source
121 |
122 |
123 |
124 | ${project.build.directory}/generated-sources/sql2java
125 |
126 |
127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 |
--------------------------------------------------------------------------------
/sql2java-test/src/main/resources/sql2java.properties:
--------------------------------------------------------------------------------
1 | #
2 | # PROPERTIES FILE FOR SQL2JAVA
3 | #
4 |
5 |
6 | #-------------------------------------------------
7 | # (2/6) CONFIGURE RETRIEVAL OF AUTO GENERATED KEY
8 | #-------------------------------------------------
9 | # For those who do not want to read below, please simply pick up the
10 | # configuration associated with your database.
11 | #
12 | # More explanation:
13 | # When you save a bean whose primary key is numeric and has no value set,
14 | # we assume that you want sql2java to retrieve a key's value generated
15 | # on the database side.
16 | #
17 | # generatedkey.retrieve can take 4 values:
18 | #
19 | # auto - the standard approach when you have a JDBC 3.0 driver.
20 | #
21 | # before - the key's value is retrieved before inserting the record.
22 | #
23 | # after - the key's value is retrieved after inserting the record
24 | #
25 | # none - the key's value is never retrieved, frankly I doubt you
26 | # want this configuration
27 | #
28 | # If you set it to before or after you also need to configure the
29 | # autogeneratedkey.statement properties.
30 | #
is replaced at code generation time by the table name.
31 | # You may adjust this properties to fit your own naming convention.
32 | #
33 | # PICK THE CONFIGURATION ASSOCIATED WITH YOUR DATABASE
34 | # (or create one, but in that case let us know so we can add it here... :-)
35 | #
36 | #-- HSQL ------
37 | #generatedkey.retrieve=after
38 | #generatedkey.statement=CALL IDENTITY()
39 |
40 | #-- IF YOU USE A JDBC 3.0 DRIVER (works with mysql, ORACLE 9, etc..) ------
41 | generatedkey.retrieve=auto
42 | generatedkey.statement=
43 |
44 | #----------------------------------------------
45 | # (3/6) GENERATED SOURCE CODE
46 | #----------------------------------------------
47 |
48 | # Package name for the generated source code
49 | mgrwriter.package=com.test
50 |
51 | # Property file to use when initializing Velocity
52 | #mgrwriter.velocityprops=somefile
53 |
54 | # templates (you can generate java files, jsp, etc...)
55 |
56 | mgrwriter.templates.loadingpath=templates/velocity/global, \
57 | templates/velocity/table, \
58 | templates/velocity/includes
59 |
60 | mgrwriter.templates.perschema= database.java.vm
61 |
62 | mgrwriter.templates.pertable= bean.java.vm, \
63 | manager.java.vm
64 |
65 | #-----------------------------------------------
66 | # (4/6) JDBC TYPES Mapping
67 | #-----------------------------------------------
68 | #
69 | # jdbc DATE mapping can be:
70 | # java.sql.Date
71 | # java.util.Date
72 | jdbc2java.date=java.util.Date
73 |
74 | # jdbc TIME mapping can be:
75 | # java.sql.Time
76 | # java.util.Date
77 | jdbc2java.time=java.util.Date
78 |
79 | # jdbc TIMESTAMP mappning can be:
80 | # java.sql.Timestamp
81 | # java.util.Date
82 | jdbc2java.timestamp=java.util.Date
83 |
84 | #-----------------------------------------------
85 | # (5/6) FILTER OUT CERTAIN TABLES
86 | #-----------------------------------------------
87 | #
88 | # COMMA SEPARATED list of table types to be mapped
89 | # Commonly seen types are TABLE, VIEW, SYSTEM TABLE, SYNONYM
90 | jdbc.tabletypes=TABLE
91 |
92 | # Table name pattern of tables to be mapped to classes.
93 | # available wildcard: %
94 | # defaults to %
95 | # You can specify several patterns separated by commas.
96 | jdbc.tablenamepattern=%
97 |
98 | # SPACE SEPARATED list of tables to include or exclude. If you specify both,
99 | # the include list will take priority. If these fields are left commented out,
100 | # all tables in the specified schema will get mapped to classes
101 | #mgrwriter.include=Testing
102 | #mgrwriter.exclude=
103 |
104 | #-----------------------------------------------
105 | # (6/6) CONFIGURE OPTIMISTIC LOCK
106 | #-----------------------------------------------
107 | # optimisticlock.type can take 2 values:
108 | # none - the optimistic lock mechanism is disabled (default).
109 | # timestamp - the optimistic lock column contains the System.currentTimeMillis() value.
110 | #
111 | # optimisticlock.column takes the column name used by optimistic lock mechanism in your database.
112 | # If this column is not present in some table the optimistic lock is not applied there.
113 | # the column mapping can be java.lang.Long or java.lang.String.
114 | # (jdbc type size >= 13 characters)
115 | optimisticlock.type=timestamp
116 | optimisticlock.column=version_time
117 |
--------------------------------------------------------------------------------
/sql2java-test/src/main/resources/sqltool.rc:
--------------------------------------------------------------------------------
1 | urlid test
2 | url jdbc:hsqldb:file:target/databases/test
3 | username SA
4 | password
5 |
--------------------------------------------------------------------------------
/sql2java-test/src/main/sql/00-test.sql:
--------------------------------------------------------------------------------
1 | CREATE TABLE person (
2 | id integer GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
3 | username varchar(255) NOT NULL,
4 | first_name varchar(255) NOT NULL,
5 | last_name varchar(255) NOT NULL,
6 | create_date datetime NOT NULL,
7 | update_date timestamp DEFAULT CURRENT_TIMESTAMP NOT NULL,
8 | UNIQUE (username)
9 | );
10 |
11 | CREATE TABLE phone (
12 | id integer GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
13 | phone_number varchar(30) NOT NULL,
14 | phone_type integer NOT NULL,
15 | person_id integer NOT NULL,
16 | create_date datetime NOT NULL,
17 | FOREIGN KEY (person_id) REFERENCES person(id),
18 | UNIQUE (phone_number)
19 | );
20 |
--------------------------------------------------------------------------------
/sql2java-test/src/main/sql/01-test.sql:
--------------------------------------------------------------------------------
1 | insert into person (username, first_name, last_name, create_date) values ('farkhan', 'Farkhan', 'Parambulator', now());
2 | insert into phone (phone_number, phone_type, person_id, create_date) values ('+12125551212', 1, identity(), now());
3 |
--------------------------------------------------------------------------------
/sql2java-test/src/test/java/com/test/TransactionTest.java:
--------------------------------------------------------------------------------
1 | package com.test;
2 |
3 | import java.io.File;
4 | import java.util.Date;
5 | import javax.sql.DataSource;
6 | import net.sourceforge.sql2java.lib.*;
7 | import org.hsqldb.jdbc.JDBCDataSource;
8 | import org.junit.*;
9 |
10 | public class TransactionTest {
11 |
12 | @Test public void twoTableCommitTransactionTest() throws Exception {
13 | JDBCDataSource ds = new JDBCDataSource();
14 | ds.setDatabase("jdbc:hsqldb:file:target/databases/test");
15 | ds.setUser("SA");
16 | ds.setPassword("");
17 |
18 | PublicDatabase db = new PublicDatabase(ds);
19 | //clean up
20 | db.deleteByWhere(Phone.class, "WHERE PHONE_NUMBER='+14105551212'");
21 | db.deleteByWhere(Person.class, "WHERE USERNAME='hansolo'");
22 |
23 | try {
24 | db.beginTransaction(Txn.Isolation.REPEATABLE_READ);
25 | Person s0 = db.createBean(Person.class);
26 | s0.setUsername("hansolo");
27 | s0.setFirstName("Harrison");
28 | s0.setLastName("Ford");
29 | s0.setCreateDate(new Date());
30 | s0 = db.save(s0);
31 | Phone m0 = db.createBean(Phone.class);
32 | m0.setPersonId(s0.getId());
33 | m0.setPhoneType(1);
34 | m0.setPhoneNumber("+14105551212");
35 | m0.setCreateDate(new Date());
36 | m0 = db.save(m0);
37 | db.commitTransaction();
38 | } finally {
39 | db.endTransaction();
40 | }
41 |
42 | Person s1 = db.loadUniqueByWhere(Person.class, "WHERE USERNAME='hansolo'");
43 | Assert.assertNotNull(s1);
44 |
45 | Phone m1 = db.loadUniqueByWhere(Phone.class, "WHERE PHONE_NUMBER='+14105551212'");
46 | Assert.assertNotNull(m1);
47 | }
48 |
49 |
50 | @Test public void twoTableRollbackTransactionTest() throws Exception {
51 | JDBCDataSource ds = new JDBCDataSource();
52 | ds.setDatabase("jdbc:hsqldb:file:target/databases/test");
53 | ds.setUser("SA");
54 | ds.setPassword("");
55 |
56 | PublicDatabase db = new PublicDatabase(ds);
57 | //clean up
58 | db.deleteByWhere(Phone.class, "WHERE PHONE_NUMBER='+14105551212'");
59 | db.deleteByWhere(Person.class, "WHERE USERNAME='hansolo'");
60 |
61 | try {
62 | db.beginTransaction(Txn.Isolation.REPEATABLE_READ);
63 | Person s0 = db.createBean(Person.class);
64 | s0.setUsername("hansolo");
65 | s0.setFirstName("Harrison");
66 | s0.setLastName("Ford");
67 | s0.setCreateDate(new Date());
68 | s0 = db.save(s0);
69 | Phone m0 = db.createBean(Phone.class);
70 | m0.setPersonId(s0.getId());
71 | m0.setPhoneType(1);
72 | m0.setPhoneNumber("+14105551212");
73 | m0.setCreateDate(new Date());
74 | m0 = db.save(m0);
75 | db.rollbackTransaction();
76 | } finally {
77 | db.endTransaction();
78 | }
79 |
80 | Person s1 = db.loadUniqueByWhere(Person.class, "WHERE USERNAME='hansolo'");
81 | Assert.assertNull(s1);
82 |
83 | Phone m1 = db.loadUniqueByWhere(Phone.class, "WHERE PHONE_NUMBER='+14105551212'");
84 | Assert.assertNull(m1);
85 | }
86 |
87 | }
88 |
--------------------------------------------------------------------------------
/sql2java-test/src/test/resources/sqltool.rc:
--------------------------------------------------------------------------------
1 | urlid test
2 | url jdbc:hsqldb:file:target/databases/test
3 | username SA
4 | password
5 |
--------------------------------------------------------------------------------