Hibernate SVN: r18624 - in branches/Branch_3_2/HibernateExt/tools/src: java/org/hibernate/cfg/reveng and 2 other directories.
by hibernate-commits@lists.jboss.org
Author: max.andersen(a)jboss.com
Date: 2010-01-26 07:19:38 -0500 (Tue, 26 Jan 2010)
New Revision: 18624
Added:
branches/Branch_3_2/HibernateExt/tools/src/java/org/hibernate/cfg/MetaDataDialectFactory.java
branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/test/jdbc2cfg/MetaDataDialectFactoryTest.java
Modified:
branches/Branch_3_2/HibernateExt/tools/src/java/org/hibernate/cfg/JDBCReaderFactory.java
branches/Branch_3_2/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/DefaultReverseEngineeringStrategy.java
branches/Branch_3_2/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/dialect/HSQLMetaDataDialect.java
branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/test/jdbc2cfg/Jdbc2CfgAllTests.java
Log:
Fixed statement leak and quoting bug for JBIDE-4486 Primary Key or Idenity not being respected
+ JBIDE-4426 Filtering Oracle's bogus $BIN tables
Modified: branches/Branch_3_2/HibernateExt/tools/src/java/org/hibernate/cfg/JDBCReaderFactory.java
===================================================================
--- branches/Branch_3_2/HibernateExt/tools/src/java/org/hibernate/cfg/JDBCReaderFactory.java 2010-01-26 08:48:00 UTC (rev 18623)
+++ branches/Branch_3_2/HibernateExt/tools/src/java/org/hibernate/cfg/JDBCReaderFactory.java 2010-01-26 12:19:38 UTC (rev 18624)
@@ -4,18 +4,8 @@
import org.hibernate.cfg.reveng.JDBCReader;
import org.hibernate.cfg.reveng.ReverseEngineeringStrategy;
-import org.hibernate.cfg.reveng.dialect.H2MetaDataDialect;
-import org.hibernate.cfg.reveng.dialect.HSQLMetaDataDialect;
-import org.hibernate.cfg.reveng.dialect.JDBCMetaDataDialect;
import org.hibernate.cfg.reveng.dialect.MetaDataDialect;
-import org.hibernate.cfg.reveng.dialect.MySQLMetaDataDialect;
-import org.hibernate.cfg.reveng.dialect.OracleMetaDataDialect;
import org.hibernate.dialect.Dialect;
-import org.hibernate.dialect.H2Dialect;
-import org.hibernate.dialect.HSQLDialect;
-import org.hibernate.dialect.MySQLDialect;
-import org.hibernate.dialect.Oracle9Dialect;
-import org.hibernate.util.ReflectHelper;
final public class JDBCReaderFactory {
@@ -33,30 +23,9 @@
.getSQLExceptionConverter(), settings.getDefaultCatalogName(), settings.getDefaultSchemaName(), revengStrategy );
}
- public static MetaDataDialect newMetaDataDialect(Dialect dialect, Properties cfg) {
- String property = cfg.getProperty( "hibernatetool.metadatadialect" );
- if ( property != null ) {
- try {
- return (MetaDataDialect) ReflectHelper.classForName( property,
- JDBCReaderFactory.class ).newInstance();
- }
- catch (Exception e) {
- throw new JDBCBinderException(
- "Could not load MetaDataDialect: " + property, e );
- }
- }
- if(dialect!=null) { // temporary hack to enable dialect specific metadata dialects.
- if(dialect instanceof Oracle9Dialect) {
- return new OracleMetaDataDialect();
- } else if (dialect instanceof H2Dialect) {
- return new H2MetaDataDialect();
- } else if (dialect instanceof MySQLDialect) {
- return new MySQLMetaDataDialect();
- } else if (dialect instanceof HSQLDialect) {
- return new HSQLMetaDataDialect();
- }
- }
- return new JDBCMetaDataDialect();
+ public static MetaDataDialect newMetaDataDialect(Dialect dialect, Properties cfg) {
+ return new MetaDataDialectFactory().createMetaDataDialect(dialect, cfg);
+
}
-
+
}
Added: branches/Branch_3_2/HibernateExt/tools/src/java/org/hibernate/cfg/MetaDataDialectFactory.java
===================================================================
--- branches/Branch_3_2/HibernateExt/tools/src/java/org/hibernate/cfg/MetaDataDialectFactory.java (rev 0)
+++ branches/Branch_3_2/HibernateExt/tools/src/java/org/hibernate/cfg/MetaDataDialectFactory.java 2010-01-26 12:19:38 UTC (rev 18624)
@@ -0,0 +1,85 @@
+package org.hibernate.cfg;
+
+import java.util.Properties;
+
+import org.hibernate.cfg.reveng.dialect.H2MetaDataDialect;
+import org.hibernate.cfg.reveng.dialect.HSQLMetaDataDialect;
+import org.hibernate.cfg.reveng.dialect.JDBCMetaDataDialect;
+import org.hibernate.cfg.reveng.dialect.MetaDataDialect;
+import org.hibernate.cfg.reveng.dialect.MySQLMetaDataDialect;
+import org.hibernate.cfg.reveng.dialect.OracleMetaDataDialect;
+import org.hibernate.dialect.Dialect;
+import org.hibernate.dialect.H2Dialect;
+import org.hibernate.dialect.HSQLDialect;
+import org.hibernate.dialect.MySQLDialect;
+import org.hibernate.dialect.Oracle8iDialect;
+import org.hibernate.dialect.Oracle9Dialect;
+import org.hibernate.util.ReflectHelper;
+
+public class MetaDataDialectFactory {
+
+ public MetaDataDialect createMetaDataDialect(Dialect dialect, Properties cfg) {
+ String property = cfg.getProperty( "hibernatetool.metadatadialect" );
+ MetaDataDialect mdd = fromClassName(property);
+ if(mdd==null) {
+ mdd = fromDialect(dialect);
+ }
+ if(mdd==null) {
+ mdd = fromDialectName(dialect.getClass().getName());
+ }
+ if(mdd==null) {
+ mdd = new JDBCMetaDataDialect();
+ }
+ return mdd;
+ }
+
+ private MetaDataDialect fromClassName(String property) {
+ if ( property != null ) {
+ try {
+ return (MetaDataDialect) ReflectHelper.classForName( property,
+ JDBCReaderFactory.class ).newInstance();
+ }
+ catch (Exception e) {
+ throw new JDBCBinderException(
+ "Could not load MetaDataDialect: " + property, e );
+ }
+ } else {
+ return null;
+ }
+ }
+
+ public MetaDataDialect fromDialect(Dialect dialect) {
+ if(dialect!=null) {
+ if(dialect instanceof Oracle9Dialect) {
+ return new OracleMetaDataDialect();
+ } else if(dialect instanceof Oracle8iDialect) {
+ return new OracleMetaDataDialect();
+ } else if (dialect instanceof H2Dialect) {
+ return new H2MetaDataDialect();
+ } else if (dialect instanceof MySQLDialect) {
+ return new MySQLMetaDataDialect();
+ } else if (dialect instanceof HSQLDialect) {
+ return new HSQLMetaDataDialect();
+ }
+ }
+ return null;
+ }
+
+ public MetaDataDialect fromDialectName(String dialect) {
+ if (dialect.toLowerCase().contains("oracle")) {
+ return new OracleMetaDataDialect();
+ }
+ if (dialect.toLowerCase().contains("mysql")) {
+ return new MySQLMetaDataDialect();
+ }
+ if (dialect.toLowerCase().contains("h2")) {
+ return new H2MetaDataDialect();
+ }
+ if (dialect.toLowerCase().contains("hsql")) {
+ return new HSQLMetaDataDialect();
+ }
+ return null;
+ }
+
+
+}
Modified: branches/Branch_3_2/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/DefaultReverseEngineeringStrategy.java
===================================================================
--- branches/Branch_3_2/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/DefaultReverseEngineeringStrategy.java 2010-01-26 08:48:00 UTC (rev 18623)
+++ branches/Branch_3_2/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/DefaultReverseEngineeringStrategy.java 2010-01-26 12:19:38 UTC (rev 18624)
@@ -125,8 +125,7 @@
}
}
- public boolean excludeTable(TableIdentifier ti) {
- if(ti.getName().startsWith("BIN$")) return true; // hard code oracle recycle bin names. Better than requiring users to do it manually. TODO: make it dependent on dialect.
+ public boolean excludeTable(TableIdentifier ti) {
return false;
}
Modified: branches/Branch_3_2/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/dialect/HSQLMetaDataDialect.java
===================================================================
--- branches/Branch_3_2/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/dialect/HSQLMetaDataDialect.java 2010-01-26 08:48:00 UTC (rev 18623)
+++ branches/Branch_3_2/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/dialect/HSQLMetaDataDialect.java 2010-01-26 12:19:38 UTC (rev 18624)
@@ -10,6 +10,7 @@
import org.hibernate.cfg.reveng.dialect.JDBCMetaDataDialect;
import org.hibernate.cfg.reveng.dialect.ResultSetIterator;
+import org.hibernate.mapping.Table;
/**
* @author Dmitry Geraskov
@@ -17,6 +18,18 @@
*/
public class HSQLMetaDataDialect extends JDBCMetaDataDialect {
+ private String quote(String columnName) {
+ if(columnName==null) return columnName;
+ if(needQuote(columnName)) {
+ if(columnName.length()>1 && columnName.charAt(0)=='\"' && columnName.charAt(columnName.length()-1)=='\"') {
+ return columnName; // avoid double quoting
+ }
+ return "\"" + columnName + "\"";
+ } else {
+ return columnName;
+ }
+ }
+
public Iterator getSuggestedPrimaryKeyStrategyName(String catalog, String schema, String table) {
String sql = null;
try {
@@ -27,30 +40,45 @@
//log.debug("geSuggestedPrimaryKeyStrategyName(" + catalog + "." + schema + "." + table + ")");
final String sc = schema;
+ final String cat = catalog;
return new ResultSetIterator(getMetaData().getTables(catalog, schema, table, new String[]{"TABLE"}),
getSQLExceptionConverter()) {
Map element = new HashMap();
protected Object convertRow(ResultSet tableRs) throws SQLException{
String table = tableRs.getString("TABLE_NAME");
- String fullTableName = (sc == null ? "" : sc + '.') + table;
+ String fullTableName = Table.qualify(cat, sc, quote(table));
String sql ="SELECT * FROM " + fullTableName + " WHERE FALSE";
- PreparedStatement statement = getConnection().prepareStatement( sql );
-
- element.clear();
- element.put("TABLE_NAME", table);
- element.put("TABLE_SCHEM", sc);
- element.put("TABLE_CAT", null);
-
boolean isAutoIncrement = false;
- ResultSet rs = statement.executeQuery();
- ResultSetMetaData rsmd = rs.getMetaData();
- for (int i = 0; i < rsmd.getColumnCount(); i++) {
- isAutoIncrement = rsmd.isAutoIncrement(i + 1);
- if (isAutoIncrement) break;
- }
+ PreparedStatement statement = null;
+ try {
+ statement = getConnection().prepareStatement( sql );
+ element.clear();
+ element.put("TABLE_NAME", table);
+ element.put("TABLE_SCHEM", sc);
+ element.put("TABLE_CAT", null);
+
+ ResultSet rs = statement.executeQuery();
+ ResultSetMetaData rsmd = rs.getMetaData();
+ for (int i = 0; i < rsmd.getColumnCount(); i++) {
+ isAutoIncrement = rsmd.isAutoIncrement(i + 1);
+ if (isAutoIncrement) break;
+ }
+
+ } finally {
+ if(statement!=null) {
+ try {
+ statement.close();
+ }
+ catch (SQLException e) {
+ throw getSQLExceptionConverter().convert(e,
+ "Problem while closing prepared statement", null);
+ }
+ }
+ }
+
if(isAutoIncrement) {
element.put("HIBERNATE_STRATEGY", "identity");
} else {
Modified: branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/test/jdbc2cfg/Jdbc2CfgAllTests.java
===================================================================
--- branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/test/jdbc2cfg/Jdbc2CfgAllTests.java 2010-01-26 08:48:00 UTC (rev 18623)
+++ branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/test/jdbc2cfg/Jdbc2CfgAllTests.java 2010-01-26 12:19:38 UTC (rev 18624)
@@ -1,5 +1,6 @@
package org.hibernate.tool.test.jdbc2cfg;
+
import junit.framework.Test;
import junit.framework.TestSuite;
@@ -28,6 +29,7 @@
suite.addTest(AutoQuoteTest.suite());
suite.addTest(KeyPropertyCompositeIdTest.suite());
suite.addTest(IndexTest.suite());
+ suite.addTest(new TestSuite(MetaDataDialectFactoryTest.class));
//$JUnit-END$
return suite;
}
Added: branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/test/jdbc2cfg/MetaDataDialectFactoryTest.java
===================================================================
--- branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/test/jdbc2cfg/MetaDataDialectFactoryTest.java (rev 0)
+++ branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/test/jdbc2cfg/MetaDataDialectFactoryTest.java 2010-01-26 12:19:38 UTC (rev 18624)
@@ -0,0 +1,120 @@
+package org.hibernate.tool.test.jdbc2cfg;
+
+import java.util.Properties;
+
+import junit.framework.TestCase;
+
+import org.hibernate.cfg.JDBCBinderException;
+import org.hibernate.cfg.MetaDataDialectFactory;
+import org.hibernate.cfg.reveng.dialect.H2MetaDataDialect;
+import org.hibernate.cfg.reveng.dialect.HSQLMetaDataDialect;
+import org.hibernate.cfg.reveng.dialect.JDBCMetaDataDialect;
+import org.hibernate.cfg.reveng.dialect.MySQLMetaDataDialect;
+import org.hibernate.cfg.reveng.dialect.OracleMetaDataDialect;
+import org.hibernate.dialect.Dialect;
+import org.hibernate.dialect.H2Dialect;
+import org.hibernate.dialect.HSQLDialect;
+import org.hibernate.dialect.MySQL5Dialect;
+import org.hibernate.dialect.MySQL5InnoDBDialect;
+import org.hibernate.dialect.Oracle10gDialect;
+import org.hibernate.dialect.Oracle8iDialect;
+import org.hibernate.dialect.Oracle9Dialect;
+import org.hibernate.dialect.Oracle9iDialect;
+import org.hibernate.dialect.OracleDialect;
+
+public class MetaDataDialectFactoryTest extends TestCase {
+
+ private MetaDataDialectFactory mdf;
+
+ static class NoNameDialect extends Dialect {
+
+ }
+
+ static class H2NamedDialect extends Dialect {
+
+ }
+
+ protected void setUp() throws Exception {
+ mdf = new MetaDataDialectFactory();
+ }
+
+ public void testCreateMetaDataDialect() {
+ assertSameClass("Generic metadata for dialects with no specifics", JDBCMetaDataDialect.class, mdf.createMetaDataDialect(new NoNameDialect(), new Properties()));
+ assertSameClass(H2MetaDataDialect.class, mdf.createMetaDataDialect(new H2NamedDialect(), new Properties()));
+ assertSameClass(OracleMetaDataDialect.class, mdf.createMetaDataDialect(new OracleDialect(), new Properties()));
+ assertSameClass(MySQLMetaDataDialect.class, mdf.createMetaDataDialect(new MySQL5Dialect(), new Properties()));
+
+ Properties p = new Properties();
+ p.setProperty("hibernatetool.metadatadialect", H2MetaDataDialect.class.getCanonicalName());
+ assertSameClass("property should override specific dialect", H2MetaDataDialect.class, mdf.createMetaDataDialect(new MySQL5Dialect(), p));
+
+ }
+
+ public void testCreateMetaDataDialectNonExistingOverride(Properties p) {
+ p.setProperty("hibernatetool.metadatadialect", "DoesNotExists");
+ try {
+ mdf.createMetaDataDialect(new MySQL5Dialect(), p);
+ fail();
+ } catch (JDBCBinderException jbe) {
+ // expected
+ } catch(Exception e) {
+ fail();
+ }
+ }
+
+ public void testFromDialect() {
+ assertSameClass("Generic metadata for dialects with no specifics", null, mdf.fromDialect(new NoNameDialect()));
+
+ assertSameClass(OracleMetaDataDialect.class, mdf.fromDialect(new Oracle8iDialect()));
+ assertSameClass(OracleMetaDataDialect.class, mdf.fromDialect(new Oracle9Dialect()));
+ assertSameClass(OracleMetaDataDialect.class, mdf.fromDialect(new Oracle10gDialect()));
+ assertSameClass(OracleMetaDataDialect.class, mdf.fromDialect(new Oracle9iDialect()));
+ assertSameClass(MySQLMetaDataDialect.class, mdf.fromDialect(new MySQL5InnoDBDialect()));
+ assertSameClass(H2MetaDataDialect.class, mdf.fromDialect(new H2Dialect()));
+ assertSameClass(HSQLMetaDataDialect.class, mdf.fromDialect(new HSQLDialect()));
+
+ }
+
+ public void testFromDialectName() {
+ assertSameClass(null, mdf.fromDialectName("BlahBlah"));
+ assertSameClass(OracleMetaDataDialect.class, mdf.fromDialectName("mYorAcleDialect"));
+ assertSameClass(OracleMetaDataDialect.class, mdf.fromDialectName(Oracle8iDialect.class.getName()));
+ assertSameClass(OracleMetaDataDialect.class, mdf.fromDialectName(Oracle9Dialect.class.getName()));
+ assertSameClass(MySQLMetaDataDialect.class, mdf.fromDialectName(MySQL5InnoDBDialect.class.getName()));
+ assertSameClass(H2MetaDataDialect.class, mdf.fromDialectName(H2Dialect.class.getName()));
+ assertSameClass(HSQLMetaDataDialect.class, mdf.fromDialectName(HSQLDialect.class.getName()));
+
+ }
+
+ public void assertSameClass(Class clazz, Object instance) {
+ if(clazz==null && instance==null) {
+ assertEquals(null,null);
+ return;
+ }
+ if(clazz==null) {
+ assertEquals(null, instance);
+ return;
+ }
+ if(instance==null) {
+ assertEquals(clazz.getCanonicalName(), null);
+ return;
+ }
+ assertEquals(clazz.getCanonicalName(), instance.getClass().getName());
+ }
+
+ public void assertSameClass(String msg, Class clazz, Object instance) {
+ if(clazz==null && instance==null) {
+ assertEquals(null,null);
+ return;
+ }
+ if(clazz==null) {
+ assertEquals(msg, null, instance);
+ return;
+ }
+ if(instance==null) {
+ assertEquals(msg, clazz.getCanonicalName(), null);
+ return;
+ }
+ assertEquals(msg, clazz.getCanonicalName(), instance.getClass().getName());
+ }
+}
14 years, 11 months
Hibernate SVN: r18623 - in branches/Branch_3_2/HibernateExt/tools/src: java/org/hibernate/cfg/reveng/dialect and 2 other directories.
by hibernate-commits@lists.jboss.org
Author: max.andersen(a)jboss.com
Date: 2010-01-26 03:48:00 -0500 (Tue, 26 Jan 2010)
New Revision: 18623
Added:
branches/Branch_3_2/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/dialect/HSQLMetaDataDialect.java
branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/test/jdbc2cfg/identity/HSQLIdentityTest.java
Modified:
branches/Branch_3_2/HibernateExt/tools/src/java/org/hibernate/cfg/JDBCReaderFactory.java
branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/Hbm2XAllTests.java
Log:
JBIDE-4486 Primary Key or Idenity not being respected (reviewed and committed patch from dgeraskov)
Modified: branches/Branch_3_2/HibernateExt/tools/src/java/org/hibernate/cfg/JDBCReaderFactory.java
===================================================================
--- branches/Branch_3_2/HibernateExt/tools/src/java/org/hibernate/cfg/JDBCReaderFactory.java 2010-01-26 02:58:26 UTC (rev 18622)
+++ branches/Branch_3_2/HibernateExt/tools/src/java/org/hibernate/cfg/JDBCReaderFactory.java 2010-01-26 08:48:00 UTC (rev 18623)
@@ -5,12 +5,14 @@
import org.hibernate.cfg.reveng.JDBCReader;
import org.hibernate.cfg.reveng.ReverseEngineeringStrategy;
import org.hibernate.cfg.reveng.dialect.H2MetaDataDialect;
+import org.hibernate.cfg.reveng.dialect.HSQLMetaDataDialect;
import org.hibernate.cfg.reveng.dialect.JDBCMetaDataDialect;
import org.hibernate.cfg.reveng.dialect.MetaDataDialect;
import org.hibernate.cfg.reveng.dialect.MySQLMetaDataDialect;
import org.hibernate.cfg.reveng.dialect.OracleMetaDataDialect;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.H2Dialect;
+import org.hibernate.dialect.HSQLDialect;
import org.hibernate.dialect.MySQLDialect;
import org.hibernate.dialect.Oracle9Dialect;
import org.hibernate.util.ReflectHelper;
@@ -50,6 +52,8 @@
return new H2MetaDataDialect();
} else if (dialect instanceof MySQLDialect) {
return new MySQLMetaDataDialect();
+ } else if (dialect instanceof HSQLDialect) {
+ return new HSQLMetaDataDialect();
}
}
return new JDBCMetaDataDialect();
Added: branches/Branch_3_2/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/dialect/HSQLMetaDataDialect.java
===================================================================
--- branches/Branch_3_2/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/dialect/HSQLMetaDataDialect.java (rev 0)
+++ branches/Branch_3_2/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/dialect/HSQLMetaDataDialect.java 2010-01-26 08:48:00 UTC (rev 18623)
@@ -0,0 +1,72 @@
+package org.hibernate.cfg.reveng.dialect;
+
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.ResultSetMetaData;
+import java.sql.SQLException;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+import org.hibernate.cfg.reveng.dialect.JDBCMetaDataDialect;
+import org.hibernate.cfg.reveng.dialect.ResultSetIterator;
+
+/**
+ * @author Dmitry Geraskov
+ *
+ */
+public class HSQLMetaDataDialect extends JDBCMetaDataDialect {
+
+ public Iterator getSuggestedPrimaryKeyStrategyName(String catalog, String schema, String table) {
+ String sql = null;
+ try {
+ catalog = caseForSearch( catalog );
+ schema = caseForSearch( schema );
+ table = caseForSearch( table );
+
+ //log.debug("geSuggestedPrimaryKeyStrategyName(" + catalog + "." + schema + "." + table + ")");
+
+ final String sc = schema;
+ return new ResultSetIterator(getMetaData().getTables(catalog, schema, table, new String[]{"TABLE"}),
+ getSQLExceptionConverter()) {
+
+ Map element = new HashMap();
+ protected Object convertRow(ResultSet tableRs) throws SQLException{
+ String table = tableRs.getString("TABLE_NAME");
+ String fullTableName = (sc == null ? "" : sc + '.') + table;
+
+ String sql ="SELECT * FROM " + fullTableName + " WHERE FALSE";
+ PreparedStatement statement = getConnection().prepareStatement( sql );
+
+ element.clear();
+ element.put("TABLE_NAME", table);
+ element.put("TABLE_SCHEM", sc);
+ element.put("TABLE_CAT", null);
+
+ boolean isAutoIncrement = false;
+ ResultSet rs = statement.executeQuery();
+ ResultSetMetaData rsmd = rs.getMetaData();
+ for (int i = 0; i < rsmd.getColumnCount(); i++) {
+ isAutoIncrement = rsmd.isAutoIncrement(i + 1);
+ if (isAutoIncrement) break;
+ }
+
+ if(isAutoIncrement) {
+ element.put("HIBERNATE_STRATEGY", "identity");
+ } else {
+ element.put("HIBERNATE_STRATEGY", null);
+ }
+ return element;
+ }
+ protected Throwable handleSQLException(SQLException e) {
+ // schemaRs and catalogRs are only used for error reporting if
+ // we get an exception
+ throw getSQLExceptionConverter().convert( e,
+ "Could not get list of suggested identity strategies from database. Probably a JDBC driver problem. ", null);
+ }
+ };
+ } catch (SQLException e) {
+ throw getSQLExceptionConverter().convert(e, "Could not get list of suggested identity strategies from database. Probably a JDBC driver problem. ", sql);
+ }
+ }
+}
Modified: branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/Hbm2XAllTests.java
===================================================================
--- branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/Hbm2XAllTests.java 2010-01-26 02:58:26 UTC (rev 18622)
+++ branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/Hbm2XAllTests.java 2010-01-26 08:48:00 UTC (rev 18623)
@@ -1,11 +1,12 @@
package org.hibernate.tool.hbm2x;
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
import org.hibernate.tool.test.jdbc2cfg.identity.H2IdentityTest;
+import org.hibernate.tool.test.jdbc2cfg.identity.HSQLIdentityTest;
import org.hibernate.tool.test.jdbc2cfg.identity.MySQLIdentityTest;
-import junit.framework.Test;
-import junit.framework.TestSuite;
-
public class Hbm2XAllTests {
public static Test suite() {
@@ -36,6 +37,7 @@
suite.addTestSuite(H2IdentityTest.class);
suite.addTestSuite(MySQLIdentityTest.class);
+ suite.addTestSuite(HSQLIdentityTest.class);
return suite;
}
Added: branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/test/jdbc2cfg/identity/HSQLIdentityTest.java
===================================================================
--- branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/test/jdbc2cfg/identity/HSQLIdentityTest.java (rev 0)
+++ branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/test/jdbc2cfg/identity/HSQLIdentityTest.java 2010-01-26 08:48:00 UTC (rev 18623)
@@ -0,0 +1,50 @@
+package org.hibernate.tool.test.jdbc2cfg.identity;
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+import org.hibernate.cfg.JDBCMetaDataConfiguration;
+import org.hibernate.cfg.reveng.dialect.HSQLMetaDataDialect;
+import org.hibernate.dialect.Dialect;
+import org.hibernate.dialect.HSQLDialect;
+
+/**
+ * @author Dmitry Geraskov
+ *
+ */
+public class HSQLIdentityTest extends AbstractIdentityTest {
+
+ /**
+ * @return
+ */
+ protected String[] getDropSQL() {
+ return new String[] {
+ "DROP TABLE AUTOINC IF EXISTS",
+ "DROP TABLE NOAUTOINC IF EXISTS",
+ };
+ }
+
+ /**
+ * @return
+ */
+ protected String[] getCreateSQL() {
+
+ return new String[] {
+ "CREATE TABLE AUTOINC (I identity, C CHAR(20), D CHAR(20))",
+ "CREATE TABLE NOAUTOINC (I int, C CHAR(20), D CHAR(20))",
+ };
+ }
+
+ public boolean appliesTo(Dialect dialect) {
+ return dialect instanceof HSQLDialect;
+ }
+
+ protected void configure(JDBCMetaDataConfiguration configuration) {
+ configuration.setProperty( "hibernatetool.metadatadialect", HSQLMetaDataDialect.class.getName() );
+ }
+
+ public static Test suite() {
+ return new TestSuite(HSQLIdentityTest.class);
+ }
+
+}
14 years, 11 months
Hibernate SVN: r18622 - in jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen: annotation and 2 other directories.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2010-01-25 21:58:26 -0500 (Mon, 25 Jan 2010)
New Revision: 18622
Added:
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/util/
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/util/TypeUtils.java
Removed:
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/TypeUtils.java
Modified:
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/Context.java
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/JPAMetaModelEntityProcessor.java
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationMetaEntity.java
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaEntity.java
Log:
METAGEN-16 - Code makes use of getAnnotation() instead of getAnnotationMirrors()
Modified: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/Context.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/Context.java 2010-01-25 18:49:02 UTC (rev 18621)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/Context.java 2010-01-26 02:58:26 UTC (rev 18622)
@@ -27,6 +27,7 @@
import javax.tools.Diagnostic;
import org.hibernate.jpamodelgen.annotation.AnnotationMetaEntity;
+import org.hibernate.jpamodelgen.util.TypeUtils;
/**
* @author Max Andersen
Modified: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/JPAMetaModelEntityProcessor.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/JPAMetaModelEntityProcessor.java 2010-01-25 18:49:02 UTC (rev 18621)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/JPAMetaModelEntityProcessor.java 2010-01-26 02:58:26 UTC (rev 18622)
@@ -29,10 +29,12 @@
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import javax.persistence.Embeddable;
+import javax.persistence.Entity;
import javax.persistence.MappedSuperclass;
import javax.tools.Diagnostic;
import org.hibernate.jpamodelgen.annotation.AnnotationMetaEntity;
+import org.hibernate.jpamodelgen.util.TypeUtils;
import org.hibernate.jpamodelgen.xml.XmlParser;
import static javax.lang.model.SourceVersion.RELEASE_6;
@@ -48,11 +50,7 @@
@SupportedSourceVersion(RELEASE_6)
public class JPAMetaModelEntityProcessor extends AbstractProcessor {
-
private static final Boolean ALLOW_OTHER_PROCESSORS_TO_CLAIM_ANNOTATIONS = Boolean.FALSE;
- private static final String ENTITY_ANN = javax.persistence.Entity.class.getName();
- private static final String MAPPED_SUPERCLASS_ANN = MappedSuperclass.class.getName();
- private static final String EMBEDDABLE_ANN = Embeddable.class.getName();
private boolean xmlProcessed = false;
private Context context;
@@ -115,14 +113,13 @@
private boolean hostJPAAnnotations(Set<? extends TypeElement> annotations) {
for ( TypeElement type : annotations ) {
- final String typeName = type.getQualifiedName().toString();
- if ( typeName.equals( ENTITY_ANN ) ) {
+ if ( TypeUtils.isTypeElementOfType( type, Entity.class ) ) {
return true;
}
- else if ( typeName.equals( EMBEDDABLE_ANN ) ) {
+ else if ( TypeUtils.isTypeElementOfType( type, Embeddable.class ) ) {
return true;
}
- else if ( typeName.equals( MAPPED_SUPERCLASS_ANN ) ) {
+ else if ( TypeUtils.isTypeElementOfType( type, MappedSuperclass.class ) ) {
return true;
}
}
@@ -131,20 +128,17 @@
private void handleRootElementAnnotationMirrors(final Element element) {
- List<? extends AnnotationMirror> annotationMirrors = element
- .getAnnotationMirrors();
+ List<? extends AnnotationMirror> annotationMirrors = element.getAnnotationMirrors();
for ( AnnotationMirror mirror : annotationMirrors ) {
- final String annotationType = mirror.getAnnotationType().toString();
-
if ( element.getKind() == ElementKind.CLASS ) {
- if ( annotationType.equals( ENTITY_ANN ) ) {
+ if ( TypeUtils.isAnnotationMirrorOfType( mirror, Entity.class ) ) {
AnnotationMetaEntity metaEntity = new AnnotationMetaEntity( ( TypeElement ) element, context );
// TODO instead of just adding the entity we have to do some merging.
context.getMetaEntitiesToProcess().put( metaEntity.getQualifiedName(), metaEntity );
}
- else if ( annotationType.equals( MAPPED_SUPERCLASS_ANN )
- || annotationType.equals( EMBEDDABLE_ANN ) ) {
+ else if ( TypeUtils.isAnnotationMirrorOfType( mirror, MappedSuperclass.class )
+ || TypeUtils.isAnnotationMirrorOfType( mirror, Embeddable.class ) ) {
AnnotationMetaEntity metaEntity = new AnnotationMetaEntity( ( TypeElement ) element, context );
// TODO instead of just adding the entity we have to do some merging.
Deleted: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/TypeUtils.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/TypeUtils.java 2010-01-25 18:49:02 UTC (rev 18621)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/TypeUtils.java 2010-01-26 02:58:26 UTC (rev 18622)
@@ -1,96 +0,0 @@
-// $Id$
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2008, Red Hat Middleware LLC, and individual contributors
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-* http://www.apache.org/licenses/LICENSE-2.0
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-package org.hibernate.jpamodelgen;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.lang.model.type.TypeMirror;
-import javax.lang.model.type.TypeKind;
-import javax.lang.model.type.DeclaredType;
-import javax.lang.model.element.TypeElement;
-import javax.lang.model.element.Element;
-import javax.lang.model.type.TypeVariable;
-import javax.lang.model.util.Types;
-
-/**
- * Utility class.
- *
- * @author Max Andersen
- * @author Hardy Ferentschik
- * @author Emmanuel Bernard
- */
-public class TypeUtils {
-
- private static final Map<String, String> PRIMITIVES = new HashMap<String, String>();
- static {
- PRIMITIVES.put( "char", "Character" );
-
- PRIMITIVES.put( "byte", "Byte" );
- PRIMITIVES.put( "short", "Short" );
- PRIMITIVES.put( "int", "Integer" );
- PRIMITIVES.put( "long", "Long" );
-
- PRIMITIVES.put( "boolean", "Boolean" );
-
- PRIMITIVES.put( "float", "Float" );
- PRIMITIVES.put( "double", "Double" );
-
- }
-
- static public String toTypeString(TypeMirror type) {
- if(type.getKind().isPrimitive()) {
- return PRIMITIVES.get(type.toString());
- }
-
- return type.toString();
- }
-
- static public TypeElement getSuperclass(TypeElement element) {
- final TypeMirror superClass = element.getSuperclass();
- //superclass of Object is of NoType which returns some other kind
- String superclassDeclaration = "";
- if (superClass.getKind() == TypeKind.DECLARED ) {
- //F..king Ch...t Have those people used their horrible APIs even once?
- final Element superClassElement = ( ( DeclaredType ) superClass ).asElement();
- return ( TypeElement ) superClassElement;
- }
- else {
- return null;
- }
- }
-
- public static String extractClosestRealTypeAsString(TypeMirror type, Context context) {
- if ( type instanceof TypeVariable ) {
- final TypeMirror compositeUpperBound = ( ( TypeVariable ) type ).getUpperBound();
- final Types types = context.getProcessingEnvironment().getTypeUtils();
- final List<? extends TypeMirror> upperBounds = types.directSupertypes( compositeUpperBound );
- if (upperBounds.size() == 0) {
- return compositeUpperBound.toString();
- }
- else {
- //take the first one
- return extractClosestRealTypeAsString( upperBounds.get( 0 ), context );
- }
- }
- else {
- return type.toString();
- }
- }
-}
Modified: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationMetaEntity.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationMetaEntity.java 2010-01-25 18:49:02 UTC (rev 18621)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationMetaEntity.java 2010-01-26 02:58:26 UTC (rev 18622)
@@ -58,7 +58,7 @@
import org.hibernate.jpamodelgen.ImportContextImpl;
import org.hibernate.jpamodelgen.MetaAttribute;
import org.hibernate.jpamodelgen.MetaEntity;
-import org.hibernate.jpamodelgen.TypeUtils;
+import org.hibernate.jpamodelgen.util.TypeUtils;
/**
* @author Max Andersen
@@ -67,6 +67,7 @@
*/
public class AnnotationMetaEntity implements MetaEntity {
+ private static final String DEFAULT_ANNOTATION_PARAMETER_NAME = "value";
static Map<String, String> COLLECTIONS = new HashMap<String, String>();
static {
@@ -122,14 +123,14 @@
addPersistentMembers( membersFound, elementAccessType, methodsOfClass, AccessType.PROPERTY );
//process superclasses
- for ( TypeElement superclass = TypeUtils.getSuperclass( element );
+ for ( TypeElement superclass = TypeUtils.getSuperclassTypeElement( element );
superclass != null;
- superclass = TypeUtils.getSuperclass( superclass ) ) {
- if ( superclass.getAnnotation( Entity.class ) != null ) {
+ superclass = TypeUtils.getSuperclassTypeElement( superclass ) ) {
+ if ( TypeUtils.containsAnnotation( superclass, Entity.class ) ) {
break; //will be handled or has been handled already
}
- else if ( superclass.getAnnotation( MappedSuperclass.class ) != null ) {
- //FIXME use the class defalut access type
+ else if ( TypeUtils.containsAnnotation( superclass, MappedSuperclass.class ) ) {
+ //FIXME use the class default access type
context.processElement( superclass, defaultAccessTypeForHierarchy );
}
}
@@ -175,10 +176,9 @@
//FIXME is it really true if only the superclass is changed
TypeElement superClass = element;
do {
- superClass = TypeUtils.getSuperclass( superClass );
+ superClass = TypeUtils.getSuperclassTypeElement( superClass );
if ( superClass != null ) {
- if ( superClass.getAnnotation( Entity.class ) != null
- || superClass.getAnnotation( MappedSuperclass.class ) != null ) {
+ if ( TypeUtils.containsAnnotation( superClass, Entity.class, MappedSuperclass.class ) ) {
//FIXME make it work for XML
AccessType superClassAccessType = getAccessTypeForClass( superClass );
//we've reach the root entity and resolved Ids
@@ -221,8 +221,7 @@
* when forcing access type, we can only override the defaultAccessTypeForHierarchy
* if we are the entity root (identified by having @Id or @EmbeddedId
*/
- final Access accessAnn = searchedElement.getAnnotation( Access.class );
- AccessType forcedAccessType = accessAnn != null ? accessAnn.value() : null;
+ AccessType forcedAccessType = determineAnnotationSpecifiedAccessType( searchedElement );
if ( forcedAccessType != null ) {
context.logMessage( Diagnostic.Kind.OTHER, "access type " + searchedElement + ":" + forcedAccessType );
context.addAccessType( searchedElement, forcedAccessType );
@@ -239,11 +238,9 @@
for ( Object entityAnnotation : entityAnnotations ) {
AnnotationMirror annotationMirror = ( AnnotationMirror ) entityAnnotation;
- final String annotationType = annotationMirror.getAnnotationType().toString();
-
//FIXME consider XML
- if ( annotationType.equals( Id.class.getName() )
- || annotationType.equals( EmbeddedId.class.getName() ) ) {
+ if ( TypeUtils.isAnnotationMirrorOfType( annotationMirror, Id.class )
+ || TypeUtils.isAnnotationMirrorOfType( annotationMirror, EmbeddedId.class ) ) {
context.logMessage( Diagnostic.Kind.OTHER, "Found id on" + searchedElement );
final ElementKind kind = subElement.getKind();
if ( kind == ElementKind.FIELD || kind == ElementKind.METHOD ) {
@@ -279,6 +276,30 @@
return forcedAccessType;
}
+ private AccessType determineAnnotationSpecifiedAccessType(Element element) {
+ final AnnotationMirror accessAnnotationMirror = TypeUtils.getAnnotationMirror( element, Access.class );
+ AccessType forcedAccessType = null;
+ if ( accessAnnotationMirror != null ) {
+ Element accessElement = ( Element ) TypeUtils.getAnnotationValue(
+ accessAnnotationMirror,
+ DEFAULT_ANNOTATION_PARAMETER_NAME
+ );
+ if ( accessElement.getKind().equals( ElementKind.ENUM_CONSTANT ) ) {
+ if ( accessElement.getSimpleName().toString().equals( AccessType.PROPERTY.toString() ) ) {
+ forcedAccessType = AccessType.PROPERTY;
+ }
+ else if ( accessElement.getSimpleName().toString().equals( AccessType.FIELD.toString() ) ) {
+ forcedAccessType = AccessType.FIELD;
+
+ }
+ else {
+ context.logMessage( Diagnostic.Kind.ERROR, "Unexpected type for access type" );
+ }
+ }
+ }
+ return forcedAccessType;
+ }
+
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
@@ -332,13 +353,13 @@
correctAccessType = true;
}
else {
- final Access accessAnn = element.getAnnotation( Access.class );
- if ( accessAnn != null && explicitAccessType.equals( accessAnn.value() ) ) {
+ AccessType annotationAccessType = determineAnnotationSpecifiedAccessType( element );
+ if ( explicitAccessType.equals( annotationAccessType ) ) {
correctAccessType = true;
}
}
return correctAccessType
- && element.getAnnotation( Transient.class ) == null
+ && !TypeUtils.containsAnnotation( element, Transient.class )
&& !element.getModifiers().contains( Modifier.TRANSIENT )
&& !element.getModifiers().contains( Modifier.STATIC );
@@ -354,10 +375,9 @@
String fqElementName = returnedElement.getQualifiedName()
.toString(); // WARNING: .toString() is necessary here since Name equals does not compare to String
String collection = COLLECTIONS.get( fqElementName );
- final List<? extends AnnotationMirror> annotations = element.getAnnotationMirrors();
- String targetEntity = getTargetEntity( annotations );
+ String targetEntity = getTargetEntity( element.getAnnotationMirrors() );
if ( collection != null ) {
- if ( containsAnnotation( annotations, ElementCollection.class ) ) {
+ if ( TypeUtils.containsAnnotation( element, ElementCollection.class ) ) {
//FIXME I don't understand why this code is different between Elementcollection and a regular collection but it needs to take targetClass into account
TypeMirror collectionElementType = getCollectionElementType( t, fqElementName );
final TypeElement collectionElement = ( TypeElement ) context.getProcessingEnvironment()
@@ -375,13 +395,14 @@
);
}
else {
- return new AnnotationMetaCollection( parent, element, collection, getElementType( t, targetEntity ) );
+ return new AnnotationMetaCollection(
+ parent, element, collection, getElementType( t, targetEntity )
+ );
}
}
else {
//FIXME Consider XML
- if ( element.getAnnotation( Embedded.class ) != null
- || returnedElement.getAnnotation( Embeddable.class ) != null ) {
+ if ( TypeUtils.containsAnnotation( returnedElement, Embedded.class, Embeddable.class ) ) {
this.parent.context.processElement(
returnedElement,
this.parent.defaultAccessTypeForElement
@@ -424,44 +445,23 @@
}
}
- private boolean containsAnnotation(List<? extends AnnotationMirror> annotations, Class<?> annotation) {
- String annString = annotation.getName();
- for ( AnnotationMirror mirror : annotations ) {
- if ( annString.equals( mirror.getAnnotationType().toString() ) ) {
- return true;
- }
- }
- return false;
- }
-
/**
- * Returns targetEntity or null if no targetEntity is here or if equals to void
+ * @return target entity class name as string or {@code null} if no targetEntity is here or if equals to void
*/
+
private String getTargetEntity(List<? extends AnnotationMirror> annotations) {
- final String elementCollection = ElementCollection.class.getName();
for ( AnnotationMirror mirror : annotations ) {
- final String annotation = mirror.getAnnotationType().toString();
- if ( elementCollection.equals( annotation ) ) {
+ if ( TypeUtils.isAnnotationMirrorOfType( mirror, ElementCollection.class )
+ || TypeUtils.isAnnotationMirrorOfType( mirror, OneToMany.class )
+ || TypeUtils.isAnnotationMirrorOfType( mirror, ManyToMany.class )
+ || TypeUtils.isAnnotationMirrorOfType( mirror, ManyToOne.class )
+ || TypeUtils.isAnnotationMirrorOfType( mirror, OneToOne.class ) ) {
final String targetEntity = getTargetEntity( mirror );
- if (targetEntity != null) return targetEntity;
+ if ( targetEntity != null ) {
+ return targetEntity;
+ }
}
- else if ( OneToMany.class.getName().equals( annotation ) ) {
- final String targetEntity = getTargetEntity( mirror );
- if (targetEntity != null) return targetEntity;
- }
- else if ( ManyToMany.class.getName().equals( annotation ) ) {
- final String targetEntity = getTargetEntity( mirror );
- if (targetEntity != null) return targetEntity;
- }
- else if ( ManyToOne.class.getName().equals( annotation ) ) {
- final String targetEntity = getTargetEntity( mirror );
- if (targetEntity != null) return targetEntity;
- }
- else if ( OneToOne.class.getName().equals( annotation ) ) {
- final String targetEntity = getTargetEntity( mirror );
- if (targetEntity != null) return targetEntity;
- }
}
return null;
}
@@ -506,7 +506,9 @@
}
private String getElementType(DeclaredType declaredType, String targetEntity) {
- if (targetEntity != null) return targetEntity;
+ if ( targetEntity != null ) {
+ return targetEntity;
+ }
final List<? extends TypeMirror> mirrors = declaredType.getTypeArguments();
if ( mirrors.size() == 1 ) {
final TypeMirror type = mirrors.get( 0 );
@@ -518,12 +520,10 @@
else {
//for 0 or many
//0 is expected, many is not
- if ( mirrors.size() > 2) {
+ if ( mirrors.size() > 2 ) {
context.logMessage( Diagnostic.Kind.WARNING, "Unable to find the closest solid type" + declaredType );
}
return "?";
}
}
-
-
}
Copied: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/util/TypeUtils.java (from rev 18609, jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/TypeUtils.java)
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/util/TypeUtils.java (rev 0)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/util/TypeUtils.java 2010-01-26 02:58:26 UTC (rev 18622)
@@ -0,0 +1,184 @@
+// $Id$
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+* http://www.apache.org/licenses/LICENSE-2.0
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.hibernate.jpamodelgen.util;
+
+import java.lang.annotation.Annotation;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import javax.lang.model.element.AnnotationMirror;
+import javax.lang.model.element.AnnotationValue;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.ExecutableElement;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.type.DeclaredType;
+import javax.lang.model.type.TypeKind;
+import javax.lang.model.type.TypeMirror;
+import javax.lang.model.type.TypeVariable;
+import javax.lang.model.util.Types;
+
+import org.hibernate.jpamodelgen.Context;
+
+/**
+ * Utility class.
+ *
+ * @author Max Andersen
+ * @author Hardy Ferentschik
+ * @author Emmanuel Bernard
+ */
+public class TypeUtils {
+
+ private static final Map<String, String> PRIMITIVES = new HashMap<String, String>();
+
+ static {
+ PRIMITIVES.put( "char", "Character" );
+
+ PRIMITIVES.put( "byte", "Byte" );
+ PRIMITIVES.put( "short", "Short" );
+ PRIMITIVES.put( "int", "Integer" );
+ PRIMITIVES.put( "long", "Long" );
+
+ PRIMITIVES.put( "boolean", "Boolean" );
+
+ PRIMITIVES.put( "float", "Float" );
+ PRIMITIVES.put( "double", "Double" );
+
+ }
+
+ static public String toTypeString(TypeMirror type) {
+ if ( type.getKind().isPrimitive() ) {
+ return PRIMITIVES.get( type.toString() );
+ }
+ return type.toString();
+ }
+
+ static public TypeElement getSuperclassTypeElement(TypeElement element) {
+ final TypeMirror superClass = element.getSuperclass();
+ //superclass of Object is of NoType which returns some other kind
+ if ( superClass.getKind() == TypeKind.DECLARED ) {
+ //F..king Ch...t Have those people used their horrible APIs even once?
+ final Element superClassElement = ( ( DeclaredType ) superClass ).asElement();
+ return ( TypeElement ) superClassElement;
+ }
+ else {
+ return null;
+ }
+ }
+
+ public static String extractClosestRealTypeAsString(TypeMirror type, Context context) {
+ if ( type instanceof TypeVariable ) {
+ final TypeMirror compositeUpperBound = ( ( TypeVariable ) type ).getUpperBound();
+ final Types types = context.getProcessingEnvironment().getTypeUtils();
+ final List<? extends TypeMirror> upperBounds = types.directSupertypes( compositeUpperBound );
+ if ( upperBounds.size() == 0 ) {
+ return compositeUpperBound.toString();
+ }
+ else {
+ //take the first one
+ return extractClosestRealTypeAsString( upperBounds.get( 0 ), context );
+ }
+ }
+ else {
+ return type.toString();
+ }
+ }
+
+ public static boolean containsAnnotation(Element element, Class<?>... annotations) {
+ assert element != null;
+ assert annotations != null;
+
+ List<String> annotationClassNames = new ArrayList<String>();
+ for ( Class<?> clazz : annotations ) {
+ annotationClassNames.add( clazz.getName() );
+ }
+
+ List<? extends AnnotationMirror> annotationMirrors = element.getAnnotationMirrors();
+ for ( AnnotationMirror mirror : annotationMirrors ) {
+ if ( annotationClassNames.contains( mirror.getAnnotationType().toString() ) ) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Returns {@code true} if the provided annotation type is of the same type as the provided class, {@code false} otherwise.
+ * This method uses the string class names for comparison. See also {@link http://www.retep.org/2009/02/getting-class-values-from-annotations.html}.
+ *
+ * @param annotationMirror The annotation mirror
+ * @param clazz the class name to check again
+ *
+ * @return {@code true} if the provided annotation type is of the same type as the provided class, {@code false} otherwise.
+ */
+ public static boolean isAnnotationMirrorOfType(AnnotationMirror annotationMirror, Class<? extends Annotation> clazz) {
+ assert annotationMirror != null;
+ assert clazz != null;
+ String annotationClassName = annotationMirror.getAnnotationType().toString();
+ String className = clazz.getName();
+
+ return annotationClassName.equals( className );
+ }
+
+ public static boolean isTypeElementOfType(TypeElement element, Class<?> clazz) {
+ assert element != null;
+ assert clazz != null;
+ String elementClassName = element.getQualifiedName().toString();
+ String className = clazz.getName();
+
+ return elementClassName.equals( className );
+ }
+
+ /**
+ * Returns the annotation mirror for the specified annotation class from the {@code Element}.
+ *
+ * @param element the element to check for the hosted annotation
+ * @param clazz the annotation class to check for
+ *
+ * @return the annotation mirror for the specified annotation class from the {@code Element} or {@code null} in case
+ * the {@code TypeElement} does not host the specified annotation.
+ */
+ public static AnnotationMirror getAnnotationMirror(Element element, Class<? extends Annotation> clazz) {
+ assert element != null;
+ assert clazz != null;
+
+ AnnotationMirror mirror = null;
+ for ( AnnotationMirror am : element.getAnnotationMirrors() ) {
+ if ( isAnnotationMirrorOfType( am, clazz ) ) {
+ mirror = am;
+ break;
+ }
+ }
+ return mirror;
+ }
+
+ public static Object getAnnotationValue(AnnotationMirror annotationMirror, String parameterValue) {
+ assert annotationMirror != null;
+ assert parameterValue != null;
+
+ Object returnValue = null;
+ for ( Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : annotationMirror.getElementValues()
+ .entrySet() ) {
+ if ( parameterValue.equals( entry.getKey().getSimpleName().toString() ) ) {
+ returnValue = entry.getValue().getValue();
+ break;
+ }
+ }
+ return returnValue;
+ }
+}
Property changes on: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/util/TypeUtils.java
___________________________________________________________________
Name: svn:keywords
+ Id
Modified: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaEntity.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaEntity.java 2010-01-25 18:49:02 UTC (rev 18621)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaEntity.java 2010-01-26 02:58:26 UTC (rev 18622)
@@ -31,7 +31,7 @@
import org.hibernate.jpamodelgen.ImportContextImpl;
import org.hibernate.jpamodelgen.MetaEntity;
import org.hibernate.jpamodelgen.ImportContext;
-import org.hibernate.jpamodelgen.TypeUtils;
+import org.hibernate.jpamodelgen.util.TypeUtils;
import org.hibernate.jpamodelgen.xml.jaxb.Attributes;
import org.hibernate.jpamodelgen.xml.jaxb.Basic;
import org.hibernate.jpamodelgen.xml.jaxb.ElementCollection;
14 years, 11 months
Hibernate SVN: r18621 - core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/cacheable/annotation.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2010-01-25 13:49:02 -0500 (Mon, 25 Jan 2010)
New Revision: 18621
Modified:
core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/cacheable/annotation/ConfigurationTest.java
Log:
HHH-4659 - Add support for standard declarative cache (@Cacheable)
Modified: core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/cacheable/annotation/ConfigurationTest.java
===================================================================
--- core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/cacheable/annotation/ConfigurationTest.java 2010-01-25 17:57:07 UTC (rev 18620)
+++ core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/cacheable/annotation/ConfigurationTest.java 2010-01-25 18:49:02 UTC (rev 18621)
@@ -26,6 +26,9 @@
import java.util.Properties;
import javax.persistence.SharedCacheMode;
+import org.hibernate.cache.access.AccessType;
+import org.hibernate.cache.impl.NoCachingRegionFactory;
+import org.hibernate.cfg.Environment;
import org.hibernate.ejb.AvailableSettings;
import org.hibernate.ejb.Ejb3Configuration;
import org.hibernate.junit.UnitTestCase;
@@ -109,6 +112,7 @@
private Ejb3Configuration buildConfiguration(SharedCacheMode mode) {
Properties properties = new Properties();
properties.put( AvailableSettings.SHARED_CACHE_MODE, mode );
+ properties.put( Environment.CACHE_REGION_FACTORY, CustomRegionFactory.class.getName() );
Ejb3Configuration config = new Ejb3Configuration();
config.setProperties( properties );
config.addAnnotatedClass( ExplicitlyCacheableEntity.class );
@@ -117,4 +121,15 @@
config.buildMappings();
return config;
}
+
+ public static class CustomRegionFactory extends NoCachingRegionFactory {
+ public CustomRegionFactory(Properties properties) {
+ super( properties );
+ }
+
+ @Override
+ public AccessType getDefaultAccessType() {
+ return AccessType.READ_WRITE;
+ }
+ }
}
14 years, 11 months
Hibernate SVN: r18620 - in core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities: e2 and 1 other directories.
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2010-01-25 12:57:07 -0500 (Mon, 25 Jan 2010)
New Revision: 18620
Added:
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e2/
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e2/b/
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e2/b/Dependent.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e2/b/DependentId.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e2/b/Employee.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e2/b/EmployeeId.java
Log:
HHH-4529 add new test
Added: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e2/b/Dependent.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e2/b/Dependent.java (rev 0)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e2/b/Dependent.java 2010-01-25 17:57:07 UTC (rev 18620)
@@ -0,0 +1,25 @@
+package org.hibernate.test.annotations.derivedidentities.e2.b;
+
+import javax.persistence.EmbeddedId;
+import javax.persistence.Entity;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinColumns;
+import javax.persistence.ManyToOne;
+import javax.persistence.MapsId;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Dependent {
+ @EmbeddedId
+ DependentId id;
+
+ @MapsId("empPK")
+ @JoinColumns({
+ @JoinColumn(name = "FK1", referencedColumnName = "firstName"),
+ @JoinColumn(name = "FK2", referencedColumnName = "lastName")
+ })
+ @ManyToOne
+ Employee emp;
+}
Added: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e2/b/DependentId.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e2/b/DependentId.java (rev 0)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e2/b/DependentId.java 2010-01-25 17:57:07 UTC (rev 18620)
@@ -0,0 +1,13 @@
+package org.hibernate.test.annotations.derivedidentities.e2.b;
+
+import java.io.Serializable;
+import javax.persistence.Embeddable;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Embeddable
+public class DependentId implements Serializable {
+ String name;
+ EmployeeId empPK;
+}
\ No newline at end of file
Added: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e2/b/Employee.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e2/b/Employee.java (rev 0)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e2/b/Employee.java 2010-01-25 17:57:07 UTC (rev 18620)
@@ -0,0 +1,17 @@
+package org.hibernate.test.annotations.derivedidentities.e2.b;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.IdClass;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+(a)IdClass(EmployeeId.class)
+public class Employee {
+ @Id
+ String firstName;
+ @Id
+ String lastName;
+}
\ No newline at end of file
Added: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e2/b/EmployeeId.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e2/b/EmployeeId.java (rev 0)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e2/b/EmployeeId.java 2010-01-25 17:57:07 UTC (rev 18620)
@@ -0,0 +1,9 @@
+package org.hibernate.test.annotations.derivedidentities.e2.b;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class EmployeeId {
+ String firstName;
+ String lastName;
+}
\ No newline at end of file
14 years, 11 months
Hibernate SVN: r18619 - in core/trunk/annotations/src: main/java/org/hibernate/cfg/annotations and 4 other directories.
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2010-01-25 12:19:05 -0500 (Mon, 25 Jan 2010)
New Revision: 18619
Added:
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/c/
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/c/Dependent.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/c/DerivedIdentitySimpleParentEmbeddedDepTest.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/c/Employee.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e4/a/
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e4/a/DerivedIdentitySimpleParentSimpleDepTest.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e4/a/FinancialHistory.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e4/a/MedicalHistory.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e4/a/Person.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e4/a/Simple.java
Modified:
core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationBinder.java
core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/EntityBinder.java
core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/PropertyBinder.java
core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/Version.java
Log:
HHH-4529 support for derived entity id as a XToOne pointing to the master entity
HHH-4840 support for Core style embedded id (after all these years :) )
Modified: core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationBinder.java
===================================================================
--- core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationBinder.java 2010-01-25 16:23:59 UTC (rev 18618)
+++ core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationBinder.java 2010-01-25 17:19:05 UTC (rev 18619)
@@ -625,10 +625,10 @@
HashMap<String, IdGenerator> classGenerators = buildLocalGenerators( clazzToProcess, mappings );
// check properties
- List<PropertyData> elements =
- getElementsToProcess(
- persistentClass, clazzToProcess, inheritanceStatePerClass, entityBinder, mappings
- );
+ final ElementsToProcess elementsToProcess = getElementsToProcess(
+ persistentClass, clazzToProcess, inheritanceStatePerClass, entityBinder, mappings
+ );
+
final boolean subclassAndSingleTableStrategy = inheritanceState.getType() == InheritanceType.SINGLE_TABLE
&& inheritanceState.hasParents();
//process idclass if any
@@ -674,7 +674,9 @@
isComponent,
propertyAccessor, entityBinder,
true,
- false, mappings, inheritanceStatePerClass
+ false,
+ mappings,
+ inheritanceStatePerClass
);
inferredData = new PropertyPreloadedData(
propertyAccessor, "_identifierMapper", compositeClass
@@ -683,9 +685,11 @@
propertyHolder,
inferredData,
baseInferredData,
- propertyAccessor, false,
+ propertyAccessor,
+ false,
entityBinder,
- true, true,
+ true,
+ true,
false, mappings, inheritanceStatePerClass
);
entityBinder.setIgnoreIdAnnotations( ignoreIdAnnotations );
@@ -720,8 +724,11 @@
idProperties.add( ( (Property) properties.next() ).getName() );
}
}
+ else {
+ entityBinder.setWrapIdsInEmbeddedComponents( elementsToProcess.getIdPropertyCount() > 1 );
+ }
Set<String> missingIdProperties = new HashSet<String>( idProperties );
- for (PropertyData propertyAnnotatedElement : elements) {
+ for (PropertyData propertyAnnotatedElement : elementsToProcess.getElements() ) {
String propertyName = propertyAnnotatedElement.getPropertyName();
if ( !idProperties.contains( propertyName ) ) {
processElementAnnotations(
@@ -979,7 +986,7 @@
* Get the annotated elements, guessing the access type from @Id or @EmbeddedId presence.
* Change EntityBinder by side effect
*/
- private static List<PropertyData> getElementsToProcess(
+ private static ElementsToProcess getElementsToProcess(
PersistentClass persistentClass, XClass clazzToProcess,
Map<XClass, InheritanceState> inheritanceStatePerClass,
EntityBinder entityBinder, ExtendedMappings mappings
@@ -996,23 +1003,41 @@
List<PropertyData> elements = new ArrayList<PropertyData>();
int deep = classesToProcess.size();
- boolean hasIdentifier = false;
+ int idPropertyCount = 0;
for ( int index = 0; index < deep; index++ ) {
- PropertyContainer properyContainer = new PropertyContainer( classesToProcess.get( index ), clazzToProcess );
- boolean currentHasIdentifier = addElementsOfClass( elements, accessType, properyContainer, mappings );
- hasIdentifier = hasIdentifier || currentHasIdentifier;
+ PropertyContainer propertyContainer = new PropertyContainer( classesToProcess.get( index ), clazzToProcess );
+ int currentIdPropertyCount = addElementsOfClass( elements, accessType, propertyContainer, mappings );
+ idPropertyCount += currentIdPropertyCount;
}
entityBinder.setPropertyAccessType( accessType );
- if ( !hasIdentifier && !inheritanceState.hasParents() ) {
+ if ( idPropertyCount == 0 && !inheritanceState.hasParents() ) {
throw new AnnotationException( "No identifier specified for entity: " + clazzToProcess.getName() );
}
- return elements;
+ return new ElementsToProcess( elements, idPropertyCount);
}
+ private static final class ElementsToProcess {
+ private final List<PropertyData> properties;
+ private final int idPropertyCount;
+
+ public List<PropertyData> getElements() {
+ return properties;
+ }
+
+ public int getIdPropertyCount() {
+ return idPropertyCount;
+ }
+
+ private ElementsToProcess(List<PropertyData> properties, int idPropertyCount) {
+ this.properties = properties;
+ this.idPropertyCount = idPropertyCount;
+ }
+ }
+
private static AccessType determineDefaultAccessType(XClass annotatedClass, Map<XClass, InheritanceState> inheritanceStatePerClass) {
XClass xclass = annotatedClass;
while ( xclass != null && !Object.class.getName().equals( xclass.getName() ) ) {
@@ -1207,13 +1232,13 @@
* strategy is used
* @param propertyContainer Metadata about a class and its properties
* @param mappings Mapping meta data
- * @return {@code true} in case an id property was found while iterating the elements of {@code annoatedClass} using
+ * @return the number of id properties found while iterating the elements of {@code annoatedClass} using
* the determined access strategy, {@code false} otherwise.
*/
- private static boolean addElementsOfClass(
+ private static int addElementsOfClass(
List<PropertyData> elements, AccessType defaultAccessType, PropertyContainer propertyContainer, ExtendedMappings mappings
) {
- boolean hasIdentifier = false;
+ int idPropertyCounter = 0;
AccessType accessType = defaultAccessType;
if ( propertyContainer.hasExplicitAccessStrategy() ) {
@@ -1223,21 +1248,21 @@
propertyContainer.assertTypesAreResolvable( accessType );
Collection<XProperty> properties = propertyContainer.getProperties( accessType );
for ( XProperty p : properties ) {
- final boolean currentHasIdentifier = addProperty(
+ final int currentIdPropertyCounter = addProperty(
propertyContainer, p, elements, accessType.getType(), mappings
);
- hasIdentifier = hasIdentifier || currentHasIdentifier;
+ idPropertyCounter += currentIdPropertyCounter;
}
- return hasIdentifier;
+ return idPropertyCounter;
}
- private static boolean addProperty(
+ private static int addProperty(
PropertyContainer propertyContainer, XProperty property, List<PropertyData> annElts,
String propertyAccessor, ExtendedMappings mappings
) {
final XClass declaringClass = propertyContainer.getDeclaringClass();
final XClass entity = propertyContainer.getEntityAtStake();
- boolean hasIdentifier;
+ int idPropertyCounter = 0;
PropertyData propertyAnnotatedElement = new PropertyInferredData(
declaringClass, property, propertyAccessor,
mappings.getReflectionManager() );
@@ -1249,17 +1274,16 @@
final XAnnotatedElement element = propertyAnnotatedElement.getProperty();
if ( element.isAnnotationPresent( Id.class ) || element.isAnnotationPresent( EmbeddedId.class ) ) {
annElts.add( 0, propertyAnnotatedElement );
- hasIdentifier = true;
+ idPropertyCounter++;
}
else {
annElts.add( propertyAnnotatedElement );
- hasIdentifier = false;
}
if ( element.isAnnotationPresent( MapsId.class ) ) {
mappings.addPropertyAnnotatedWithMapsId( entity, propertyAnnotatedElement );
}
- return hasIdentifier;
+ return idPropertyCounter;
}
/*
@@ -1361,9 +1385,28 @@
final XClass returnedClass = inferredData.getClassOrElement();
+ //prepare PropertyBinder
+ PropertyBinder propertyBinder = new PropertyBinder();
+ propertyBinder.setName( inferredData.getPropertyName() );
+ propertyBinder.setReturnedClassName( inferredData.getTypeName() );
+ propertyBinder.setAccessType( inferredData.getDefaultAccess() );
+ propertyBinder.setHolder( propertyHolder );
+ propertyBinder.setProperty( property );
+ propertyBinder.setReturnedClass( inferredData.getPropertyClass() );
+ propertyBinder.setMappings( mappings );
+ if ( isIdentifierMapper ) {
+ propertyBinder.setInsertable( false );
+ propertyBinder.setUpdatable( false );
+ }
+ propertyBinder.setDeclaringClass( inferredData.getDeclaringClass() );
+ propertyBinder.setEntityBinder( entityBinder );
+ propertyBinder.setInheritanceStatePerClass(inheritanceStatePerClass);
+
boolean isId = !entityBinder.isIgnoreIdAnnotations() &&
( property.isAnnotationPresent( Id.class )
|| property.isAnnotationPresent( EmbeddedId.class ) );
+ propertyBinder.setId( isId );
+
if ( property.isAnnotationPresent( Version.class ) ) {
if ( isIdentifierMapper ) {
throw new AnnotationException(
@@ -1384,19 +1427,14 @@
}
log.trace( "{} is a version property", inferredData.getPropertyName() );
RootClass rootClass = (RootClass) propertyHolder.getPersistentClass();
- PropertyBinder propBinder = new PropertyBinder();
- propBinder.setName( inferredData.getPropertyName() );
- propBinder.setReturnedClassName( inferredData.getTypeName() );
- propBinder.setLazy( false );
- propBinder.setAccessType( inferredData.getDefaultAccess() );
- propBinder.setColumns( columns );
- propBinder.setHolder( propertyHolder ); //PropertyHolderBuilder.buildPropertyHolder(rootClass)
- propBinder.setProperty( property );
- propBinder.setReturnedClass( inferredData.getPropertyClass() );
- propBinder.setMappings( mappings );
- propBinder.setDeclaringClass( inferredData.getDeclaringClass() );
- Property prop = propBinder.makePropertyValueAndBind();
- propBinder.getSimpleValueBinder().setVersion(true);
+// PropertyBinder propBinder = new PropertyBinder();
+// propBinder.setName( inferredData.getPropertyName() );
+// propBinder.setReturnedClassName( inferredData.getTypeName() );
+// propBinder.setLazy( false );
+// propBinder.setAccessType( inferredData.getDefaultAccess() );
+ propertyBinder.setColumns( columns );
+ Property prop = propertyBinder.makePropertyValueAndBind();
+ propertyBinder.getSimpleValueBinder().setVersion(true);
rootClass.setVersion( prop );
//If version is on a mapped superclass, update the mapping
@@ -1451,7 +1489,8 @@
ignoreNotFound, onDeleteCascade,
ToOneBinder.getTargetEntity( inferredData, mappings ),
propertyHolder,
- inferredData, false, isIdentifierMapper, inSecondPass, mappings
+ inferredData, false, isIdentifierMapper,
+ inSecondPass, propertyBinder, mappings
);
}
else if ( property.isAnnotationPresent( OneToOne.class ) ) {
@@ -1489,7 +1528,13 @@
ignoreNotFound, onDeleteCascade,
ToOneBinder.getTargetEntity( inferredData, mappings ),
propertyHolder,
- inferredData, ann.mappedBy(), trueOneToOne, isIdentifierMapper, inSecondPass, mappings
+ inferredData,
+ ann.mappedBy(),
+ trueOneToOne,
+ isIdentifierMapper,
+ inSecondPass,
+ propertyBinder,
+ mappings
);
}
else if ( property.isAnnotationPresent( org.hibernate.annotations.Any.class ) ) {
@@ -1793,7 +1838,7 @@
isComponent = property.isAnnotationPresent( Embedded.class )
|| property.isAnnotationPresent( EmbeddedId.class )
|| returnedClass.isAnnotationPresent( Embeddable.class );
- PropertyBinder propertyBinder;
+
if ( isComponent ) {
AccessType propertyAccessor = entityBinder.getPropertyAccessor( property );
propertyBinder = bindComponent(
@@ -1835,23 +1880,12 @@
mappings );
}
- propertyBinder = new PropertyBinder();
- propertyBinder.setName( inferredData.getPropertyName() );
- propertyBinder.setReturnedClassName( inferredData.getTypeName() );
propertyBinder.setLazy( lazy );
- propertyBinder.setAccessType( inferredData.getDefaultAccess() );
propertyBinder.setColumns( columns );
- propertyBinder.setHolder( propertyHolder );
- propertyBinder.setProperty( property );
- propertyBinder.setReturnedClass( inferredData.getPropertyClass() );
- propertyBinder.setMappings( mappings );
- if ( isIdentifierMapper ) {
- propertyBinder.setInsertable( false );
- propertyBinder.setUpdatable( false );
- }
- propertyBinder.setDeclaringClass( inferredData.getDeclaringClass() );
- propertyBinder.setId(isId);
- propertyBinder.setInheritanceStatePerClass(inheritanceStatePerClass);
+// if ( isIdentifierMapper ) {
+// propertyBinder.setInsertable( false );
+// propertyBinder.setUpdatable( false );
+// }
propertyBinder.makePropertyValueAndBind();
}
if (isId) {
@@ -2105,6 +2139,7 @@
binder.setEmbedded( isComponentEmbedded );
binder.setHolder( propertyHolder );
binder.setId( isId );
+ binder.setEntityBinder( entityBinder );
binder.setInheritanceStatePerClass( inheritanceStatePerClass );
binder.setMappings( mappings );
binder.makePropertyAndBind();
@@ -2136,17 +2171,7 @@
* Because it's a value type, there is no bidirectional association, hence second pass
* ordering does not matter
*/
- Component comp = new Component( propertyHolder.getPersistentClass() );
- comp.setEmbedded( isComponentEmbedded );
- //yuk
- comp.setTable( propertyHolder.getTable() );
- if ( !isIdentifierMapper ) {
- comp.setComponentClassName( inferredData.getClassOrElementName() );
- }
- else {
- comp.setComponentClassName( comp.getOwner().getClassName() );
- }
- comp.setNodeName( inferredData.getPropertyName() );
+ Component comp = createComponent( propertyHolder, inferredData, isComponentEmbedded, isIdentifierMapper );
String subpath = BinderHelper.getPath( propertyHolder, inferredData );
log.trace( "Binding component with path: {}", subpath );
PropertyHolder subHolder = PropertyHolderBuilder.buildPropertyHolder(
@@ -2202,6 +2227,22 @@
return comp;
}
+ public static Component createComponent(PropertyHolder propertyHolder, PropertyData inferredData, boolean isComponentEmbedded, boolean isIdentifierMapper) {
+ Component comp = new Component( propertyHolder.getPersistentClass() );
+ comp.setEmbedded( isComponentEmbedded );
+ //yuk
+ comp.setTable( propertyHolder.getTable() );
+ //FIXME shouldn't identifier mapper use getClassOrElementName? Need to be checked.
+ if ( isIdentifierMapper || ( isComponentEmbedded && inferredData.getPropertyName() == null ) ) {
+ comp.setComponentClassName( comp.getOwner().getClassName() );
+ }
+ else {
+ comp.setComponentClassName( inferredData.getClassOrElementName() );
+ }
+ comp.setNodeName( inferredData.getPropertyName() );
+ return comp;
+ }
+
private static void bindId(
String generatorType, String generatorName,
PropertyData inferredData, Ejb3Column[] columns, PropertyHolder propertyHolder,
@@ -2345,7 +2386,9 @@
String cascadeStrategy, Ejb3JoinColumn[] columns, boolean optional,
boolean ignoreNotFound, boolean cascadeOnDelete,
XClass targetEntity, PropertyHolder propertyHolder,
- PropertyData inferredData, boolean unique, boolean isIdentifierMapper, boolean inSecondPass,
+ PropertyData inferredData, boolean unique,
+ boolean isIdentifierMapper, boolean inSecondPass,
+ PropertyBinder propertyBinder,
ExtendedMappings mappings
) {
//All FK columns should be in the same table
@@ -2399,24 +2442,26 @@
);
}
Ejb3Column.checkPropertyConsistency( columns, propertyHolder.getEntityName() + propertyName );
- PropertyBinder binder = new PropertyBinder();
- binder.setName( propertyName );
- binder.setValue( value );
+ //PropertyBinder binder = new PropertyBinder();
+ propertyBinder.setName( propertyName );
+ propertyBinder.setValue( value );
//binder.setCascade(cascadeStrategy);
if ( isIdentifierMapper ) {
- binder.setInsertable( false );
- binder.setUpdatable( false );
+ propertyBinder.setInsertable( false );
+ propertyBinder.setUpdatable( false );
}
else {
- binder.setInsertable( columns[0].isInsertable() );
- binder.setUpdatable( columns[0].isUpdatable() );
+ propertyBinder.setInsertable( columns[0].isInsertable() );
+ propertyBinder.setUpdatable( columns[0].isUpdatable() );
}
- binder.setAccessType( inferredData.getDefaultAccess() );
- binder.setCascade( cascadeStrategy );
- binder.setProperty( property );
- Property prop = binder.makeProperty();
+ propertyBinder.setColumns( columns );
+ propertyBinder.setAccessType( inferredData.getDefaultAccess() );
+ propertyBinder.setCascade( cascadeStrategy );
+ propertyBinder.setProperty( property );
+ propertyBinder.setXToMany( true );
+ Property prop = propertyBinder.makePropertyAndBind();
//composite FK columns are in the same table so its OK
- propertyHolder.addProperty( prop, columns, inferredData.getDeclaringClass() );
+ //propertyHolder.addProperty( prop, columns, inferredData.getDeclaringClass() );
}
protected static void defineFetchingStrategy(ToOne toOne, XProperty property) {
@@ -2476,7 +2521,10 @@
PropertyHolder propertyHolder,
PropertyData inferredData, String mappedBy,
boolean trueOneToOne,
- boolean isIdentifierMapper, boolean inSecondPass, ExtendedMappings mappings
+ boolean isIdentifierMapper,
+ boolean inSecondPass,
+ PropertyBinder propertyBinder,
+ ExtendedMappings mappings
) {
//column.getTable() => persistentClass.getTable()
final String propertyName = inferredData.getPropertyName();
@@ -2535,7 +2583,8 @@
bindManyToOne(
cascadeStrategy, joinColumns, optional, ignoreNotFound, cascadeOnDelete,
targetEntity,
- propertyHolder, inferredData, true, isIdentifierMapper, inSecondPass, mappings
+ propertyHolder, inferredData, true, isIdentifierMapper, inSecondPass,
+ propertyBinder, mappings
);
}
}
Modified: core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/EntityBinder.java
===================================================================
--- core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/EntityBinder.java 2010-01-25 16:23:59 UTC (rev 18618)
+++ core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/EntityBinder.java 2010-01-25 17:19:05 UTC (rev 18619)
@@ -119,7 +119,12 @@
private boolean ignoreIdAnnotations;
private boolean cacheLazyProperty;
private AccessType propertyAccessType = AccessType.DEFAULT;
+ private boolean wrapIdsInEmbeddedComponents;
+ public boolean wrapIdsInEmbeddedComponents() {
+ return wrapIdsInEmbeddedComponents;
+ }
+
/**
* Use as a fake one for Collection of elements
*/
@@ -413,6 +418,11 @@
}
}
+ public void setWrapIdsInEmbeddedComponents(boolean wrapIdsInEmbeddedComponents) {
+ this.wrapIdsInEmbeddedComponents = wrapIdsInEmbeddedComponents;
+ }
+
+
private static class EntityTableObjectNameSource implements ObjectNameSource {
private final String explicitName;
private final String logicalName;
Modified: core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/PropertyBinder.java
===================================================================
--- core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/PropertyBinder.java 2010-01-25 16:23:59 UTC (rev 18618)
+++ core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/PropertyBinder.java 2010-01-25 17:19:05 UTC (rev 18619)
@@ -40,11 +40,14 @@
import org.hibernate.annotations.common.reflection.XClass;
import org.hibernate.annotations.common.reflection.XProperty;
import org.hibernate.cfg.AccessType;
+import org.hibernate.cfg.AnnotationBinder;
import org.hibernate.cfg.BinderHelper;
import org.hibernate.cfg.Ejb3Column;
import org.hibernate.cfg.ExtendedMappings;
import org.hibernate.cfg.InheritanceState;
import org.hibernate.cfg.PropertyHolder;
+import org.hibernate.cfg.PropertyPreloadedData;
+import org.hibernate.mapping.Component;
import org.hibernate.mapping.KeyValue;
import org.hibernate.mapping.Property;
import org.hibernate.mapping.PropertyGeneration;
@@ -73,15 +76,21 @@
private XClass declaringClass;
private boolean declaringClassSet;
private boolean embedded;
+ private EntityBinder entityBinder;
+ private boolean isXToMany;
public void setEmbedded(boolean embedded) {
this.embedded = embedded;
}
+ public void setEntityBinder(EntityBinder entityBinder) {
+ this.entityBinder = entityBinder;
+ }
+
/*
- * property can be null
- * prefer propertyName to property.getName() since some are overloaded
- */
+ * property can be null
+ * prefer propertyName to property.getName() since some are overloaded
+ */
private XProperty property;
private XClass returnedClass;
private boolean isId;
@@ -185,27 +194,45 @@
return bind( makePropertyAndValue() );
}
+ public void setXToMany(boolean xToMany) {
+ this.isXToMany = xToMany;
+ }
+
private Property bind(Property prop) {
if (isId) {
final RootClass rootClass = ( RootClass ) holder.getPersistentClass();
- rootClass.setIdentifier( ( KeyValue ) getValue() );
-
- if (embedded) {
- rootClass.setEmbeddedIdentifier( true );
+ //if an xToMany, it as to be wrapped today.
+ //FIXME this pose a problem as the PK is the class instead of the associated class which is not really compliant with the spec
+ if ( isXToMany || entityBinder.wrapIdsInEmbeddedComponents() ) {
+ Component identifier = (Component) rootClass.getIdentifier();
+ if (identifier == null) {
+ identifier = AnnotationBinder.createComponent( holder, new PropertyPreloadedData(null, null, null), true, false );
+ rootClass.setIdentifier( identifier );
+ identifier.setNullValue( "undefined" );
+ rootClass.setEmbeddedIdentifier( true );
+ }
+ //FIXME is it good enough?
+ identifier.addProperty( prop );
}
else {
- rootClass.setIdentifierProperty( prop );
- final org.hibernate.mapping.MappedSuperclass superclass = BinderHelper.getMappedSuperclassOrNull(
- declaringClass,
- inheritanceStatePerClass,
- mappings
- );
- if (superclass != null) {
- superclass.setDeclaredIdentifierProperty(prop);
+ rootClass.setIdentifier( ( KeyValue ) getValue() );
+ if (embedded) {
+ rootClass.setEmbeddedIdentifier( true );
}
else {
- //we know the property is on the actual entity
- rootClass.setDeclaredIdentifierProperty( prop );
+ rootClass.setIdentifierProperty( prop );
+ final org.hibernate.mapping.MappedSuperclass superclass = BinderHelper.getMappedSuperclassOrNull(
+ declaringClass,
+ inheritanceStatePerClass,
+ mappings
+ );
+ if (superclass != null) {
+ superclass.setDeclaredIdentifierProperty(prop);
+ }
+ else {
+ //we know the property is on the actual entity
+ rootClass.setDeclaredIdentifierProperty( prop );
+ }
}
}
}
Modified: core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/Version.java
===================================================================
--- core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/Version.java 2010-01-25 16:23:59 UTC (rev 18618)
+++ core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/Version.java 2010-01-25 17:19:05 UTC (rev 18619)
@@ -1,4 +1,4 @@
-// $Id:$
+// $Id$
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
@@ -24,6 +24,8 @@
*/
package org.hibernate.cfg.annotations;
+import java.util.Date;
+
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -34,7 +36,7 @@
private static Logger log = LoggerFactory.getLogger( Version.class );
public static String getVersionString() {
- return "[WORKING]";
+ return "[WORKING]-1";
}
static {
Added: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/c/Dependent.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/c/Dependent.java (rev 0)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/c/Dependent.java 2010-01-25 17:19:05 UTC (rev 18619)
@@ -0,0 +1,25 @@
+package org.hibernate.test.annotations.derivedidentities.e1.c;
+
+import java.io.Serializable;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Dependent implements Serializable {
+
+ @Id
+ String name;
+
+
+ @Id
+ //@JoinColumn(name = "FK")
+ // id attribute mapped by join column default
+ @ManyToOne
+ Employee emp;
+
+}
Added: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/c/DerivedIdentitySimpleParentEmbeddedDepTest.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/c/DerivedIdentitySimpleParentEmbeddedDepTest.java (rev 0)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/c/DerivedIdentitySimpleParentEmbeddedDepTest.java 2010-01-25 17:19:05 UTC (rev 18619)
@@ -0,0 +1,46 @@
+package org.hibernate.test.annotations.derivedidentities.e1.c;
+
+import org.hibernate.Session;
+import org.hibernate.test.annotations.TestCase;
+import org.hibernate.test.util.SchemaUtil;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class DerivedIdentitySimpleParentEmbeddedDepTest extends TestCase {
+
+ public void testManyToOne() throws Exception {
+ assertTrue( SchemaUtil.isColumnPresent( "Dependent", "emp_empId", getCfg() ) );
+ assertTrue( ! SchemaUtil.isColumnPresent( "Dependent", "empPK", getCfg() ) );
+ Employee e = new Employee();
+ e.empId = 1;
+ e.empName = "Emmanuel";
+ Session s = openSession( );
+ s.getTransaction().begin();
+ s.persist( e );
+ Dependent d = new Dependent();
+ d.emp = e;
+ d.name = "Doggy";
+ s.persist( d );
+ s.flush();
+ s.clear();
+ d = getDerivedClassById( e, s, Dependent.class, d.name );
+ assertEquals( e.empId, d.emp.empId );
+ s.getTransaction().rollback();
+ s.close();
+ }
+
+ private <T> T getDerivedClassById(Employee e, Session s, Class<T> clazz, String name) {
+ return ( T )
+ s.createQuery( "from " + clazz.getName() + " d where d.name = :name and d.emp.empId = :empId")
+ .setParameter( "empId", e.empId ).setParameter( "name", name ).uniqueResult();
+ }
+
+ @Override
+ protected Class<?>[] getAnnotatedClasses() {
+ return new Class<?>[] {
+ Dependent.class,
+ Employee.class
+ };
+ }
+}
Added: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/c/Employee.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/c/Employee.java (rev 0)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/c/Employee.java 2010-01-25 17:19:05 UTC (rev 18619)
@@ -0,0 +1,14 @@
+package org.hibernate.test.annotations.derivedidentities.e1.c;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Employee {
+ @Id
+ long empId;
+ String empName;
+}
Copied: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e4/a/DerivedIdentitySimpleParentSimpleDepTest.java (from rev 18592, core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e4/b/DerivedIdentitySimpleParentSimpleDepTest.java)
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e4/a/DerivedIdentitySimpleParentSimpleDepTest.java (rev 0)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e4/a/DerivedIdentitySimpleParentSimpleDepTest.java 2010-01-25 17:19:05 UTC (rev 18619)
@@ -0,0 +1,78 @@
+package org.hibernate.test.annotations.derivedidentities.e4.a;
+
+import java.util.Date;
+
+import org.hibernate.Session;
+import org.hibernate.test.annotations.TestCase;
+import org.hibernate.test.util.SchemaUtil;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class DerivedIdentitySimpleParentSimpleDepTest extends TestCase {
+
+ public void testOneToOneExplicitJoinColumn() throws Exception {
+ assertTrue( SchemaUtil.isColumnPresent( "MedicalHistory", "FK", getCfg() ) );
+ assertTrue( ! SchemaUtil.isColumnPresent( "MedicalHistory", "id", getCfg() ) );
+ Person e = new Person();
+ e.ssn = "aaa";
+ Session s = openSession( );
+ s.getTransaction().begin();
+ s.persist( e );
+ MedicalHistory d = new MedicalHistory();
+ d.patient = e;
+ s.persist( d );
+ s.flush();
+ s.clear();
+ final Class<MedicalHistory> clazz = MedicalHistory.class;
+ d = getDerivedClassById( e, s, clazz );
+ assertEquals( e.ssn, d.patient.ssn );
+ d.lastupdate = new Date();
+ s.flush();
+ s.clear();
+ d = getDerivedClassById( e, s, clazz );
+ assertNotNull( d.lastupdate );
+ s.getTransaction().rollback();
+ s.close();
+ }
+
+ private <T> T getDerivedClassById(Person e, Session s, Class<T> clazz) {
+ return ( T )
+ s.createQuery( "from " + clazz.getName() + " mh where mh.patient.ssn = :ssn")
+ .setParameter( "ssn", e.ssn ).uniqueResult();
+ }
+
+ public void testManyToOneExplicitJoinColumn() throws Exception {
+ assertTrue( SchemaUtil.isColumnPresent( "FinancialHistory", "patient_ssn", getCfg() ) );
+ assertTrue( ! SchemaUtil.isColumnPresent( "FinancialHistory", "id", getCfg() ) );
+ Person e = new Person();
+ e.ssn = "aaa";
+ Session s = openSession( );
+ s.getTransaction().begin();
+ s.persist( e );
+ FinancialHistory d = new FinancialHistory();
+ d.patient = e;
+ s.persist( d );
+ s.flush();
+ s.clear();
+ d = getDerivedClassById(e, s, FinancialHistory.class);
+ assertEquals( e.ssn, d.patient.ssn );
+ d.lastupdate = new Date();
+ s.flush();
+ s.clear();
+ d = getDerivedClassById(e, s, FinancialHistory.class);
+ assertNotNull( d.lastupdate );
+ s.getTransaction().rollback();
+ s.close();
+ }
+
+ @Override
+ protected Class<?>[] getAnnotatedClasses() {
+ return new Class<?>[] {
+ MedicalHistory.class,
+ Simple.class,
+ Person.class,
+ FinancialHistory.class
+ };
+ }
+}
\ No newline at end of file
Copied: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e4/a/FinancialHistory.java (from rev 18592, core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e4/b/FinancialHistory.java)
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e4/a/FinancialHistory.java (rev 0)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e4/a/FinancialHistory.java 2010-01-25 17:19:05 UTC (rev 18619)
@@ -0,0 +1,28 @@
+package org.hibernate.test.annotations.derivedidentities.e4.a;
+
+import java.io.Serializable;
+import java.util.Date;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+import javax.persistence.MapsId;
+import javax.persistence.Temporal;
+import javax.persistence.TemporalType;
+
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class FinancialHistory implements Serializable {
+
+ @Temporal(TemporalType.DATE)
+ Date lastupdate;
+
+ @Id
+ //@JoinColumn(name = "FK")
+ @ManyToOne
+ Person patient;
+
+}
\ No newline at end of file
Copied: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e4/a/MedicalHistory.java (from rev 18592, core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e4/b/MedicalHistory.java)
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e4/a/MedicalHistory.java (rev 0)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e4/a/MedicalHistory.java 2010-01-25 17:19:05 UTC (rev 18619)
@@ -0,0 +1,27 @@
+package org.hibernate.test.annotations.derivedidentities.e4.a;
+
+import java.io.Serializable;
+import java.util.Date;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.MapsId;
+import javax.persistence.OneToOne;
+import javax.persistence.Temporal;
+import javax.persistence.TemporalType;
+
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class MedicalHistory implements Serializable {
+
+ @Temporal(TemporalType.DATE)
+ Date lastupdate;
+
+ @Id
+ @JoinColumn(name = "FK")
+ @OneToOne
+ Person patient;
+}
\ No newline at end of file
Copied: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e4/a/Person.java (from rev 18592, core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e4/b/Person.java)
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e4/a/Person.java (rev 0)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e4/a/Person.java 2010-01-25 17:19:05 UTC (rev 18619)
@@ -0,0 +1,14 @@
+package org.hibernate.test.annotations.derivedidentities.e4.a;
+
+import java.io.Serializable;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Person {
+ @Id
+ String ssn;
+}
\ No newline at end of file
Added: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e4/a/Simple.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e4/a/Simple.java (rev 0)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e4/a/Simple.java 2010-01-25 17:19:05 UTC (rev 18619)
@@ -0,0 +1,17 @@
+package org.hibernate.test.annotations.derivedidentities.e4.a;
+
+import java.io.Serializable;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Simple
+ implements Serializable {
+ @Id
+ String ssn;
+ @Id
+ String name;
+}
14 years, 11 months
Hibernate SVN: r18618 - in core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan: collection and 4 other directories.
by hibernate-commits@lists.jboss.org
Author: galder.zamarreno(a)jboss.com
Date: 2010-01-25 11:23:59 -0500 (Mon, 25 Jan 2010)
New Revision: 18618
Modified:
core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/InfinispanRegionFactory.java
core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/CollectionRegionImpl.java
core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/EntityRegionImpl.java
core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseGeneralDataRegion.java
core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseRegion.java
core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseTransactionalDataRegion.java
core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/query/QueryResultsRegionImpl.java
core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/TimestampsRegionImpl.java
Log:
Individual regions currently use the same implementation as InfinispanRegionFactory for the next timestamp. Get them to actually call InfinispanRegionFactory to make it easier for users to provide diff implementations if desired.
Modified: core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/InfinispanRegionFactory.java
===================================================================
--- core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/InfinispanRegionFactory.java 2010-01-25 15:47:02 UTC (rev 18617)
+++ core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/InfinispanRegionFactory.java 2010-01-25 16:23:59 UTC (rev 18618)
@@ -162,7 +162,7 @@
log.debug("Building collection cache region [" + regionName + "]");
Cache cache = getCache(regionName, COLLECTION_KEY, properties);
CacheAdapter cacheAdapter = CacheAdapterImpl.newInstance(cache);
- CollectionRegionImpl region = new CollectionRegionImpl(cacheAdapter, regionName, metadata, transactionManager);
+ CollectionRegionImpl region = new CollectionRegionImpl(cacheAdapter, regionName, metadata, transactionManager, this);
region.start();
return region;
}
@@ -172,7 +172,7 @@
if (log.isDebugEnabled()) log.debug("Building entity cache region [" + regionName + "]");
Cache cache = getCache(regionName, ENTITY_KEY, properties);
CacheAdapter cacheAdapter = CacheAdapterImpl.newInstance(cache);
- EntityRegionImpl region = new EntityRegionImpl(cacheAdapter, regionName, metadata, transactionManager);
+ EntityRegionImpl region = new EntityRegionImpl(cacheAdapter, regionName, metadata, transactionManager, this);
region.start();
return region;
}
@@ -185,7 +185,7 @@
log.debug("Building query results cache region [" + regionName + "]");
String cacheName = typeOverrides.get(QUERY_KEY).getCacheName();
CacheAdapter cacheAdapter = CacheAdapterImpl.newInstance(manager.getCache(cacheName));
- QueryResultsRegionImpl region = new QueryResultsRegionImpl(cacheAdapter, regionName, properties, transactionManager);
+ QueryResultsRegionImpl region = new QueryResultsRegionImpl(cacheAdapter, regionName, properties, transactionManager, this);
region.start();
return region;
}
@@ -198,7 +198,7 @@
log.debug("Building timestamps cache region [" + regionName + "]");
String cacheName = typeOverrides.get(TIMESTAMPS_KEY).getCacheName();
CacheAdapter cacheAdapter = CacheAdapterImpl.newInstance(manager.getCache(cacheName));
- TimestampsRegionImpl region = new TimestampsRegionImpl(cacheAdapter, regionName, transactionManager);
+ TimestampsRegionImpl region = new TimestampsRegionImpl(cacheAdapter, regionName, transactionManager, this);
region.start();
return region;
}
Modified: core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/CollectionRegionImpl.java
===================================================================
--- core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/CollectionRegionImpl.java 2010-01-25 15:47:02 UTC (rev 18617)
+++ core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/CollectionRegionImpl.java 2010-01-25 16:23:59 UTC (rev 18618)
@@ -5,6 +5,7 @@
import org.hibernate.cache.CacheDataDescription;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.CollectionRegion;
+import org.hibernate.cache.RegionFactory;
import org.hibernate.cache.access.AccessType;
import org.hibernate.cache.access.CollectionRegionAccessStrategy;
import org.hibernate.cache.infinispan.access.PutFromLoadValidator;
@@ -20,8 +21,9 @@
@Listener
public class CollectionRegionImpl extends BaseTransactionalDataRegion implements CollectionRegion {
- public CollectionRegionImpl(CacheAdapter cacheAdapter, String name, CacheDataDescription metadata, TransactionManager transactionManager) {
- super(cacheAdapter, name, metadata, transactionManager);
+ public CollectionRegionImpl(CacheAdapter cacheAdapter, String name, CacheDataDescription metadata,
+ TransactionManager transactionManager, RegionFactory factory) {
+ super(cacheAdapter, name, metadata, transactionManager, factory);
}
public CollectionRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException {
Modified: core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/EntityRegionImpl.java
===================================================================
--- core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/EntityRegionImpl.java 2010-01-25 15:47:02 UTC (rev 18617)
+++ core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/EntityRegionImpl.java 2010-01-25 16:23:59 UTC (rev 18618)
@@ -5,6 +5,7 @@
import org.hibernate.cache.CacheDataDescription;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.EntityRegion;
+import org.hibernate.cache.RegionFactory;
import org.hibernate.cache.access.AccessType;
import org.hibernate.cache.access.EntityRegionAccessStrategy;
import org.hibernate.cache.infinispan.access.PutFromLoadValidator;
@@ -20,8 +21,9 @@
@Listener
public class EntityRegionImpl extends BaseTransactionalDataRegion implements EntityRegion {
- public EntityRegionImpl(CacheAdapter cacheAdapter, String name, CacheDataDescription metadata, TransactionManager transactionManager) {
- super(cacheAdapter, name, metadata, transactionManager);
+ public EntityRegionImpl(CacheAdapter cacheAdapter, String name, CacheDataDescription metadata,
+ TransactionManager transactionManager, RegionFactory factory) {
+ super(cacheAdapter, name, metadata, transactionManager, factory);
}
public EntityRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException {
Modified: core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseGeneralDataRegion.java
===================================================================
--- core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseGeneralDataRegion.java 2010-01-25 15:47:02 UTC (rev 18617)
+++ core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseGeneralDataRegion.java 2010-01-25 16:23:59 UTC (rev 18618)
@@ -4,6 +4,7 @@
import org.hibernate.cache.CacheException;
import org.hibernate.cache.GeneralDataRegion;
+import org.hibernate.cache.RegionFactory;
import org.hibernate.cache.infinispan.util.CacheAdapter;
/**
@@ -15,8 +16,8 @@
*/
public abstract class BaseGeneralDataRegion extends BaseRegion implements GeneralDataRegion {
- public BaseGeneralDataRegion(CacheAdapter cacheAdapter, String name, TransactionManager transactionManager) {
- super(cacheAdapter, name, transactionManager);
+ public BaseGeneralDataRegion(CacheAdapter cacheAdapter, String name, TransactionManager transactionManager, RegionFactory factory) {
+ super(cacheAdapter, name, transactionManager, factory);
}
public void evict(Object key) throws CacheException {
Modified: core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseRegion.java
===================================================================
--- core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseRegion.java 2010-01-25 15:47:02 UTC (rev 18617)
+++ core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseRegion.java 2010-01-25 16:23:59 UTC (rev 18618)
@@ -14,6 +14,7 @@
import org.hibernate.cache.CacheException;
import org.hibernate.cache.Region;
+import org.hibernate.cache.RegionFactory;
import org.hibernate.cache.infinispan.util.AddressAdapter;
import org.hibernate.cache.infinispan.util.AddressAdapterImpl;
import org.hibernate.cache.infinispan.util.CacheAdapter;
@@ -48,14 +49,16 @@
protected final boolean replication;
protected final Object invalidationMutex = new Object();
protected final AtomicReference<InvalidateState> invalidateState = new AtomicReference<InvalidateState>(InvalidateState.VALID);
+ private final RegionFactory factory;
- public BaseRegion(CacheAdapter cacheAdapter, String name, TransactionManager transactionManager) {
+ public BaseRegion(CacheAdapter cacheAdapter, String name, TransactionManager transactionManager, RegionFactory factory) {
this.cacheAdapter = cacheAdapter;
this.name = name;
this.transactionManager = transactionManager;
this.replication = cacheAdapter.isClusteredReplication();
this.address = this.cacheAdapter.getAddress();
this.cacheAdapter.addListener(this);
+ this.factory = factory;
}
public void start() {
@@ -126,7 +129,7 @@
}
public long nextTimestamp() {
- return System.currentTimeMillis() / 100;
+ return factory.nextTimestamp();
}
public Map toMap() {
Modified: core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseTransactionalDataRegion.java
===================================================================
--- core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseTransactionalDataRegion.java 2010-01-25 15:47:02 UTC (rev 18617)
+++ core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseTransactionalDataRegion.java 2010-01-25 16:23:59 UTC (rev 18618)
@@ -3,6 +3,7 @@
import javax.transaction.TransactionManager;
import org.hibernate.cache.CacheDataDescription;
+import org.hibernate.cache.RegionFactory;
import org.hibernate.cache.TransactionalDataRegion;
import org.hibernate.cache.infinispan.util.CacheAdapter;
@@ -17,8 +18,8 @@
private final CacheDataDescription metadata;
- public BaseTransactionalDataRegion(CacheAdapter cacheAdapter, String name, CacheDataDescription metadata, TransactionManager transactionManager) {
- super(cacheAdapter, name, transactionManager);
+ public BaseTransactionalDataRegion(CacheAdapter cacheAdapter, String name, CacheDataDescription metadata, TransactionManager transactionManager, RegionFactory factory) {
+ super(cacheAdapter, name, transactionManager, factory);
this.metadata = metadata;
}
Modified: core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/query/QueryResultsRegionImpl.java
===================================================================
--- core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/query/QueryResultsRegionImpl.java 2010-01-25 15:47:02 UTC (rev 18617)
+++ core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/query/QueryResultsRegionImpl.java 2010-01-25 16:23:59 UTC (rev 18618)
@@ -7,6 +7,7 @@
import org.hibernate.cache.CacheException;
import org.hibernate.cache.QueryResultsRegion;
+import org.hibernate.cache.RegionFactory;
import org.hibernate.cache.infinispan.impl.BaseTransactionalDataRegion;
import org.hibernate.cache.infinispan.util.CacheAdapter;
import org.hibernate.cache.infinispan.util.CacheHelper;
@@ -22,9 +23,8 @@
public class QueryResultsRegionImpl extends BaseTransactionalDataRegion implements QueryResultsRegion {
private boolean localOnly;
- public QueryResultsRegionImpl(CacheAdapter cacheAdapter, String name, Properties properties, TransactionManager transactionManager) {
- super(cacheAdapter, name, null, transactionManager);
-
+ public QueryResultsRegionImpl(CacheAdapter cacheAdapter, String name, Properties properties, TransactionManager transactionManager, RegionFactory factory) {
+ super(cacheAdapter, name, null, transactionManager, factory);
// If Infinispan is using INVALIDATION for query cache, we don't want to propagate changes.
// We use the Timestamps cache to manage invalidation
localOnly = cacheAdapter.isClusteredInvalidation();
Modified: core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/TimestampsRegionImpl.java
===================================================================
--- core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/TimestampsRegionImpl.java 2010-01-25 15:47:02 UTC (rev 18617)
+++ core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/TimestampsRegionImpl.java 2010-01-25 16:23:59 UTC (rev 18618)
@@ -8,6 +8,7 @@
import javax.transaction.TransactionManager;
import org.hibernate.cache.CacheException;
+import org.hibernate.cache.RegionFactory;
import org.hibernate.cache.TimestampsRegion;
import org.hibernate.cache.infinispan.impl.BaseGeneralDataRegion;
import org.hibernate.cache.infinispan.util.CacheAdapter;
@@ -32,8 +33,8 @@
private Map localCache = new ConcurrentHashMap();
- public TimestampsRegionImpl(CacheAdapter cacheAdapter, String name, TransactionManager transactionManager) {
- super(cacheAdapter, name, transactionManager);
+ public TimestampsRegionImpl(CacheAdapter cacheAdapter, String name, TransactionManager transactionManager, RegionFactory factory) {
+ super(cacheAdapter, name, transactionManager, factory);
cacheAdapter.addListener(this);
populateLocalCache();
}
14 years, 11 months
Hibernate SVN: r18617 - in core/trunk/cache-infinispan/src: test/java/org/hibernate/test/cache/infinispan and 1 other directory.
by hibernate-commits@lists.jboss.org
Author: galder.zamarreno(a)jboss.com
Date: 2010-01-25 10:47:02 -0500 (Mon, 25 Jan 2010)
New Revision: 18617
Modified:
core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/InfinispanRegionFactory.java
core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/TypeOverrides.java
core/trunk/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/InfinispanRegionFactoryTestCase.java
Log:
[HHH-4814] (Configure global/cache level JMX statistics from Hibernate configuration file) Added hibernate.cache.infinispan.statistics that enables cache manager and individual cache statistics.
Modified: core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/InfinispanRegionFactory.java
===================================================================
--- core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/InfinispanRegionFactory.java 2010-01-25 07:56:21 UTC (rev 18616)
+++ core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/InfinispanRegionFactory.java 2010-01-25 15:47:02 UTC (rev 18617)
@@ -55,13 +55,15 @@
private static final String STRATEGY_SUFFIX = ".eviction.strategy";
private static final String WAKE_UP_INTERVAL_SUFFIX = ".eviction.wake_up_interval";
-
+
private static final String MAX_ENTRIES_SUFFIX = ".eviction.max_entries";
-
+
private static final String LIFESPAN_SUFFIX = ".expiration.lifespan";
-
+
private static final String MAX_IDLE_SUFFIX = ".expiration.max_idle";
-
+
+// private static final String STATISTICS_SUFFIX = ".statistics";
+
/**
* Classpath or filesystem resource containing Infinispan configurations the factory should use.
*
@@ -69,6 +71,8 @@
*/
public static final String INFINISPAN_CONFIG_RESOURCE_PROP = "hibernate.cache.infinispan.cfg";
+ public static final String INFINISPAN_GLOBAL_STATISTICS_PROP = "hibernate.cache.infinispan.statistics";
+
private static final String ENTITY_KEY = "entity";
/**
@@ -107,35 +111,35 @@
* @see #DEF_QUERY_RESOURCE
*/
public static final String QUERY_CACHE_RESOURCE_PROP = PREFIX + QUERY_KEY + CONFIG_SUFFIX;
-
+
/**
* Default value for {@link #INFINISPAN_RESOURCE_PROP}. Specifies the "infinispan-configs.xml" file in this package.
*/
public static final String DEF_INFINISPAN_CONFIG_RESOURCE = "org/hibernate/cache/infinispan/builder/infinispan-configs.xml";
-
+
/**
* Default value for {@link #ENTITY_CACHE_RESOURCE_PROP}.
*/
public static final String DEF_ENTITY_RESOURCE = "entity";
-
+
/**
* Default value for {@link #TIMESTAMPS_CACHE_RESOURCE_PROP}.
*/
public static final String DEF_TIMESTAMPS_RESOURCE = "timestamps";
-
+
/**
* Default value for {@link #QUERY_CACHE_RESOURCE_PROP}.
*/
public static final String DEF_QUERY_RESOURCE = "local-query";
-
+
private CacheManager manager;
-
+
private final Map<String, TypeOverrides> typeOverrides = new HashMap<String, TypeOverrides>();
-
+
private final Set<String> definedConfigurations = new HashSet<String>();
-
+
private org.infinispan.transaction.lookup.TransactionManagerLookup transactionManagerlookup;
-
+
private TransactionManager transactionManager;
/**
@@ -206,12 +210,12 @@
return true;
}
- @Override
- public AccessType getDefaultAccessType() {
- return AccessType.TRANSACTIONAL;
- }
+ @Override
+ public AccessType getDefaultAccessType() {
+ return AccessType.TRANSACTIONAL;
+ }
- /**
+ /**
* {@inheritDoc}
*/
public long nextTimestamp() {
@@ -234,7 +238,6 @@
try {
transactionManagerlookup = new HibernateTransactionManagerLookup(settings, properties);
transactionManager = transactionManagerlookup.getTransactionManager();
-
manager = createCacheManager(properties);
initGenericDataTypeOverrides();
Enumeration keys = properties.propertyNames();
@@ -278,7 +281,13 @@
protected CacheManager createCacheManager(Properties properties) throws CacheException {
try {
String configLoc = PropertiesHelper.getString(INFINISPAN_CONFIG_RESOURCE_PROP, properties, DEF_INFINISPAN_CONFIG_RESOURCE);
- return new DefaultCacheManager(configLoc);
+ CacheManager manager = new DefaultCacheManager(configLoc, false);
+ String globalStats = PropertiesHelper.extractPropertyValue(INFINISPAN_GLOBAL_STATISTICS_PROP, properties);
+ if (globalStats != null) {
+ manager.getGlobalConfiguration().setExposeGlobalJmxStatistics(Boolean.parseBoolean(globalStats));
+ }
+ manager.start();
+ return manager;
} catch (IOException e) {
throw new CacheException("Unable to create default cache manager", e);
}
@@ -299,12 +308,7 @@
typeOverrides.put(QUERY_KEY, queryOverrides);
return typeOverrides;
}
-
-// private boolean isGenericDataTypeProperty(String property) {
-// return property.startsWith(PREFIX + ENTITY_KEY) || property.startsWith(PREFIX + COLLECTION_KEY)
-// || property.startsWith(PREFIX + QUERY_KEY) || property.startsWith(PREFIX + TIMESTAMP_KEY);
-// }
-
+
private void dissectProperty(int prefixLoc, String key, Properties properties) {
TypeOverrides cfgOverride = null;
int suffixLoc = -1;
@@ -327,6 +331,10 @@
cfgOverride = getOrCreateConfig(prefixLoc, key, suffixLoc);
cfgOverride.setExpirationMaxIdle(Long.parseLong(PropertiesHelper.extractPropertyValue(key, properties)));
}
+// else if ((suffixLoc = key.indexOf(STATISTICS_SUFFIX)) != -1) {
+// cfgOverride = getOrCreateConfig(prefixLoc, key, suffixLoc);
+// cfgOverride.setExposeStatistics(Boolean.parseBoolean(PropertiesHelper.extractPropertyValue(key, properties)));
+// }
}
private TypeOverrides getOrCreateConfig(int prefixLoc, String key, int suffixLoc) {
@@ -338,11 +346,11 @@
}
return cfgOverride;
}
-
+
private void defineGenericDataTypeCacheConfigurations(Settings settings, Properties properties) throws CacheException {
String[] defaultGenericDataTypes = new String[]{ENTITY_KEY, COLLECTION_KEY, TIMESTAMPS_KEY, QUERY_KEY};
for (String type : defaultGenericDataTypes) {
- TypeOverrides override = typeOverrides.get(type);
+ TypeOverrides override = overrideStatisticsIfPresent(typeOverrides.get(type), properties);
String cacheName = override.getCacheName();
Configuration newCacheCfg = override.createInfinispanConfiguration();
// Apply overrides
@@ -354,7 +362,7 @@
override.validateInfinispanConfiguration(cacheConfig);
}
}
-
+
private Cache getCache(String regionName, String typeKey, Properties properties) {
TypeOverrides regionOverride = typeOverrides.get(regionName);
if (!definedConfigurations.contains(regionName)) {
@@ -362,6 +370,7 @@
Configuration regionCacheCfg = null;
if (regionOverride != null) {
if (log.isDebugEnabled()) log.debug("Entity cache region specific configuration exists: " + regionOverride);
+ regionOverride = overrideStatisticsIfPresent(regionOverride, properties);
regionCacheCfg = regionOverride.createInfinispanConfiguration();
String cacheName = regionOverride.getCacheName();
if (cacheName != null) // Region specific override with a given cache name
@@ -381,7 +390,7 @@
}
return manager.getCache(regionName);
}
-
+
private Configuration configureTransactionManager(Configuration regionOverrides, String templateCacheName, Properties properties) {
// Get existing configuration to verify whether a tm was configured or not.
Configuration templateConfig = manager.defineConfiguration(templateCacheName, new Configuration());
@@ -395,4 +404,12 @@
}
return regionOverrides;
}
+
+ private TypeOverrides overrideStatisticsIfPresent(TypeOverrides override, Properties properties) {
+ String globalStats = PropertiesHelper.extractPropertyValue(INFINISPAN_GLOBAL_STATISTICS_PROP, properties);
+ if (globalStats != null) {
+ override.setExposeStatistics(Boolean.parseBoolean(globalStats));
+ }
+ return override;
+ }
}
\ No newline at end of file
Modified: core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/TypeOverrides.java
===================================================================
--- core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/TypeOverrides.java 2010-01-25 07:56:21 UTC (rev 18616)
+++ core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/TypeOverrides.java 2010-01-25 15:47:02 UTC (rev 18617)
@@ -21,7 +21,9 @@
*/
package org.hibernate.cache.infinispan;
+import java.util.HashSet;
import java.util.Locale;
+import java.util.Set;
import org.hibernate.cache.CacheException;
import org.infinispan.config.Configuration;
@@ -36,19 +38,23 @@
* @since 3.5
*/
public class TypeOverrides {
-
+
+ private final Set<String> overridden = new HashSet<String>();
+
private String cacheName;
-
+
private EvictionStrategy evictionStrategy;
-
- private long evictionWakeUpInterval = Long.MIN_VALUE;
-
- private int evictionMaxEntries = Integer.MIN_VALUE;
-
- private long expirationLifespan = Long.MIN_VALUE;
-
- private long expirationMaxIdle = Long.MIN_VALUE;
+ private long evictionWakeUpInterval;
+
+ private int evictionMaxEntries;
+
+ private long expirationLifespan;
+
+ private long expirationMaxIdle;
+
+ private boolean isExposeStatistics;
+
public String getCacheName() {
return cacheName;
}
@@ -62,6 +68,7 @@
}
public void setEvictionStrategy(String evictionStrategy) {
+ markAsOverriden("evictionStrategy");
this.evictionStrategy = EvictionStrategy.valueOf(uc(evictionStrategy));
}
@@ -70,6 +77,7 @@
}
public void setEvictionWakeUpInterval(long evictionWakeUpInterval) {
+ markAsOverriden("evictionWakeUpInterval");
this.evictionWakeUpInterval = evictionWakeUpInterval;
}
@@ -78,6 +86,7 @@
}
public void setEvictionMaxEntries(int evictionMaxEntries) {
+ markAsOverriden("evictionMaxEntries");
this.evictionMaxEntries = evictionMaxEntries;
}
@@ -86,6 +95,7 @@
}
public void setExpirationLifespan(long expirationLifespan) {
+ markAsOverriden("expirationLifespan");
this.expirationLifespan = expirationLifespan;
}
@@ -94,32 +104,34 @@
}
public void setExpirationMaxIdle(long expirationMaxIdle) {
+ markAsOverriden("expirationMaxIdle");
this.expirationMaxIdle = expirationMaxIdle;
}
-
-// public boolean isConvertedToInfinispanConfiguration() {
-// return convertedToInfinispanConfiguration;
-// }
-
+
+ public boolean isExposeStatistics() {
+ return isExposeStatistics;
+ }
+
+ public void setExposeStatistics(boolean isExposeStatistics) {
+ markAsOverriden("isExposeStatistics");
+ this.isExposeStatistics = isExposeStatistics;
+ }
+
public Configuration createInfinispanConfiguration() {
Configuration cacheCfg = new Configuration();
- // If eviction strategy is different from null, an override has been defined
- if (evictionStrategy != null) cacheCfg.setEvictionStrategy(evictionStrategy);
- // If eviction wake up interval is different from min value, an override has been defined
- // Checking for -1 might not be enough because user might have defined -1 in the config.
- // Same applies to other configuration options.
- if (evictionWakeUpInterval != Long.MIN_VALUE) cacheCfg.setEvictionWakeUpInterval(evictionWakeUpInterval);
- if (evictionMaxEntries != Integer.MIN_VALUE) cacheCfg.setEvictionMaxEntries(evictionMaxEntries);
- if (expirationLifespan != Long.MIN_VALUE) cacheCfg.setExpirationLifespan(expirationLifespan);
- if (expirationMaxIdle != Long.MIN_VALUE) cacheCfg.setExpirationMaxIdle(expirationMaxIdle);
-// convertedToInfinispanConfiguration = true;
+ if (overridden.contains("evictionStrategy")) cacheCfg.setEvictionStrategy(evictionStrategy);
+ if (overridden.contains("evictionWakeUpInterval")) cacheCfg.setEvictionWakeUpInterval(evictionWakeUpInterval);
+ if (overridden.contains("evictionMaxEntries")) cacheCfg.setEvictionMaxEntries(evictionMaxEntries);
+ if (overridden.contains("expirationLifespan")) cacheCfg.setExpirationLifespan(expirationLifespan);
+ if (overridden.contains("expirationMaxIdle")) cacheCfg.setExpirationMaxIdle(expirationMaxIdle);
+ if (overridden.contains("isExposeStatistics")) cacheCfg.setExposeJmxStatistics(isExposeStatistics);
return cacheCfg;
}
-
+
public void validateInfinispanConfiguration(Configuration configuration) throws CacheException {
// no-op
}
-
+
@Override
public String toString() {
return new StringBuilder().append(getClass().getSimpleName()).append('{')
@@ -131,8 +143,12 @@
.append(", maxIdle=").append(expirationMaxIdle)
.append('}').toString();
}
-
+
private String uc(String s) {
return s == null ? null : s.toUpperCase(Locale.ENGLISH);
}
+
+ private void markAsOverriden(String fieldName) {
+ overridden.add(fieldName);
+ }
}
Modified: core/trunk/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/InfinispanRegionFactoryTestCase.java
===================================================================
--- core/trunk/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/InfinispanRegionFactoryTestCase.java 2010-01-25 07:56:21 UTC (rev 18616)
+++ core/trunk/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/InfinispanRegionFactoryTestCase.java 2010-01-25 15:47:02 UTC (rev 18617)
@@ -121,6 +121,7 @@
CacheManager manager = factory.getCacheManager();
manager.getGlobalConfiguration().setTransportClass(null);
try {
+ assertFalse(manager.getGlobalConfiguration().isExposeGlobalJmxStatistics());
assertNotNull(factory.getTypeOverrides().get(person));
assertFalse(factory.getDefinedConfigurations().contains(person));
assertNotNull(factory.getTypeOverrides().get(addresses));
@@ -138,6 +139,7 @@
assertEquals(5000, cacheCfg.getEvictionMaxEntries());
assertEquals(60000, cacheCfg.getExpirationLifespan());
assertEquals(30000, cacheCfg.getExpirationMaxIdle());
+ assertFalse(cacheCfg.isExposeJmxStatistics());
region = (EntityRegionImpl) factory.buildEntityRegion(address, p, null);
assertNotNull(factory.getTypeOverrides().get(person));
@@ -148,6 +150,7 @@
assertEquals(EvictionStrategy.FIFO, cacheCfg.getEvictionStrategy());
assertEquals(3000, cacheCfg.getEvictionWakeUpInterval());
assertEquals(20000, cacheCfg.getEvictionMaxEntries());
+ assertFalse(cacheCfg.isExposeJmxStatistics());
region = (EntityRegionImpl) factory.buildEntityRegion(car, p, null);
assertNotNull(factory.getTypeOverrides().get(person));
@@ -158,6 +161,7 @@
assertEquals(EvictionStrategy.FIFO, cacheCfg.getEvictionStrategy());
assertEquals(3000, cacheCfg.getEvictionWakeUpInterval());
assertEquals(20000, cacheCfg.getEvictionMaxEntries());
+ assertFalse(cacheCfg.isExposeJmxStatistics());
CollectionRegionImpl collectionRegion = (CollectionRegionImpl) factory.buildCollectionRegion(addresses, p, null);
assertNotNull(factory.getTypeOverrides().get(addresses));
@@ -170,6 +174,7 @@
assertEquals(5500, cacheCfg.getEvictionMaxEntries());
assertEquals(65000, cacheCfg.getExpirationLifespan());
assertEquals(35000, cacheCfg.getExpirationMaxIdle());
+ assertFalse(cacheCfg.isExposeJmxStatistics());
collectionRegion = (CollectionRegionImpl) factory.buildCollectionRegion(parts, p, null);
assertNotNull(factory.getTypeOverrides().get(addresses));
@@ -180,6 +185,7 @@
assertEquals(EvictionStrategy.LRU, cacheCfg.getEvictionStrategy());
assertEquals(3500, cacheCfg.getEvictionWakeUpInterval());
assertEquals(25000, cacheCfg.getEvictionMaxEntries());
+ assertFalse(cacheCfg.isExposeJmxStatistics());
collectionRegion = (CollectionRegionImpl) factory.buildCollectionRegion(parts, p, null);
assertNotNull(factory.getTypeOverrides().get(addresses));
@@ -190,6 +196,7 @@
assertEquals(EvictionStrategy.LRU, cacheCfg.getEvictionStrategy());
assertEquals(3500, cacheCfg.getEvictionWakeUpInterval());
assertEquals(25000, cacheCfg.getEvictionMaxEntries());
+ assertFalse(cacheCfg.isExposeJmxStatistics());
} finally {
factory.stop();
}
@@ -282,7 +289,7 @@
} catch(CacheException ce) {
}
}
-
+
public void testBuildDefaultTimestampsRegion() {
final String timestamps = "org.hibernate.cache.UpdateTimestampsCache";
Properties p = new Properties();
@@ -302,6 +309,7 @@
assertEquals(EvictionStrategy.NONE, cacheCfg.getEvictionStrategy());
assertEquals(CacheMode.REPL_ASYNC, cacheCfg.getCacheMode());
assertTrue(cacheCfg.isUseLazyDeserialization());
+ assertFalse(cacheCfg.isExposeJmxStatistics());
} finally {
factory.stop();
}
@@ -329,11 +337,12 @@
assertEquals(EvictionStrategy.NONE, cacheCfg.getEvictionStrategy());
assertEquals(CacheMode.REPL_SYNC, cacheCfg.getCacheMode());
assertFalse(cacheCfg.isUseLazyDeserialization());
+ assertFalse(cacheCfg.isExposeJmxStatistics());
} finally {
factory.stop();
}
}
-
+
public void testBuildTimestamRegionWithCacheNameOverride() {
final String timestamps = "org.hibernate.cache.UpdateTimestampsCache";
Properties p = new Properties();
@@ -370,7 +379,7 @@
factory.stop();
}
}
-
+
public void testBuildTimestamRegionWithNoneEvictionOverride() {
final String timestamps = "org.hibernate.cache.UpdateTimestampsCache";
Properties p = new Properties();
@@ -389,7 +398,7 @@
factory.stop();
}
}
-
+
public void testBuildQueryRegion() {
final String query = "org.hibernate.cache.StandardQueryCache";
Properties p = new Properties();
@@ -403,9 +412,107 @@
CacheAdapter cache = region.getCacheAdapter();
Configuration cacheCfg = cache.getConfiguration();
assertEquals(CacheMode.LOCAL, cacheCfg.getCacheMode());
+ assertFalse(cacheCfg.isExposeJmxStatistics());
} finally {
factory.stop();
}
}
+ public void testEnableStatistics() {
+ Properties p = new Properties();
+ p.setProperty("hibernate.cache.infinispan.statistics", "true");
+ p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.lifespan", "60000");
+ p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.max_idle", "30000");
+ p.setProperty("hibernate.cache.infinispan.entity.cfg", "myentity-cache");
+ p.setProperty("hibernate.cache.infinispan.entity.eviction.strategy", "FIFO");
+ p.setProperty("hibernate.cache.infinispan.entity.eviction.wake_up_interval", "3000");
+ p.setProperty("hibernate.cache.infinispan.entity.eviction.max_entries", "10000");
+ InfinispanRegionFactory factory = new InfinispanRegionFactory();
+ factory.start(null, p);
+ CacheManager manager = factory.getCacheManager();
+ manager.getGlobalConfiguration().setTransportClass(null);
+ try {
+ assertTrue(manager.getGlobalConfiguration().isExposeGlobalJmxStatistics());
+ EntityRegionImpl region = (EntityRegionImpl) factory.buildEntityRegion("com.acme.Address", p, null);
+ CacheAdapter cache = region.getCacheAdapter();
+ assertTrue(factory.getTypeOverrides().get("entity").isExposeStatistics());
+ assertTrue(cache.getConfiguration().isExposeJmxStatistics());
+
+ region = (EntityRegionImpl) factory.buildEntityRegion("com.acme.Person", p, null);
+ cache = region.getCacheAdapter();
+ assertTrue(factory.getTypeOverrides().get("com.acme.Person").isExposeStatistics());
+ assertTrue(cache.getConfiguration().isExposeJmxStatistics());
+
+ final String query = "org.hibernate.cache.StandardQueryCache";
+ QueryResultsRegionImpl queryRegion = (QueryResultsRegionImpl) factory.buildQueryResultsRegion(query, p);
+ cache = queryRegion.getCacheAdapter();
+ assertTrue(factory.getTypeOverrides().get("query").isExposeStatistics());
+ assertTrue(cache.getConfiguration().isExposeJmxStatistics());
+
+ final String timestamps = "org.hibernate.cache.UpdateTimestampsCache";
+ Configuration config = new Configuration();
+ config.setFetchInMemoryState(false);
+ manager.defineConfiguration("timestamps", config);
+ TimestampsRegionImpl timestampsRegion = (TimestampsRegionImpl) factory.buildTimestampsRegion(timestamps, p);
+ cache = timestampsRegion.getCacheAdapter();
+ assertTrue(factory.getTypeOverrides().get("timestamps").isExposeStatistics());
+ assertTrue(cache.getConfiguration().isExposeJmxStatistics());
+
+ CollectionRegionImpl collectionRegion = (CollectionRegionImpl) factory.buildCollectionRegion("com.acme.Person.addresses", p, null);
+ cache = collectionRegion.getCacheAdapter();
+ assertTrue(factory.getTypeOverrides().get("collection").isExposeStatistics());
+ assertTrue(cache.getConfiguration().isExposeJmxStatistics());
+ } finally {
+ factory.stop();
+ }
+ }
+
+ public void testDisableStatistics() {
+ Properties p = new Properties();
+ p.setProperty("hibernate.cache.infinispan.statistics", "false");
+ p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.lifespan", "60000");
+ p.setProperty("hibernate.cache.infinispan.com.acme.Person.expiration.max_idle", "30000");
+ p.setProperty("hibernate.cache.infinispan.entity.cfg", "myentity-cache");
+ p.setProperty("hibernate.cache.infinispan.entity.eviction.strategy", "FIFO");
+ p.setProperty("hibernate.cache.infinispan.entity.eviction.wake_up_interval", "3000");
+ p.setProperty("hibernate.cache.infinispan.entity.eviction.max_entries", "10000");
+ InfinispanRegionFactory factory = new InfinispanRegionFactory();
+ factory.start(null, p);
+ CacheManager manager = factory.getCacheManager();
+ manager.getGlobalConfiguration().setTransportClass(null);
+ try {
+ assertFalse(manager.getGlobalConfiguration().isExposeGlobalJmxStatistics());
+ EntityRegionImpl region = (EntityRegionImpl) factory.buildEntityRegion("com.acme.Address", p, null);
+ CacheAdapter cache = region.getCacheAdapter();
+ assertFalse(factory.getTypeOverrides().get("entity").isExposeStatistics());
+ assertFalse(cache.getConfiguration().isExposeJmxStatistics());
+
+ region = (EntityRegionImpl) factory.buildEntityRegion("com.acme.Person", p, null);
+ cache = region.getCacheAdapter();
+ assertFalse(factory.getTypeOverrides().get("com.acme.Person").isExposeStatistics());
+ assertFalse(cache.getConfiguration().isExposeJmxStatistics());
+
+ final String query = "org.hibernate.cache.StandardQueryCache";
+ QueryResultsRegionImpl queryRegion = (QueryResultsRegionImpl) factory.buildQueryResultsRegion(query, p);
+ cache = queryRegion.getCacheAdapter();
+ assertFalse(factory.getTypeOverrides().get("query").isExposeStatistics());
+ assertFalse(cache.getConfiguration().isExposeJmxStatistics());
+
+ final String timestamps = "org.hibernate.cache.UpdateTimestampsCache";
+ Configuration config = new Configuration();
+ config.setFetchInMemoryState(false);
+ manager.defineConfiguration("timestamps", config);
+ TimestampsRegionImpl timestampsRegion = (TimestampsRegionImpl) factory.buildTimestampsRegion(timestamps, p);
+ cache = timestampsRegion.getCacheAdapter();
+ assertFalse(factory.getTypeOverrides().get("timestamps").isExposeStatistics());
+ assertFalse(cache.getConfiguration().isExposeJmxStatistics());
+
+ CollectionRegionImpl collectionRegion = (CollectionRegionImpl) factory.buildCollectionRegion("com.acme.Person.addresses", p, null);
+ cache = collectionRegion.getCacheAdapter();
+ assertFalse(factory.getTypeOverrides().get("collection").isExposeStatistics());
+ assertFalse(cache.getConfiguration().isExposeJmxStatistics());
+ } finally {
+ factory.stop();
+ }
+ }
}
14 years, 11 months
Hibernate SVN: r18616 - core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/relation/lazy/proxy.
by hibernate-commits@lists.jboss.org
Author: adamw
Date: 2010-01-25 02:56:21 -0500 (Mon, 25 Jan 2010)
New Revision: 18616
Modified:
core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/relation/lazy/proxy/MapProxy.java
core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/relation/lazy/proxy/SortedMapProxy.java
Log:
HHH-4693:
- applying patch, making map proxies serializable
Modified: core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/relation/lazy/proxy/MapProxy.java
===================================================================
--- core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/relation/lazy/proxy/MapProxy.java 2010-01-24 22:49:05 UTC (rev 18615)
+++ core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/relation/lazy/proxy/MapProxy.java 2010-01-25 07:56:21 UTC (rev 18616)
@@ -36,7 +36,7 @@
public class MapProxy<K, V> implements Map<K, V>, Serializable {
private static final long serialVersionUID = 8418037541773074646L;
- private Initializor<Map<K, V>> initializor;
+ private transient Initializor<Map<K, V>> initializor;
protected Map<K, V> delegate;
public MapProxy() {
Modified: core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/relation/lazy/proxy/SortedMapProxy.java
===================================================================
--- core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/relation/lazy/proxy/SortedMapProxy.java 2010-01-24 22:49:05 UTC (rev 18615)
+++ core/trunk/envers/src/main/java/org/hibernate/envers/entities/mapper/relation/lazy/proxy/SortedMapProxy.java 2010-01-25 07:56:21 UTC (rev 18616)
@@ -38,7 +38,7 @@
public class SortedMapProxy<K, V> implements SortedMap<K, V>, Serializable {
private static final long serialVersionUID = 2645817952901452375L;
- private Initializor<SortedMap<K, V>> initializor;
+ private transient Initializor<SortedMap<K, V>> initializor;
protected SortedMap<K, V> delegate;
public SortedMapProxy() {
@@ -154,4 +154,4 @@
checkInit();
return delegate.hashCode();
}
-}
\ No newline at end of file
+}
14 years, 11 months
Hibernate SVN: r18615 - annotations/branches/v3_3_1_GA_CP.
by hibernate-commits@lists.jboss.org
Author: stliu
Date: 2010-01-24 17:49:05 -0500 (Sun, 24 Jan 2010)
New Revision: 18615
Modified:
annotations/branches/v3_3_1_GA_CP/
Log:
ignore build and target directories
Property changes on: annotations/branches/v3_3_1_GA_CP
___________________________________________________________________
Name: svn:ignore
- .classpath
.project
+ .classpath
.project
build
target
14 years, 11 months