Hibernate SVN: r10498 - in trunk/HibernateExt/tools/src/java/org/hibernate/tool: . stat
by hibernate-commits@lists.jboss.org
Author: max.andersen(a)jboss.com
Date: 2006-09-20 12:25:44 -0400 (Wed, 20 Sep 2006)
New Revision: 10498
Added:
trunk/HibernateExt/tools/src/java/org/hibernate/tool/stat/
trunk/HibernateExt/tools/src/java/org/hibernate/tool/stat/AbstractTreeModel.java
trunk/HibernateExt/tools/src/java/org/hibernate/tool/stat/BeanTableModel.java
trunk/HibernateExt/tools/src/java/org/hibernate/tool/stat/StatisticsBrowser.java
trunk/HibernateExt/tools/src/java/org/hibernate/tool/stat/StatisticsCellRenderer.java
trunk/HibernateExt/tools/src/java/org/hibernate/tool/stat/StatisticsTreeModel.java
Log:
HBX-759 Add a statistics browser that is easy to use from hibernate apps
Added: trunk/HibernateExt/tools/src/java/org/hibernate/tool/stat/AbstractTreeModel.java
===================================================================
--- trunk/HibernateExt/tools/src/java/org/hibernate/tool/stat/AbstractTreeModel.java 2006-09-20 09:27:18 UTC (rev 10497)
+++ trunk/HibernateExt/tools/src/java/org/hibernate/tool/stat/AbstractTreeModel.java 2006-09-20 16:25:44 UTC (rev 10498)
@@ -0,0 +1,158 @@
+package org.hibernate.tool.stat;
+
+import javax.swing.event.TreeModelEvent;
+import javax.swing.event.TreeModelListener;
+import javax.swing.event.EventListenerList;
+import javax.swing.tree.TreeModel;
+import javax.swing.tree.TreePath;
+
+/**
+ * Abstract class implementing the support for TreeModelEvents
+ * and TreeModelListeners. The code is partly snipped from the
+ * implementation of DefaultTreeModel.
+ *
+ * @version $Revision: 1.1.2.1 $
+ **/
+
+public abstract class AbstractTreeModel implements TreeModel {
+
+ private EventListenerList listenerList = new EventListenerList();
+
+ /**
+ * Adds a listener for the TreeModelEvent posted after the tree changes.
+ *
+ * @see #removeTreeModelListener
+ * @param l the listener to add
+ */
+ public void addTreeModelListener(TreeModelListener l) {
+ listenerList.add(TreeModelListener.class, l);
+ }
+
+ /**
+ * Removes a listener previously added with <B>addTreeModelListener()</B>.
+ *
+ * @see #addTreeModelListener
+ * @param l the listener to remove
+ */
+ public void removeTreeModelListener(TreeModelListener l) {
+ listenerList.remove(TreeModelListener.class, l);
+ }
+
+ /**
+ * Messaged when the user has altered the value for the item identified
+ * by <I>path</I> to <I>newValue</I>. If <I>newValue</I> signifies
+ * a truly new value the model should post a treeNodesChanged
+ * event.
+ *
+ * @param path path to the node that the user has altered.
+ * @param newValue the new value from the TreeCellEditor.
+ */
+ public void valueForPathChanged(TreePath path, Object newValue) {
+ throw new RuntimeException("AbstractTreeModel.valueForPathChanged: you MUST override this when using a TreeCellEditor!");
+ }
+
+ /*
+ * Notify all listeners that have registered interest for
+ * notification on this event type. The event instance
+ * is lazily created using the parameters passed into
+ * the fire method.
+ * @see EventListenerList
+ */
+ protected void fireTreeNodesChanged(Object source, Object[] path,
+ int[] childIndices,
+ Object[] children) {
+ // Guaranteed to return a non-null array
+ Object[] listeners = listenerList.getListenerList();
+ TreeModelEvent e = null;
+ // Process the listeners last to first, notifying
+ // those that are interested in this event
+ for (int i = listeners.length-2; i>=0; i-=2) {
+ if (listeners[i]==TreeModelListener.class) {
+ // Lazily create the event:
+ if (e == null)
+ e = new TreeModelEvent(source, path,
+ childIndices, children);
+ ((TreeModelListener)listeners[i+1]).treeNodesChanged(e);
+ }
+ }
+ }
+
+ /*
+ * Notify all listeners that have registered interest for
+ * notification on this event type. The event instance
+ * is lazily created using the parameters passed into
+ * the fire method.
+ * @see EventListenerList
+ */
+ protected void fireTreeNodesInserted(Object source, Object[] path,
+ int[] childIndices,
+ Object[] children) {
+ // Guaranteed to return a non-null array
+ Object[] listeners = listenerList.getListenerList();
+ TreeModelEvent e = null;
+ // Process the listeners last to first, notifying
+ // those that are interested in this event
+ for (int i = listeners.length-2; i>=0; i-=2) {
+ if (listeners[i]==TreeModelListener.class) {
+ // Lazily create the event:
+ if (e == null)
+ e = new TreeModelEvent(source, path,
+ childIndices, children);
+ ((TreeModelListener)listeners[i+1]).treeNodesInserted(e);
+ }
+ }
+ }
+
+ /*
+ * Notify all listeners that have registered interest for
+ * notification on this event type. The event instance
+ * is lazily created using the parameters passed into
+ * the fire method.
+ * @see EventListenerList
+ */
+ protected void fireTreeNodesRemoved(Object source, Object[] path,
+ int[] childIndices,
+ Object[] children) {
+ // Guaranteed to return a non-null array
+ Object[] listeners = listenerList.getListenerList();
+ TreeModelEvent e = null;
+ // Process the listeners last to first, notifying
+ // those that are interested in this event
+ for (int i = listeners.length-2; i>=0; i-=2) {
+ if (listeners[i]==TreeModelListener.class) {
+ // Lazily create the event:
+ if (e == null)
+ e = new TreeModelEvent(source, path,
+ childIndices, children);
+ ((TreeModelListener)listeners[i+1]).treeNodesRemoved(e);
+ }
+ }
+ }
+
+ /*
+ * Notify all listeners that have registered interest for
+ * notification on this event type. The event instance
+ * is lazily created using the parameters passed into
+ * the fire method.
+ * @see EventListenerList
+ */
+ protected void fireTreeStructureChanged(Object source, Object[] path,
+ int[] childIndices,
+ Object[] children) {
+ // Guaranteed to return a non-null array
+ Object[] listeners = listenerList.getListenerList();
+ TreeModelEvent e = null;
+ // Process the listeners last to first, notifying
+ // those that are interested in this event
+ for (int i = listeners.length-2; i>=0; i-=2) {
+ if (listeners[i]==TreeModelListener.class) {
+ // Lazily create the event:
+ if (e == null)
+ e = new TreeModelEvent(source, path,
+ childIndices, children);
+ ((TreeModelListener)listeners[i+1]).treeStructureChanged(e);
+ }
+ }
+ }
+
+}
Added: trunk/HibernateExt/tools/src/java/org/hibernate/tool/stat/BeanTableModel.java
===================================================================
--- trunk/HibernateExt/tools/src/java/org/hibernate/tool/stat/BeanTableModel.java 2006-09-20 09:27:18 UTC (rev 10497)
+++ trunk/HibernateExt/tools/src/java/org/hibernate/tool/stat/BeanTableModel.java 2006-09-20 16:25:44 UTC (rev 10498)
@@ -0,0 +1,112 @@
+package org.hibernate.tool.stat;
+
+import java.beans.BeanDescriptor;
+import java.beans.BeanInfo;
+import java.beans.IntrospectionException;
+import java.beans.Introspector;
+import java.beans.PropertyDescriptor;
+import java.lang.reflect.InvocationTargetException;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.swing.table.AbstractTableModel;
+
+public class BeanTableModel extends AbstractTableModel {
+
+ protected List list;
+
+ private BeanInfo beanInfo = null;
+
+ private PropertyDescriptor[] descriptors = null;
+
+ public BeanTableModel(List list, Class beanClass) {
+ this.list = list;
+ introspect( beanClass );
+ }
+
+ private void introspect(Class beanClass) {
+ try {
+ this.beanInfo = Introspector.getBeanInfo( beanClass,
+ Introspector.USE_ALL_BEANINFO );
+ //descriptor = beanInfo.getBeanDescriptor();
+ descriptors = beanInfo.getPropertyDescriptors();
+ }
+ catch (IntrospectionException ie) {
+ // ignore
+ }
+
+ List v = new ArrayList(descriptors.length);
+ for (int i = 0; i < descriptors.length; i++) {
+ if(!descriptors[i].getName().equals("class")) {
+ v.add( descriptors[i] );
+ }
+ }
+ descriptors = (PropertyDescriptor[]) v.toArray( new PropertyDescriptor[v.size()] );
+
+ }
+
+ boolean isSingle() {
+ return list.size()<=1;
+ }
+
+ public int getRowCount() {
+ return isSingle() ? descriptors.length : list.size();
+ }
+
+ public int getColumnCount() {
+ return isSingle() ? list.size() + 1 : (descriptors != null ? descriptors.length : 0);
+ }
+
+ public Object getValueAt(int row, int col) {
+ if(isSingle()) {
+ if(col==0) {
+ return descriptors[row].getDisplayName();
+ } else {
+ return getValue(0, row);
+ }
+ } else {
+ return getValue( row, col );
+ }
+ }
+
+ private Object getValue(int row, int col) {
+ Object bean = list.get( row );
+ Object result = null;
+ try {
+ result = descriptors[col].getReadMethod().invoke( bean, null );
+ }
+ catch (InvocationTargetException ite) {
+ ite.printStackTrace();
+ }
+ catch (IllegalAccessException iae) {
+ iae.printStackTrace();
+ }
+ return result;
+ }
+
+ public String getColumnName(int col) {
+ if(isSingle()) {
+ if(col==0) {
+ return "Name";
+ } else {
+ return "Value";
+ }
+ } else {
+ return descriptors[col].getDisplayName();
+ }
+ }
+
+ public Class getColumnClass(int c) {
+ if(isSingle()) {
+ return String.class;
+ } else {
+ Class propertyType = descriptors[c].getPropertyType();
+
+ if(propertyType.isPrimitive()) {
+ return String.class; // to avoid jtable complain about null table renderer.
+ } else {
+ return propertyType;
+ }
+ }
+ }
+}
\ No newline at end of file
Added: trunk/HibernateExt/tools/src/java/org/hibernate/tool/stat/StatisticsBrowser.java
===================================================================
--- trunk/HibernateExt/tools/src/java/org/hibernate/tool/stat/StatisticsBrowser.java 2006-09-20 09:27:18 UTC (rev 10497)
+++ trunk/HibernateExt/tools/src/java/org/hibernate/tool/stat/StatisticsBrowser.java 2006-09-20 16:25:44 UTC (rev 10498)
@@ -0,0 +1,102 @@
+package org.hibernate.tool.stat;
+
+import java.awt.BorderLayout;
+import java.awt.Dimension;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import javax.swing.JDialog;
+import javax.swing.JFrame;
+import javax.swing.JScrollPane;
+import javax.swing.JSplitPane;
+import javax.swing.JTable;
+import javax.swing.JTree;
+import javax.swing.ToolTipManager;
+import javax.swing.event.TreeSelectionEvent;
+import javax.swing.event.TreeSelectionListener;
+
+import org.hibernate.stat.Statistics;
+import org.hibernate.stat.ui.BeanTableModel;
+import org.hibernate.stat.ui.StatisticsCellRenderer;
+import org.hibernate.stat.ui.StatisticsTreeModel;
+
+/**
+ * Very rudimentary statistics browser.
+ *
+ * Usage:
+ * new StatisticsBrowser().showStatistics(getSessions().getStatistics(), shouldBlock);
+ *
+ * @author max
+ *
+ */
+public class StatisticsBrowser {
+
+ /**
+ *
+ * @param stats a Statistics instance obtained from a SessionFactory
+ * @param shouldBlock decides if the ui will be modal or not.
+ */
+ public void showStatistics(Statistics stats, boolean shouldBlock) {
+
+ JDialog main = new JDialog((JFrame)null, "Statistics browser");
+
+ main.getContentPane().setLayout(new BorderLayout());
+
+ final StatisticsTreeModel statisticsTreeModel = new StatisticsTreeModel(stats);
+ JTree tree = new JTree(statisticsTreeModel);
+ tree.setCellRenderer( new StatisticsCellRenderer() );
+ ToolTipManager.sharedInstance().registerComponent(tree);
+
+ JScrollPane treePane = new JScrollPane(tree);
+
+ final JTable table = new JTable();
+
+ JScrollPane tablePane = new JScrollPane(table);
+ tablePane.getViewport().setBackground( table.getBackground() );
+ final BeanTableModel beanTableModel = new BeanTableModel(Collections.EMPTY_LIST, Object.class);
+ table.setModel( beanTableModel );
+
+ JSplitPane pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, treePane, tablePane);
+ pane.setContinuousLayout( true );
+
+ main.getContentPane().add(pane, BorderLayout.CENTER);
+
+ tree.addTreeSelectionListener( new TreeSelectionListener() {
+
+ public void valueChanged(TreeSelectionEvent e) {
+ Object lastPathComponent = e.getPath().getLastPathComponent();
+ List l = new ArrayList();
+ if(statisticsTreeModel.isContainer( lastPathComponent )) {
+ int childCount = statisticsTreeModel.getChildCount( lastPathComponent );
+
+ Class cl = Object.class;
+ for (int i = 0; i < childCount; i++) {
+ Object v = statisticsTreeModel.getChild( lastPathComponent, i );
+ if(v!=null) cl = v.getClass();
+ l.add(v);
+ }
+ table.setModel( new BeanTableModel(l, cl) );
+ } else {
+ l.add( lastPathComponent );
+ table.setModel( new BeanTableModel(l, lastPathComponent.getClass()) );
+ }
+
+ //table.doLayout();
+
+ }
+
+ } );
+
+
+ main.getContentPane().setSize(new Dimension(640,480));
+ main.pack();
+ main.setModal(shouldBlock);
+ main.setVisible(true);
+ }
+
+
+
+
+
+}
Added: trunk/HibernateExt/tools/src/java/org/hibernate/tool/stat/StatisticsCellRenderer.java
===================================================================
--- trunk/HibernateExt/tools/src/java/org/hibernate/tool/stat/StatisticsCellRenderer.java 2006-09-20 09:27:18 UTC (rev 10497)
+++ trunk/HibernateExt/tools/src/java/org/hibernate/tool/stat/StatisticsCellRenderer.java 2006-09-20 16:25:44 UTC (rev 10498)
@@ -0,0 +1,61 @@
+package org.hibernate.tool.stat;
+
+import java.awt.Component;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+import javax.swing.JLabel;
+import javax.swing.JTree;
+import javax.swing.tree.DefaultTreeCellRenderer;
+
+import org.hibernate.stat.CategorizedStatistics;
+import org.hibernate.stat.CollectionStatistics;
+import org.hibernate.stat.EntityStatistics;
+import org.hibernate.stat.QueryStatistics;
+import org.hibernate.stat.Statistics;
+
+public class StatisticsCellRenderer extends DefaultTreeCellRenderer {
+
+ SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
+
+ public Component getTreeCellRendererComponent(JTree tree, Object value,
+ boolean selected, boolean expanded, boolean leaf, int row,
+ boolean hasFocus) {
+
+ JLabel treeCellRendererComponent = (JLabel) super.getTreeCellRendererComponent( tree, value, selected, expanded, leaf, row, hasFocus );
+
+ String text = treeCellRendererComponent.getText();
+ String tooltip = null;
+ if(value instanceof Statistics) {
+ Statistics stats = (Statistics) value;
+ text = "Statistics " + formatter.format( new Date(stats.getStartTime()) );
+ tooltip = stats.toString();
+ }
+
+ if(value instanceof CategorizedStatistics) {
+ CategorizedStatistics stats = (CategorizedStatistics) value;
+ text = stats.getCategoryName();
+
+ }
+ if(value instanceof EntityStatistics) {
+ EntityStatistics stats = (EntityStatistics) value;
+
+ }
+
+ if(value instanceof CollectionStatistics) {
+ CollectionStatistics stats = (CollectionStatistics) value;
+
+ }
+
+ if(value instanceof QueryStatistics) {
+ QueryStatistics stats = (QueryStatistics) value;
+
+ }
+
+ treeCellRendererComponent.setText( text );
+ treeCellRendererComponent.setToolTipText( tooltip );
+ return treeCellRendererComponent;
+ }
+
+
+}
Added: trunk/HibernateExt/tools/src/java/org/hibernate/tool/stat/StatisticsTreeModel.java
===================================================================
--- trunk/HibernateExt/tools/src/java/org/hibernate/tool/stat/StatisticsTreeModel.java 2006-09-20 09:27:18 UTC (rev 10497)
+++ trunk/HibernateExt/tools/src/java/org/hibernate/tool/stat/StatisticsTreeModel.java 2006-09-20 16:25:44 UTC (rev 10498)
@@ -0,0 +1,79 @@
+package org.hibernate.tool.stat;
+
+import org.hibernate.stat.Statistics;
+import org.hibernate.stat.ui.AbstractTreeModel;
+
+public class StatisticsTreeModel extends AbstractTreeModel {
+
+ private final Statistics stats;
+
+ String queries = "Queries";
+ String entities = "Entities";
+ String collections = "Collections";
+
+
+
+ public StatisticsTreeModel(Statistics stats) {
+ this.stats = stats;
+ }
+
+ public Object getChild(Object parent, int index) {
+ if(parent==stats) {
+ switch(index) {
+ case 0: return entities;
+ case 1: return collections;
+ case 2: return queries;
+ }
+ } else if(parent==entities) {
+ return stats.getEntityStatistics(stats.getEntityNames()[index]);
+ } else if(parent==collections) {
+ return stats.getCollectionStatistics(stats.getCollectionRoleNames()[index]);
+ } else if(parent==queries) {
+ return stats.getQueryStatistics(stats.getQueries()[index]);
+ }
+ return null;
+ }
+
+ public int getChildCount(Object parent) {
+ if(parent==stats) {
+ return 3;
+ } else if(parent==entities) {
+ return stats.getEntityNames().length;
+ } else if(parent==collections) {
+ return stats.getCollectionRoleNames().length;
+ } else if(parent==queries) {
+ return stats.getQueries().length;
+ }
+ return 0;
+ }
+
+ public int getIndexOfChild(Object parent, Object child) {
+ throw new IllegalAccessError();
+ //return 0;
+ }
+
+ public Object getRoot() {
+ return stats;
+ }
+
+ public boolean isLeaf(Object node) {
+ return false;
+ }
+
+ public boolean isQueries(Object o) {
+ return o==queries; // hack
+ }
+
+ public boolean isCollections(Object o) {
+ return o==collections; // hack
+ }
+
+ public boolean isEntities(Object o) {
+ return o==entities; // hack
+ }
+
+ public boolean isContainer(Object o) {
+ return isEntities( o ) || isQueries( o ) || isCollections( o );
+ }
+
+}
\ No newline at end of file
18 years, 4 months
Hibernate SVN: r10497 - trunk/HibernateExt/tools/doc/reference/en/modules
by hibernate-commits@lists.jboss.org
Author: max.andersen(a)jboss.com
Date: 2006-09-20 05:27:18 -0400 (Wed, 20 Sep 2006)
New Revision: 10497
Modified:
trunk/HibernateExt/tools/doc/reference/en/modules/ant.xml
Log:
typo
Modified: trunk/HibernateExt/tools/doc/reference/en/modules/ant.xml
===================================================================
--- trunk/HibernateExt/tools/doc/reference/en/modules/ant.xml 2006-09-20 08:35:11 UTC (rev 10496)
+++ trunk/HibernateExt/tools/doc/reference/en/modules/ant.xml 2006-09-20 09:27:18 UTC (rev 10497)
@@ -622,7 +622,7 @@
necessary.</para>
<para><programlisting><![CDATA[<hibernatetool destdir="${build.dir}/generated">
- <annotaitonconfiguration configurationfile="hibernate.cfg.xml"/>
+ <annotationconfiguration configurationfile="hibernate.cfg.xml"/>
<hbm2hbmxml/>
</hibernatetool>]]></programlisting></para>
</section>
@@ -715,8 +715,7 @@
</section>
<section id="hbmtemplate">
- <title>Generic Hibernate metamodel exporter
- (<literal><hbmtemplate></literal>)</title>
+ <title>Generic Hibernate metamodel exporter (<literal><hbmtemplate></literal>)</title>
<para>Generic exporter that can be controlled by a user provided
template or class.</para>
18 years, 4 months
Hibernate SVN: r10496 - branches/Branch_3_2/Hibernate3/test/org/hibernate/test/extralazy
by hibernate-commits@lists.jboss.org
Author: max.andersen(a)jboss.com
Date: 2006-09-20 04:35:11 -0400 (Wed, 20 Sep 2006)
New Revision: 10496
Modified:
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/extralazy/ExtraLazyTest.java
Log:
extra lazy set test
Modified: branches/Branch_3_2/Hibernate3/test/org/hibernate/test/extralazy/ExtraLazyTest.java
===================================================================
--- branches/Branch_3_2/Hibernate3/test/org/hibernate/test/extralazy/ExtraLazyTest.java 2006-09-20 06:59:09 UTC (rev 10495)
+++ branches/Branch_3_2/Hibernate3/test/org/hibernate/test/extralazy/ExtraLazyTest.java 2006-09-20 08:35:11 UTC (rev 10496)
@@ -1,6 +1,7 @@
//$Id$
package org.hibernate.test.extralazy;
+import java.util.Iterator;
import java.util.List;
import java.util.Map;
@@ -209,6 +210,33 @@
}
+ public void testExtraLazySetFailureExpected() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ User gavin = new User("gavin", "secret");
+ new Document( "Hia", "something", gavin );
+ new Document( "Seam", "seamy", gavin );
+ s.persist(gavin);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+
+ User person = (User) s.get(User.class, gavin.getName());
+
+ new Document( "Fresh", "word", person );
+ System.out.println("Writing out the persons documentes (Set). Expected to find 3 but it only contains 2.");
+
+ for (Iterator iter = person.getDocuments().iterator(); iter.hasNext();) {
+ Document doc = (Document) iter.next();
+ System.out.println("phoneNumber: " + doc);
+ }
+
+ assertEquals(person.getDocuments().size(),3);
+ s.close();
+ }
+
protected String[] getMappings() {
return new String[] { "extralazy/UserGroup.hbm.xml" };
}
18 years, 4 months
Hibernate SVN: r10495 - branches/Branch_3_2/Hibernate3/doc/reference/en/modules trunk/Hibernate3/doc/reference/en/modules
by hibernate-commits@lists.jboss.org
Author: christian.bauer(a)jboss.com
Date: 2006-09-20 02:59:09 -0400 (Wed, 20 Sep 2006)
New Revision: 10495
Modified:
branches/Branch_3_2/Hibernate3/doc/reference/en/modules/tutorial.xml
trunk/Hibernate3/doc/reference/en/modules/tutorial.xml
Log:
Added warnings about session-per-operation anti-pattern
Modified: branches/Branch_3_2/Hibernate3/doc/reference/en/modules/tutorial.xml
===================================================================
--- branches/Branch_3_2/Hibernate3/doc/reference/en/modules/tutorial.xml 2006-09-19 16:59:36 UTC (rev 10494)
+++ branches/Branch_3_2/Hibernate3/doc/reference/en/modules/tutorial.xml 2006-09-20 06:59:09 UTC (rev 10495)
@@ -588,7 +588,7 @@
</sect2>
- <sect2 id="tutorial-firstapp-workingpersistence" revision="4">
+ <sect2 id="tutorial-firstapp-workingpersistence" revision="5">
<title>Loading and storing objects</title>
<para>
@@ -652,19 +652,35 @@
as many times and anywhere you like, once you get hold of your <literal>SessionFactory</literal>
(easy thanks to <literal>HibernateUtil</literal>). The <literal>getCurrentSession()</literal>
method always returns the "current" unit of work. Remember that we switched the configuration
- option for this mechanism to "thread" in <literal>hibernate.cfg.xml</literal>? Hence, the scope
- of the current unit of work is the current Java thread that executes our application. However, this
- is not the full truth. A <literal>Session</literal> begins when it is
- first needed, when the first call to <literal>getCurrentSession()</literal> is made.
- It is then bound by Hibernate to the current thread. When the transaction ends,
- either committed or rolled back, Hibernate also unbinds the <literal>Session</literal>
- from the thread and closes it for you. If you call <literal>getCurrentSession()</literal>
- again, you get a new <literal>Session</literal> and can start a new unit of work. This
- <emphasis>thread-bound</emphasis> programming model is the most popular way of using
- Hibernate.
+ option for this mechanism to "thread" in <literal>hibernate.cfg.xml</literal>? Hence,
+ the current unit of work is bound to the current Java thread that executes our application.
+ However, this is not the full picture, you also have to consider scope, when a unit of work
+ begins and when it ends.
</para>
<para>
+ A <literal>Session</literal> begins when it is first needed, when the first call to
+ <literal>getCurrentSession()</literal> is made. It is then bound by Hibernate to the current
+ thread. When the transaction ends, either through commit or rollback, Hibernate automatically
+ unbinds the <literal>Session</literal> from the thread and closes it for you. If you call
+ <literal>getCurrentSession()</literal> again, you get a new <literal>Session</literal> and can
+ start a new unit of work. This <emphasis>thread-bound</emphasis> programming model is the most
+ popular way of using Hibernate, as it allows flexible layering of your code (transaction
+ demarcation code can be separated from data access code, we'll do this later in this tutorial).
+ </para>
+
+ <para>
+ Related to the unit of work scope, should the Hibernate <literal>Session</literal> be used to
+ execute one or several database operations? The above example uses one <literal>Session</literal>
+ for one operation. This is pure coincidence, the example is just not complex enough to show any
+ other approach. The scope of a Hibernate <literal>Session</literal> is flexible but you should
+ never design your application to use a new Hibernate <literal>Session</literal> for
+ <emphasis>every</emphasis> database operation. So even if you see it a few more times in
+ the following (very trivial) examples, consider <emphasis>session-per-operation</emphasis>
+ an anti-pattern. A real (web) application is shown later in this tutorial.
+ </para>
+
+ <para>
Have a look at <xref linkend="transactions"/> for more information
about transaction handling and demarcation. We also skipped any error handling and
rollback in the previous example.
@@ -1254,7 +1270,7 @@
database, and it provides an HTML form to enter new events.
</para>
- <sect2 id="tutorial-webapp-servlet" revision="1">
+ <sect2 id="tutorial-webapp-servlet" revision="2">
<title>Writing the basic servlet</title>
<para>
@@ -1311,6 +1327,13 @@
</para>
<para>
+ Do <emphasis>not</emphasis> use a new Hibernate <literal>Session</literal> for
+ every database operation. Use one Hibernate <literal>Session</literal> that is
+ scoped to the whole request. Use <literal>getCurrentSession()</literal>, so that
+ it is automatically bound to the current Java thread.
+ </para>
+
+ <para>
Next, the possible actions of the request are processed and the response HTML
is rendered. We'll get to that part soon.
</para>
Modified: trunk/Hibernate3/doc/reference/en/modules/tutorial.xml
===================================================================
--- trunk/Hibernate3/doc/reference/en/modules/tutorial.xml 2006-09-19 16:59:36 UTC (rev 10494)
+++ trunk/Hibernate3/doc/reference/en/modules/tutorial.xml 2006-09-20 06:59:09 UTC (rev 10495)
@@ -588,7 +588,7 @@
</sect2>
- <sect2 id="tutorial-firstapp-workingpersistence" revision="4">
+ <sect2 id="tutorial-firstapp-workingpersistence" revision="5">
<title>Loading and storing objects</title>
<para>
@@ -652,19 +652,35 @@
as many times and anywhere you like, once you get hold of your <literal>SessionFactory</literal>
(easy thanks to <literal>HibernateUtil</literal>). The <literal>getCurrentSession()</literal>
method always returns the "current" unit of work. Remember that we switched the configuration
- option for this mechanism to "thread" in <literal>hibernate.cfg.xml</literal>? Hence, the scope
- of the current unit of work is the current Java thread that executes our application. However, this
- is not the full truth. A <literal>Session</literal> begins when it is
- first needed, when the first call to <literal>getCurrentSession()</literal> is made.
- It is then bound by Hibernate to the current thread. When the transaction ends,
- either committed or rolled back, Hibernate also unbinds the <literal>Session</literal>
- from the thread and closes it for you. If you call <literal>getCurrentSession()</literal>
- again, you get a new <literal>Session</literal> and can start a new unit of work. This
- <emphasis>thread-bound</emphasis> programming model is the most popular way of using
- Hibernate.
+ option for this mechanism to "thread" in <literal>hibernate.cfg.xml</literal>? Hence,
+ the current unit of work is bound to the current Java thread that executes our application.
+ However, this is not the full picture, you also have to consider scope, when a unit of work
+ begins and when it ends.
</para>
<para>
+ A <literal>Session</literal> begins when it is first needed, when the first call to
+ <literal>getCurrentSession()</literal> is made. It is then bound by Hibernate to the current
+ thread. When the transaction ends, either through commit or rollback, Hibernate automatically
+ unbinds the <literal>Session</literal> from the thread and closes it for you. If you call
+ <literal>getCurrentSession()</literal> again, you get a new <literal>Session</literal> and can
+ start a new unit of work. This <emphasis>thread-bound</emphasis> programming model is the most
+ popular way of using Hibernate, as it allows flexible layering of your code (transaction
+ demarcation code can be separated from data access code, we'll do this later in this tutorial).
+ </para>
+
+ <para>
+ Related to the unit of work scope, should the Hibernate <literal>Session</literal> be used to
+ execute one or several database operations? The above example uses one <literal>Session</literal>
+ for one operation. This is pure coincidence, the example is just not complex enough to show any
+ other approach. The scope of a Hibernate <literal>Session</literal> is flexible but you should
+ never design your application to use a new Hibernate <literal>Session</literal> for
+ <emphasis>every</emphasis> database operation. So even if you see it a few more times in
+ the following (very trivial) examples, consider <emphasis>session-per-operation</emphasis>
+ an anti-pattern. A real (web) application is shown later in this tutorial.
+ </para>
+
+ <para>
Have a look at <xref linkend="transactions"/> for more information
about transaction handling and demarcation. We also skipped any error handling and
rollback in the previous example.
@@ -1255,7 +1271,7 @@
database, and it provides an HTML form to enter new events.
</para>
- <sect2 id="tutorial-webapp-servlet" revision="1">
+ <sect2 id="tutorial-webapp-servlet" revision="2">
<title>Writing the basic servlet</title>
<para>
@@ -1312,6 +1328,13 @@
</para>
<para>
+ Do <emphasis>not</emphasis> use a new Hibernate <literal>Session</literal> for
+ every database operation. Use one Hibernate <literal>Session</literal> that is
+ scoped to the whole request. Use <literal>getCurrentSession()</literal>, so that
+ it is automatically bound to the current Java thread.
+ </para>
+
+ <para>
Next, the possible actions of the request are processed and the response HTML
is rendered. We'll get to that part soon.
</para>
18 years, 4 months
Hibernate SVN: r10494 - trunk/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/dialect
by hibernate-commits@lists.jboss.org
Author: max.andersen(a)jboss.com
Date: 2006-09-19 12:59:36 -0400 (Tue, 19 Sep 2006)
New Revision: 10494
Modified:
trunk/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/dialect/OracleMetaDataDialect.java
trunk/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/dialect/ResultSetIterator.java
Log:
HBX-758 OracleMetaDataDialect
fix opencursor leak (which were actually open statement leak)
Modified: trunk/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/dialect/OracleMetaDataDialect.java
===================================================================
--- trunk/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/dialect/OracleMetaDataDialect.java 2006-09-19 16:02:12 UTC (rev 10493)
+++ trunk/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/dialect/OracleMetaDataDialect.java 2006-09-19 16:59:36 UTC (rev 10494)
@@ -56,7 +56,7 @@
ResultSet tableRs = stmt.executeQuery(query.toString());
- return new ResultSetIterator(tableRs, getSQLExceptionConverter()) {
+ return new ResultSetIterator(stmt, tableRs, getSQLExceptionConverter()) {
Map element = new HashMap();
protected Object convertRow(ResultSet tableRs) throws SQLException {
@@ -108,7 +108,7 @@
ResultSet indexRs = stmt.executeQuery(query.toString());
- return new ResultSetIterator(indexRs, getSQLExceptionConverter()) {
+ return new ResultSetIterator(stmt, indexRs, getSQLExceptionConverter()) {
Map element = new HashMap();
protected Object convertRow(ResultSet rs) throws SQLException {
@@ -140,12 +140,12 @@
Statement stmt = this.getConnection().createStatement();
StringBuffer query = new StringBuffer();
- query.append("select column_name, owner, decode(nullable,'N',0,1), ");
- query.append("decode(data_type, 'FLOAT',decode(data_precision,null, data_length, data_precision), 'NUMBER', decode(data_precision,null, data_length, data_precision), data_length), ");
+ query.append("select column_name as COLUMN_NAME, owner as TABLE_SCHEM, decode(nullable,'N',0,1) as NULLABLE, ");
+ query.append("decode(data_type, 'FLOAT',decode(data_precision,null, data_length, data_precision), 'NUMBER', decode(data_precision,null, data_length, data_precision), data_length) as COLUMN_SIZE, ");
query.append("decode(data_type,'CHAR',1, 'DATE',91, 'FLOAT',6, 'LONG',-1, 'NUMBER',2, 'VARCHAR2',12, 'BFILE',-13, ");
query.append("'BLOB',2004, 'CLOB',2005, 'MLSLABEL',1111, 'NCHAR',1, 'NCLOB',2005, 'NVARCHAR2',12, ");
- query.append("'RAW',-3, 'ROWID',1111, 'UROWID',1111, 'LONG RAW', -4, 'TIMESTAMP', 93, 'XMLTYPE',2005, 1111), ");
- query.append("table_name, data_type, decode(data_scale, null, 0 ,data_scale) ");
+ query.append("'RAW',-3, 'ROWID',1111, 'UROWID',1111, 'LONG RAW', -4, 'TIMESTAMP', 93, 'XMLTYPE',2005, 1111) as DATA_TYPE, ");
+ query.append("table_name as TABLE_NAME, data_type as TYPE_NAME, decode(data_scale, null, 0 ,data_scale) as DECIMAL_DIGITS ");
query.append("from all_tab_columns ");
if (schema != null || table != null || column != null)
query.append("where ");
@@ -169,7 +169,7 @@
ResultSet columnRs = stmt.executeQuery(query.toString());
- return new ResultSetIterator(columnRs, getSQLExceptionConverter()) {
+ return new ResultSetIterator(stmt, columnRs, getSQLExceptionConverter()) {
Map element = new HashMap();
protected Object convertRow(ResultSet rs) throws SQLException {
@@ -221,7 +221,7 @@
ResultSet pkeyRs = stmt.executeQuery(query.toString());
- return new ResultSetIterator(pkeyRs, getSQLExceptionConverter()) {
+ return new ResultSetIterator(stmt, pkeyRs, getSQLExceptionConverter()) {
Map element = new HashMap();
protected Object convertRow(ResultSet rs) throws SQLException {
@@ -277,7 +277,7 @@
ResultSet pExportRs = stmt.executeQuery(query.toString());
- return new ResultSetIterator(pExportRs, getSQLExceptionConverter()) {
+ return new ResultSetIterator(stmt, pExportRs, getSQLExceptionConverter()) {
Map element = new HashMap();
protected Object convertRow(ResultSet rs) throws SQLException {
Modified: trunk/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/dialect/ResultSetIterator.java
===================================================================
--- trunk/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/dialect/ResultSetIterator.java 2006-09-19 16:02:12 UTC (rev 10493)
+++ trunk/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/dialect/ResultSetIterator.java 2006-09-19 16:59:36 UTC (rev 10494)
@@ -2,6 +2,7 @@
import java.sql.ResultSet;
import java.sql.SQLException;
+import java.sql.Statement;
import java.util.Iterator;
import java.util.NoSuchElementException;
@@ -20,11 +21,22 @@
private SQLExceptionConverter sec;
+ private Statement statement = null;
+
protected ResultSetIterator(ResultSet resultset, SQLExceptionConverter sec) {
+ this(null, resultset, sec);
+ }
+
+ public ResultSetIterator(Statement stmt, ResultSet resultset, SQLExceptionConverter exceptionConverter) {
this.rs = resultset;
- this.sec = sec;
+ this.sec = exceptionConverter;
+ this.statement = stmt;
}
+ protected SQLExceptionConverter getSQLExceptionConverter() {
+ return sec;
+ }
+
public boolean hasNext() {
try {
advance();
@@ -78,6 +90,9 @@
public void close() {
try {
rs.close();
+ if(statement!=null) {
+ statement.close();
+ }
}
catch (SQLException e) {
handleSQLException(e);
18 years, 4 months
Hibernate SVN: r10493 - trunk/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/dialect
by hibernate-commits@lists.jboss.org
Author: max.andersen(a)jboss.com
Date: 2006-09-19 12:02:12 -0400 (Tue, 19 Sep 2006)
New Revision: 10493
Added:
trunk/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/dialect/AbstractMetaDataDialect.java
Modified:
trunk/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/dialect/JDBCMetaDataDialect.java
trunk/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/dialect/OracleMetaDataDialect.java
Log:
HBX-758 OracleMetaDataDialect
fix class casting error
create abstractmetadatadialect to share the relevant code
Added: trunk/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/dialect/AbstractMetaDataDialect.java
===================================================================
--- trunk/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/dialect/AbstractMetaDataDialect.java 2006-09-18 21:48:12 UTC (rev 10492)
+++ trunk/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/dialect/AbstractMetaDataDialect.java 2006-09-19 16:02:12 UTC (rev 10493)
@@ -0,0 +1,137 @@
+package org.hibernate.cfg.reveng.dialect;
+
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.Iterator;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.hibernate.cfg.JDBCBinderException;
+import org.hibernate.connection.ConnectionProvider;
+import org.hibernate.exception.SQLExceptionConverter;
+
+/**
+ * abstract base class for the metadatadialects to hold the
+ * basic setup classes.
+ *
+ * @author max
+ *
+ */
+abstract public class AbstractMetaDataDialect implements MetaDataDialect {
+
+ protected final Log log = LogFactory.getLog(this.getClass());
+
+ private SQLExceptionConverter sec;
+ private ConnectionProvider provider;
+
+ private Connection connection;
+ private DatabaseMetaData metaData;
+
+ public void configure(ConnectionProvider provider, SQLExceptionConverter sec) {
+ this.provider = provider;
+ this.sec = sec;
+ }
+
+ public void close() {
+ metaData = null;
+ if(connection != null) {
+ try {
+ provider.closeConnection(connection);
+ }
+ catch (SQLException e) {
+ getSQLExceptionConverter().convert(e, "Problem while closing connection", null);
+ }
+ }
+ provider = null;
+ sec = null;
+ }
+
+ protected DatabaseMetaData getMetaData() throws JDBCBinderException {
+ if (metaData == null) {
+ try {
+ metaData = getConnection().getMetaData();
+ }
+ catch (SQLException e) {
+ throw getSQLExceptionConverter().convert(e, "Getting database metadata", null);
+ }
+ }
+ return metaData;
+ }
+
+ protected String getDatabaseStructure(String catalog, String schema) {
+ ResultSet schemaRs = null;
+ ResultSet catalogRs = null;
+ String nl = System.getProperty("line.separator");
+ StringBuffer sb = new StringBuffer(nl);
+ // Let's give the user some feedback. The exception
+ // is probably related to incorrect schema configuration.
+ sb.append("Configured schema:").append(schema).append(nl);
+ sb.append("Configured catalog:").append(catalog ).append(nl);
+
+ try {
+ schemaRs = getMetaData().getSchemas();
+ sb.append("Available schemas:").append(nl);
+ while (schemaRs.next() ) {
+ sb.append(" ").append(schemaRs.getString("TABLE_SCHEM") ).append(nl);
+ }
+ }
+ catch (SQLException e2) {
+ log.warn("Could not get schemas", e2);
+ sb.append(" <SQLException while getting schemas>").append(nl);
+ }
+ finally {
+ try {
+ schemaRs.close();
+ }
+ catch (Exception ignore) {
+ }
+ }
+
+ try {
+ catalogRs = getMetaData().getCatalogs();
+ sb.append("Available catalogs:").append(nl);
+ while (catalogRs.next() ) {
+ sb.append(" ").append(catalogRs.getString("TABLE_CAT") ).append(nl);
+ }
+ }
+ catch (SQLException e2) {
+ log.warn("Could not get catalogs", e2);
+ sb.append(" <SQLException while getting catalogs>").append(nl);
+ }
+ finally {
+ try {
+ catalogRs.close();
+ }
+ catch (Exception ignore) {
+ }
+ }
+ return sb.toString();
+ }
+
+ protected Connection getConnection() throws SQLException {
+ if(connection==null) {
+ connection = provider.getConnection();
+ }
+ return connection;
+ }
+
+ public void close(Iterator iterator) {
+ if(iterator instanceof ResultSetIterator) {
+ ((ResultSetIterator)iterator).close();
+ }
+ }
+
+ protected SQLExceptionConverter getSQLExceptionConverter() {
+ return sec;
+ }
+
+ public boolean needQuote(String name) {
+
+ // TODO: use jdbc metadata to decide on this. but for now we just handle the most typical cases.
+ if(name.indexOf('-')>0) return true;
+ if(name.indexOf(' ')>0) return true;
+ return false;
+ }
+}
Modified: trunk/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/dialect/JDBCMetaDataDialect.java
===================================================================
--- trunk/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/dialect/JDBCMetaDataDialect.java 2006-09-18 21:48:12 UTC (rev 10492)
+++ trunk/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/dialect/JDBCMetaDataDialect.java 2006-09-19 16:02:12 UTC (rev 10493)
@@ -1,7 +1,5 @@
package org.hibernate.cfg.reveng.dialect;
-import java.sql.Connection;
-import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
@@ -9,11 +7,6 @@
import java.util.Iterator;
import java.util.Map;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.hibernate.cfg.JDBCBinderException;
-import org.hibernate.connection.ConnectionProvider;
-import org.hibernate.exception.SQLExceptionConverter;
import org.hibernate.mapping.Table;
/**
@@ -22,54 +15,15 @@
* @author Max Rydahl Andersen
*
*/
-public class JDBCMetaDataDialect implements MetaDataDialect {
+public class JDBCMetaDataDialect extends AbstractMetaDataDialect {
- private static final Log log = LogFactory.getLog(JDBCMetaDataDialect.class);
-
- private SQLExceptionConverter sec;
- private ConnectionProvider provider;
- private Connection connection;
- private DatabaseMetaData metaData;
-
-
- public void configure(ConnectionProvider provider, SQLExceptionConverter sec) {
- this.provider = provider;
- this.sec = sec;
- }
-
- public void close() {
- metaData = null;
- if(connection != null) {
- try {
- provider.closeConnection(connection);
- }
- catch (SQLException e) {
- sec.convert(e, "Problem while closing connection", null);
- }
- }
- provider = null;
- sec = null;
- }
-
- protected DatabaseMetaData getMetaData() throws JDBCBinderException {
- if (metaData == null) {
- try {
- metaData = getConnection().getMetaData();
- }
- catch (SQLException e) {
- throw sec.convert(e, "Getting database metadata", null);
- }
- }
- return metaData;
- }
-
public Iterator getTables(final String catalog, final String schema, String table) {
try {
log.debug("getTables(" + catalog + "." + schema + "." + table + ")");
ResultSet tableRs = getMetaData().getTables(catalog , schema , table, new String[] { "TABLE", "VIEW" });
- return new ResultSetIterator(tableRs, sec) {
+ return new ResultSetIterator(tableRs, getSQLExceptionConverter()) {
Map element = new HashMap();
protected Object convertRow(ResultSet tableRs) throws SQLException {
@@ -83,7 +37,7 @@
// schemaRs and catalogRs are only used for error reporting if
// we get an exception
String databaseStructure = getDatabaseStructure( catalog, schema );
- throw sec.convert( e,
+ throw getSQLExceptionConverter().convert( e,
"Could not get list of tables from database. Probably a JDBC driver problem. "
+ databaseStructure, null );
}
@@ -91,7 +45,7 @@
} catch (SQLException e) {
// schemaRs and catalogRs are only used for error reporting if we get an exception
String databaseStructure = getDatabaseStructure(catalog,schema);
- throw sec.convert(e, "Could not get list of tables from database. Probably a JDBC driver problem. " + databaseStructure, null);
+ throw getSQLExceptionConverter().convert(e, "Could not get list of tables from database. Probably a JDBC driver problem. " + databaseStructure, null);
}
}
@@ -116,68 +70,15 @@
System.out.println();
}
- private String getDatabaseStructure(String catalog, String schema) {
- ResultSet schemaRs = null;
- ResultSet catalogRs = null;
- String nl = System.getProperty("line.separator");
- StringBuffer sb = new StringBuffer(nl);
- // Let's give the user some feedback. The exception
- // is probably related to incorrect schema configuration.
- sb.append("Configured schema:").append(schema).append(nl);
- sb.append("Configured catalog:").append(catalog ).append(nl);
+
+
- try {
- schemaRs = getMetaData().getSchemas();
- sb.append("Available schemas:").append(nl);
- while (schemaRs.next() ) {
- sb.append(" ").append(schemaRs.getString("TABLE_SCHEM") ).append(nl);
- }
- }
- catch (SQLException e2) {
- log.warn("Could not get schemas", e2);
- sb.append(" <SQLException while getting schemas>").append(nl);
- }
- finally {
- try {
- schemaRs.close();
- }
- catch (Exception ignore) {
- }
- }
-
- try {
- catalogRs = getMetaData().getCatalogs();
- sb.append("Available catalogs:").append(nl);
- while (catalogRs.next() ) {
- sb.append(" ").append(catalogRs.getString("TABLE_CAT") ).append(nl);
- }
- }
- catch (SQLException e2) {
- log.warn("Could not get catalogs", e2);
- sb.append(" <SQLException while getting catalogs>").append(nl);
- }
- finally {
- try {
- catalogRs.close();
- }
- catch (Exception ignore) {
- }
- }
- return sb.toString();
- }
-
- public void close(Iterator iterator) {
- if(iterator instanceof ResultSetIterator) {
- ((ResultSetIterator)iterator).close();
- }
- }
-
public Iterator getIndexInfo(final String catalog, final String schema, final String table) {
try {
log.debug("getIndexInfo(" + catalog + "." + schema + "." + table + ")");
ResultSet tableRs = getMetaData().getIndexInfo(catalog , schema , table, false, true);
- return new ResultSetIterator(tableRs, sec) {
+ return new ResultSetIterator(tableRs, getSQLExceptionConverter()) {
Map element = new HashMap();
protected Object convertRow(ResultSet rs) throws SQLException {
@@ -190,11 +91,11 @@
return element;
}
protected Throwable handleSQLException(SQLException e) {
- throw sec.convert(e, "Exception while getting index info for " + Table.qualify(catalog, schema, table), null);
+ throw getSQLExceptionConverter().convert(e, "Exception while getting index info for " + Table.qualify(catalog, schema, table), null);
}
};
} catch (SQLException e) {
- throw sec.convert(e, "Exception while getting index info for " + Table.qualify(catalog, schema, table), null);
+ throw getSQLExceptionConverter().convert(e, "Exception while getting index info for " + Table.qualify(catalog, schema, table), null);
}
}
@@ -209,7 +110,7 @@
log.debug("getColumns(" + catalog + "." + schema + "." + table + "." + column + ")");
ResultSet tableRs = getMetaData().getColumns(catalog, schema, table, column);
- return new ResultSetIterator(tableRs, sec) {
+ return new ResultSetIterator(tableRs, getSQLExceptionConverter()) {
Map element = new HashMap();
protected Object convertRow(ResultSet rs) throws SQLException {
@@ -225,11 +126,11 @@
return element;
}
protected Throwable handleSQLException(SQLException e) {
- throw sec.convert(e, "Error while reading column meta data for " + Table.qualify(catalog, schema, table), null);
+ throw getSQLExceptionConverter().convert(e, "Error while reading column meta data for " + Table.qualify(catalog, schema, table), null);
}
};
} catch (SQLException e) {
- throw sec.convert(e, "Error while reading column meta data for " + Table.qualify(catalog, schema, table), null);
+ throw getSQLExceptionConverter().convert(e, "Error while reading column meta data for " + Table.qualify(catalog, schema, table), null);
}
}
@@ -238,7 +139,7 @@
log.debug("getPrimaryKeys(" + catalog + "." + schema + "." + table + ")");
ResultSet tableRs = getMetaData().getPrimaryKeys(catalog, schema, table);
- return new ResultSetIterator(tableRs, sec) {
+ return new ResultSetIterator(tableRs, getSQLExceptionConverter()) {
Map element = new HashMap();
protected Object convertRow(ResultSet rs) throws SQLException {
@@ -250,11 +151,11 @@
return element;
}
protected Throwable handleSQLException(SQLException e) {
- throw sec.convert(e, "Error while reading primary key meta data for " + Table.qualify(catalog, schema, table), null);
+ throw getSQLExceptionConverter().convert(e, "Error while reading primary key meta data for " + Table.qualify(catalog, schema, table), null);
}
};
} catch (SQLException e) {
- throw sec.convert(e, "Error while reading primary key meta data for " + Table.qualify(catalog, schema, table), null);
+ throw getSQLExceptionConverter().convert(e, "Error while reading primary key meta data for " + Table.qualify(catalog, schema, table), null);
}
}
@@ -263,7 +164,7 @@
log.debug("getExportedKeys(" + catalog + "." + schema + "." + table + ")");
ResultSet tableRs = getMetaData().getExportedKeys(catalog, schema, table);
- return new ResultSetIterator(tableRs, sec) {
+ return new ResultSetIterator(tableRs, getSQLExceptionConverter()) {
Map element = new HashMap();
protected Object convertRow(ResultSet rs) throws SQLException {
@@ -281,25 +182,13 @@
return element;
}
protected Throwable handleSQLException(SQLException e) {
- throw sec.convert(e, "Error while reading exported keys meta data for " + Table.qualify(catalog, schema, table), null);
+ throw getSQLExceptionConverter().convert(e, "Error while reading exported keys meta data for " + Table.qualify(catalog, schema, table), null);
}
};
} catch (SQLException e) {
- throw sec.convert(e, "Error while reading exported keys meta data for " + Table.qualify(catalog, schema, table), null);
+ throw getSQLExceptionConverter().convert(e, "Error while reading exported keys meta data for " + Table.qualify(catalog, schema, table), null);
}
}
- protected Connection getConnection() throws SQLException {
- if(connection==null) {
- connection = provider.getConnection();
- }
- return connection;
- }
-
- public boolean needQuote(String name) {
- // TODO: use jdbc metadata to decide on this. but for now we just handle the most typical cases.
- if(name.indexOf('-')>0) return true;
- if(name.indexOf(' ')>0) return true;
- return false;
- }
+
}
Modified: trunk/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/dialect/OracleMetaDataDialect.java
===================================================================
--- trunk/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/dialect/OracleMetaDataDialect.java 2006-09-18 21:48:12 UTC (rev 10492)
+++ trunk/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/dialect/OracleMetaDataDialect.java 2006-09-19 16:02:12 UTC (rev 10493)
@@ -1,8 +1,6 @@
package org.hibernate.cfg.reveng.dialect;
-import java.sql.Connection;
-import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
@@ -10,11 +8,6 @@
import java.util.Iterator;
import java.util.Map;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.hibernate.cfg.JDBCBinderException;
-import org.hibernate.connection.ConnectionProvider;
-import org.hibernate.exception.SQLExceptionConverter;
import org.hibernate.mapping.Table;
/**
@@ -23,48 +16,11 @@
*
* @author David Channon
*/
-public class OracleMetaDataDialect implements MetaDataDialect {
+public class OracleMetaDataDialect extends AbstractMetaDataDialect {
- private static final Log log = LogFactory.getLog(OracleMetaDataDialect.class);
-
- private SQLExceptionConverter sec;
- private ConnectionProvider provider;
- private Connection connection;
- private DatabaseMetaData metaData;
-
-
- public void configure(ConnectionProvider provider, SQLExceptionConverter sec) {
- this.provider = provider;
- this.sec = sec;
- }
- public void close() {
- metaData = null;
- if(connection != null) {
- try {
- provider.closeConnection(connection);
- }
- catch (SQLException e) {
- sec.convert(e, "Problem while closing connection", null);
- }
- }
- provider = null;
- sec = null;
- }
- protected DatabaseMetaData getMetaData() throws JDBCBinderException {
- if (metaData == null) {
- try {
- metaData = getConnection().getMetaData();
- }
- catch (SQLException e) {
- throw sec.convert(e, "Getting database metadata", null);
- }
- }
- return metaData;
- }
-
public Iterator getTables(final String catalog, final String schema, String table) {
try {
log.debug("getTables(" + catalog + "." + schema + "." + table + ")");
@@ -100,7 +56,7 @@
ResultSet tableRs = stmt.executeQuery(query.toString());
- return new ResultSetIterator(tableRs, sec) {
+ return new ResultSetIterator(tableRs, getSQLExceptionConverter()) {
Map element = new HashMap();
protected Object convertRow(ResultSet tableRs) throws SQLException {
@@ -116,7 +72,7 @@
// schemaRs and catalogRs are only used for error reporting if
// we get an exception
String databaseStructure = getDatabaseStructure( catalog, schema );
- throw sec.convert( e,
+ throw getSQLExceptionConverter().convert( e,
"Could not get list of tables from database. Probably a JDBC driver problem. "
+ databaseStructure, null );
}
@@ -124,66 +80,10 @@
} catch (SQLException e) {
// schemaRs and catalogRs are only used for error reporting if we get an exception
String databaseStructure = getDatabaseStructure(catalog,schema);
- throw sec.convert(e, "Could not get list of tables from database. Probably a JDBC driver problem. " + databaseStructure, null);
+ throw getSQLExceptionConverter().convert(e, "Could not get list of tables from database. Probably a JDBC driver problem. " + databaseStructure, null);
}
}
- private String getDatabaseStructure(String catalog, String schema) {
- ResultSet schemaRs = null;
- ResultSet catalogRs = null;
- String nl = System.getProperty("line.separator");
- StringBuffer sb = new StringBuffer(nl);
- // Let's give the user some feedback. The exception
- // is probably related to incorrect schema configuration.
- sb.append("Configured schema:").append(schema).append(nl);
- sb.append("Configured catalog:").append(catalog ).append(nl);
-
- try {
- schemaRs = getMetaData().getSchemas();
- sb.append("Available schemas:").append(nl);
- while (schemaRs.next() ) {
- sb.append(" ").append(schemaRs.getString("TABLE_SCHEM") ).append(nl);
- }
- }
- catch (SQLException e2) {
- log.warn("Could not get schemas", e2);
- sb.append(" <SQLException while getting schemas>").append(nl);
- }
- finally {
- try {
- schemaRs.close();
- }
- catch (Exception ignore) {
- }
- }
-
- try {
- catalogRs = getMetaData().getCatalogs();
- sb.append("Available catalogs:").append(nl);
- while (catalogRs.next() ) {
- sb.append(" ").append(catalogRs.getString("TABLE_CAT") ).append(nl);
- }
- }
- catch (SQLException e2) {
- log.warn("Could not get catalogs", e2);
- sb.append(" <SQLException while getting catalogs>").append(nl);
- }
- finally {
- try {
- catalogRs.close();
- }
- catch (Exception ignore) {
- }
- }
- return sb.toString();
- }
-
- public void close(Iterator iterator) {
- if(iterator instanceof ResultSetIterator) {
- ((ResultSetIterator)iterator).close();
- }
- }
-
public Iterator getIndexInfo(final String catalog, final String schema, final String table) {
try {
log.debug("getIndexInfo(" + catalog + "." + schema + "." + table + ")");
@@ -208,14 +108,14 @@
ResultSet indexRs = stmt.executeQuery(query.toString());
- return new ResultSetIterator(indexRs, sec) {
+ return new ResultSetIterator(indexRs, getSQLExceptionConverter()) {
Map element = new HashMap();
protected Object convertRow(ResultSet rs) throws SQLException {
element.clear();
element.put("COLUMN_NAME", rs.getString(1));
element.put("TYPE", new Short((short)1)); // CLUSTERED INDEX
- element.put("NON_UNIQUE", rs.getString(2));
+ element.put("NON_UNIQUE", Boolean.valueOf( rs.getString(2) ));
element.put("TABLE_SCHEM", rs.getString(3));
element.put("INDEX_NAME", rs.getString(4));
element.put("TABLE_CAT", null);
@@ -224,11 +124,11 @@
return element;
}
protected Throwable handleSQLException(SQLException e) {
- throw sec.convert(e, "Exception while getting index info for " + Table.qualify(catalog, schema, table), null);
+ throw getSQLExceptionConverter().convert(e, "Exception while getting index info for " + Table.qualify(catalog, schema, table), null);
}
};
} catch (SQLException e) {
- throw sec.convert(e, "Exception while getting index info for " + Table.qualify(catalog, schema, table), null);
+ throw getSQLExceptionConverter().convert(e, "Exception while getting index info for " + Table.qualify(catalog, schema, table), null);
}
}
@@ -269,7 +169,7 @@
ResultSet columnRs = stmt.executeQuery(query.toString());
- return new ResultSetIterator(columnRs, sec) {
+ return new ResultSetIterator(columnRs, getSQLExceptionConverter()) {
Map element = new HashMap();
protected Object convertRow(ResultSet rs) throws SQLException {
@@ -287,11 +187,11 @@
return element;
}
protected Throwable handleSQLException(SQLException e) {
- throw sec.convert(e, "Error while reading column meta data for " + Table.qualify(catalog, schema, table), null);
+ throw getSQLExceptionConverter().convert(e, "Error while reading column meta data for " + Table.qualify(catalog, schema, table), null);
}
};
} catch (SQLException e) {
- throw sec.convert(e, "Error while reading column meta data for " + Table.qualify(catalog, schema, table), null);
+ throw getSQLExceptionConverter().convert(e, "Error while reading column meta data for " + Table.qualify(catalog, schema, table), null);
}
}
@@ -321,7 +221,7 @@
ResultSet pkeyRs = stmt.executeQuery(query.toString());
- return new ResultSetIterator(pkeyRs, sec) {
+ return new ResultSetIterator(pkeyRs, getSQLExceptionConverter()) {
Map element = new HashMap();
protected Object convertRow(ResultSet rs) throws SQLException {
@@ -335,11 +235,11 @@
return element;
}
protected Throwable handleSQLException(SQLException e) {
- throw sec.convert(e, "Error while reading primary key meta data for " + Table.qualify(catalog, schema, table), null);
+ throw getSQLExceptionConverter().convert(e, "Error while reading primary key meta data for " + Table.qualify(catalog, schema, table), null);
}
};
} catch (SQLException e) {
- throw sec.convert(e, "Error while reading primary key meta data for " + Table.qualify(catalog, schema, table), null);
+ throw getSQLExceptionConverter().convert(e, "Error while reading primary key meta data for " + Table.qualify(catalog, schema, table), null);
}
}
@@ -377,7 +277,7 @@
ResultSet pExportRs = stmt.executeQuery(query.toString());
- return new ResultSetIterator(pExportRs, sec) {
+ return new ResultSetIterator(pExportRs, getSQLExceptionConverter()) {
Map element = new HashMap();
protected Object convertRow(ResultSet rs) throws SQLException {
@@ -395,25 +295,12 @@
return element;
}
protected Throwable handleSQLException(SQLException e) {
- throw sec.convert(e, "Error while reading exported keys meta data for " + Table.qualify(catalog, schema, table), null);
+ throw getSQLExceptionConverter().convert(e, "Error while reading exported keys meta data for " + Table.qualify(catalog, schema, table), null);
}
};
} catch (SQLException e) {
- throw sec.convert(e, "Error while reading exported keys meta data for " + Table.qualify(catalog, schema, table), null);
+ throw getSQLExceptionConverter().convert(e, "Error while reading exported keys meta data for " + Table.qualify(catalog, schema, table), null);
}
}
- protected Connection getConnection() throws SQLException {
- if(connection==null) {
- connection = provider.getConnection();
- }
- return connection;
- }
-
- public boolean needQuote(String name) {
- // TODO: use jdbc metadata to decide on this. but for now we just handle the most typical cases.
- if(name.indexOf('-')>0) return true;
- if(name.indexOf(' ')>0) return true;
- return false;
- }
}
18 years, 4 months
Hibernate SVN: r10492 - trunk/HibernateExt/ejb/src/test/org/hibernate/ejb/test/transaction
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2006-09-18 17:48:12 -0400 (Mon, 18 Sep 2006)
New Revision: 10492
Modified:
trunk/HibernateExt/ejb/src/test/org/hibernate/ejb/test/transaction/FlushAndTransactionTest.java
Log:
more tests
Modified: trunk/HibernateExt/ejb/src/test/org/hibernate/ejb/test/transaction/FlushAndTransactionTest.java
===================================================================
--- trunk/HibernateExt/ejb/src/test/org/hibernate/ejb/test/transaction/FlushAndTransactionTest.java 2006-09-17 21:05:01 UTC (rev 10491)
+++ trunk/HibernateExt/ejb/src/test/org/hibernate/ejb/test/transaction/FlushAndTransactionTest.java 2006-09-18 21:48:12 UTC (rev 10492)
@@ -1,6 +1,7 @@
//$Id$
package org.hibernate.ejb.test.transaction;
+import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.LockModeType;
import javax.persistence.RollbackException;
@@ -182,6 +183,23 @@
em.close();
}
+ public void testTransactionCommitDoesNotFlush() throws Exception {
+ EntityManager em = factory.createEntityManager();
+ em.getTransaction().begin();
+ Book book = new Book();
+ book.name = "Java for Dummies";
+ em.persist( book );
+ em.getTransaction().commit();
+ em.close();
+ em = factory.createEntityManager();
+ em.getTransaction().begin();
+ List result = em.createQuery("select book from Book book where book.name = :title").
+ setParameter( "title", book.name ).getResultList();
+ assertEquals( "EntityManager.commit() should trigger a flush()", 1, result.size() );
+ em.getTransaction().commit();
+ em.close();
+ }
+
public void testRollbackOnlyOnPersistenceException() throws Exception {
Book book = new Book();
book.name = "Stolen keys";
18 years, 4 months
Hibernate SVN: r10491 - branches/Branch_3_2/Hibernate3/doc/reference/en/modules trunk/Hibernate3/doc/reference/en/modules
by hibernate-commits@lists.jboss.org
Author: christian.bauer(a)jboss.com
Date: 2006-09-17 17:05:01 -0400 (Sun, 17 Sep 2006)
New Revision: 10491
Modified:
branches/Branch_3_2/Hibernate3/doc/reference/en/modules/query_hql.xml
trunk/Hibernate3/doc/reference/en/modules/query_hql.xml
Log:
Documented HHH-1615
Modified: branches/Branch_3_2/Hibernate3/doc/reference/en/modules/query_hql.xml
===================================================================
--- branches/Branch_3_2/Hibernate3/doc/reference/en/modules/query_hql.xml 2006-09-17 15:25:26 UTC (rev 10490)
+++ branches/Branch_3_2/Hibernate3/doc/reference/en/modules/query_hql.xml 2006-09-17 21:05:01 UTC (rev 10491)
@@ -821,7 +821,7 @@
</para>
</sect1>
- <sect1 id="queryhql-grouping">
+ <sect1 id="queryhql-grouping" revision="1">
<title>The group by clause</title>
<para>
@@ -854,13 +854,17 @@
<programlisting><![CDATA[select cat
from Cat cat
join cat.kittens kitten
-group by cat
+group by cat.id, cat.name, cat.other, cat.properties
having avg(kitten.weight) > 100
order by count(kitten) asc, sum(kitten.weight) desc]]></programlisting>
<para>
Note that neither the <literal>group by</literal> clause nor the
<literal>order by</literal> clause may contain arithmetic expressions.
+ Also note that Hibernate currently does not expand a grouped entity,
+ so you can't write <literal>group by cat</literal> if all properties
+ of <literal>cat</literal> are non-aggregated. You have to list all
+ non-aggregated properties explicitly.
</para>
</sect1>
Modified: trunk/Hibernate3/doc/reference/en/modules/query_hql.xml
===================================================================
--- trunk/Hibernate3/doc/reference/en/modules/query_hql.xml 2006-09-17 15:25:26 UTC (rev 10490)
+++ trunk/Hibernate3/doc/reference/en/modules/query_hql.xml 2006-09-17 21:05:01 UTC (rev 10491)
@@ -821,7 +821,7 @@
</para>
</sect1>
- <sect1 id="queryhql-grouping">
+ <sect1 id="queryhql-grouping" revision="1">
<title>The group by clause</title>
<para>
@@ -854,13 +854,17 @@
<programlisting><![CDATA[select cat
from Cat cat
join cat.kittens kitten
-group by cat
+group by cat.id, cat.name, cat.other, cat.properties
having avg(kitten.weight) > 100
order by count(kitten) asc, sum(kitten.weight) desc]]></programlisting>
<para>
Note that neither the <literal>group by</literal> clause nor the
<literal>order by</literal> clause may contain arithmetic expressions.
+ Also note that Hibernate currently does not expand a grouped entity,
+ so you can't write <literal>group by cat</literal> if all properties
+ of <literal>cat</literal> are non-aggregated. You have to list all
+ non-aggregated properties explicitly.
</para>
</sect1>
18 years, 4 months
Hibernate SVN: r10490 - trunk/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/dialect
by hibernate-commits@lists.jboss.org
Author: dchannon
Date: 2006-09-17 11:25:26 -0400 (Sun, 17 Sep 2006)
New Revision: 10490
Added:
trunk/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/dialect/OracleMetaDataDialect.java
Log:
Oracle specialist rev-eng database dialect. This should avoid a few Oracle JDBC driver bugs and provide performance improvements on large schemas.
Added: trunk/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/dialect/OracleMetaDataDialect.java
===================================================================
--- trunk/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/dialect/OracleMetaDataDialect.java 2006-09-16 21:19:50 UTC (rev 10489)
+++ trunk/HibernateExt/tools/src/java/org/hibernate/cfg/reveng/dialect/OracleMetaDataDialect.java 2006-09-17 15:25:26 UTC (rev 10490)
@@ -0,0 +1,419 @@
+
+package org.hibernate.cfg.reveng.dialect;
+
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.hibernate.cfg.JDBCBinderException;
+import org.hibernate.connection.ConnectionProvider;
+import org.hibernate.exception.SQLExceptionConverter;
+import org.hibernate.mapping.Table;
+
+/**
+ * Oracle Specialised MetaData dialect that uses standard JDBC
+ * and querys on the Data Dictionary for reading metadata.
+ *
+ * @author David Channon
+ */
+public class OracleMetaDataDialect implements MetaDataDialect {
+
+ private static final Log log = LogFactory.getLog(OracleMetaDataDialect.class);
+
+ private SQLExceptionConverter sec;
+ private ConnectionProvider provider;
+
+ private Connection connection;
+ private DatabaseMetaData metaData;
+
+
+ public void configure(ConnectionProvider provider, SQLExceptionConverter sec) {
+ this.provider = provider;
+ this.sec = sec;
+ }
+
+ public void close() {
+ metaData = null;
+ if(connection != null) {
+ try {
+ provider.closeConnection(connection);
+ }
+ catch (SQLException e) {
+ sec.convert(e, "Problem while closing connection", null);
+ }
+ }
+ provider = null;
+ sec = null;
+ }
+
+ protected DatabaseMetaData getMetaData() throws JDBCBinderException {
+ if (metaData == null) {
+ try {
+ metaData = getConnection().getMetaData();
+ }
+ catch (SQLException e) {
+ throw sec.convert(e, "Getting database metadata", null);
+ }
+ }
+ return metaData;
+ }
+
+ public Iterator getTables(final String catalog, final String schema, String table) {
+ try {
+ log.debug("getTables(" + catalog + "." + schema + "." + table + ")");
+ // Collect both Tables and Views from the 'ALL' data dicitonary tables.
+ // Note: This will potentally collect more tables that the jdbc meta data
+ Statement stmt = this.getConnection().createStatement();
+ StringBuffer query = new StringBuffer();
+ query.append("select table_name, owner, 'TABLE' from all_tables ");
+ if (schema != null || table != null)
+ query.append("where ");
+ if (schema != null) {
+ query.append("owner='" + schema + "' ");
+ }
+ if (table != null) {
+ if (schema != null)
+ query.append("and ");
+ query.append("table_name = '" + table + "' ");
+ }
+ query.append("union all ");
+ query.append("select view_name, owner, 'VIEW' from all_views ");
+ if (schema != null || table != null)
+ query.append("where ");
+ if (schema != null) {
+ query.append("owner='" + schema + "' ");
+ }
+ if (table != null) {
+ if (schema != null)
+ query.append("and ");
+ query.append("view_name = '" + table + "' ");
+ }
+ if (log.isDebugEnabled())
+ log.debug("getTables Query:" + query.toString());
+
+ ResultSet tableRs = stmt.executeQuery(query.toString());
+
+ return new ResultSetIterator(tableRs, sec) {
+
+ Map element = new HashMap();
+ protected Object convertRow(ResultSet tableRs) throws SQLException {
+ element.clear();
+ element.put("TABLE_NAME", tableRs.getString(1));
+ element.put("TABLE_SCHEM", tableRs.getString(2));
+ element.put("TABLE_CAT", null);
+ element.put("TABLE_TYPE", tableRs.getString(3));
+ element.put("REMARKS", null);
+ return element;
+ }
+ protected Throwable handleSQLException(SQLException e) {
+ // schemaRs and catalogRs are only used for error reporting if
+ // we get an exception
+ String databaseStructure = getDatabaseStructure( catalog, schema );
+ throw sec.convert( e,
+ "Could not get list of tables from database. Probably a JDBC driver problem. "
+ + databaseStructure, null );
+ }
+ };
+ } catch (SQLException e) {
+ // schemaRs and catalogRs are only used for error reporting if we get an exception
+ String databaseStructure = getDatabaseStructure(catalog,schema);
+ throw sec.convert(e, "Could not get list of tables from database. Probably a JDBC driver problem. " + databaseStructure, null);
+ }
+ }
+
+ private String getDatabaseStructure(String catalog, String schema) {
+ ResultSet schemaRs = null;
+ ResultSet catalogRs = null;
+ String nl = System.getProperty("line.separator");
+ StringBuffer sb = new StringBuffer(nl);
+ // Let's give the user some feedback. The exception
+ // is probably related to incorrect schema configuration.
+ sb.append("Configured schema:").append(schema).append(nl);
+ sb.append("Configured catalog:").append(catalog ).append(nl);
+
+ try {
+ schemaRs = getMetaData().getSchemas();
+ sb.append("Available schemas:").append(nl);
+ while (schemaRs.next() ) {
+ sb.append(" ").append(schemaRs.getString("TABLE_SCHEM") ).append(nl);
+ }
+ }
+ catch (SQLException e2) {
+ log.warn("Could not get schemas", e2);
+ sb.append(" <SQLException while getting schemas>").append(nl);
+ }
+ finally {
+ try {
+ schemaRs.close();
+ }
+ catch (Exception ignore) {
+ }
+ }
+
+ try {
+ catalogRs = getMetaData().getCatalogs();
+ sb.append("Available catalogs:").append(nl);
+ while (catalogRs.next() ) {
+ sb.append(" ").append(catalogRs.getString("TABLE_CAT") ).append(nl);
+ }
+ }
+ catch (SQLException e2) {
+ log.warn("Could not get catalogs", e2);
+ sb.append(" <SQLException while getting catalogs>").append(nl);
+ }
+ finally {
+ try {
+ catalogRs.close();
+ }
+ catch (Exception ignore) {
+ }
+ }
+ return sb.toString();
+ }
+
+ public void close(Iterator iterator) {
+ if(iterator instanceof ResultSetIterator) {
+ ((ResultSetIterator)iterator).close();
+ }
+ }
+
+ public Iterator getIndexInfo(final String catalog, final String schema, final String table) {
+ try {
+ log.debug("getIndexInfo(" + catalog + "." + schema + "." + table + ")");
+ // Collect both Indexes from the 'ALL' data dicitonary table.
+ // It is assumed that atleast the TABLE name is supplied.
+ Statement stmt = this.getConnection().createStatement();
+ StringBuffer query = new StringBuffer();
+
+ query.append("select a.column_name, decode(b.uniqueness,'UNIQUE','false','true'), a.index_owner, a.index_name, a.table_name ");
+ query.append("from all_ind_columns a, all_indexes b ");
+ query.append("where a.table_name = b.table_name ");
+ query.append("AND a.table_owner = b.table_owner ");
+ query.append("AND a.index_name = b.index_name ");
+ if (schema != null) {
+ query.append("AND a.table_owner='" + schema + "' ");
+ }
+ query.append("AND a.table_name = '" + table + "' ");
+ query.append("order by a.table_name, a.column_position ");
+
+ if (log.isDebugEnabled())
+ log.debug("getIndexInfo Query:" + query.toString());
+
+ ResultSet indexRs = stmt.executeQuery(query.toString());
+
+ return new ResultSetIterator(indexRs, sec) {
+
+ Map element = new HashMap();
+ protected Object convertRow(ResultSet rs) throws SQLException {
+ element.clear();
+ element.put("COLUMN_NAME", rs.getString(1));
+ element.put("TYPE", new Short((short)1)); // CLUSTERED INDEX
+ element.put("NON_UNIQUE", rs.getString(2));
+ element.put("TABLE_SCHEM", rs.getString(3));
+ element.put("INDEX_NAME", rs.getString(4));
+ element.put("TABLE_CAT", null);
+ element.put("TABLE_NAME", rs.getString(5));
+
+ return element;
+ }
+ protected Throwable handleSQLException(SQLException e) {
+ throw sec.convert(e, "Exception while getting index info for " + Table.qualify(catalog, schema, table), null);
+ }
+ };
+ } catch (SQLException e) {
+ throw sec.convert(e, "Exception while getting index info for " + Table.qualify(catalog, schema, table), null);
+ }
+ }
+
+ public Iterator getColumns(final String catalog, final String schema, final String table, String column) {
+ try {
+ log.debug("getColumns(" + catalog + "." + schema + "." + table + "." + column + ")");
+ // Collect Columns from the 'ALL' data dicitonary table.
+ // A decode is used to map the type name to the JDBC Type ID
+ Statement stmt = this.getConnection().createStatement();
+ StringBuffer query = new StringBuffer();
+
+ query.append("select column_name, owner, decode(nullable,'N',0,1), ");
+ query.append("decode(data_type, 'FLOAT',decode(data_precision,null, data_length, data_precision), 'NUMBER', decode(data_precision,null, data_length, data_precision), data_length), ");
+ query.append("decode(data_type,'CHAR',1, 'DATE',91, 'FLOAT',6, 'LONG',-1, 'NUMBER',2, 'VARCHAR2',12, 'BFILE',-13, ");
+ query.append("'BLOB',2004, 'CLOB',2005, 'MLSLABEL',1111, 'NCHAR',1, 'NCLOB',2005, 'NVARCHAR2',12, ");
+ query.append("'RAW',-3, 'ROWID',1111, 'UROWID',1111, 'LONG RAW', -4, 'TIMESTAMP', 93, 'XMLTYPE',2005, 1111), ");
+ query.append("table_name, data_type, decode(data_scale, null, 0 ,data_scale) ");
+ query.append("from all_tab_columns ");
+ if (schema != null || table != null || column != null)
+ query.append("where ");
+ if (schema != null) {
+ query.append("owner='" + schema + "' ");
+ }
+ if (table != null) {
+ if (schema != null)
+ query.append("and ");
+ query.append("table_name = '" + table + "' ");
+ }
+ if (column != null) {
+ if (schema != null || table != null)
+ query.append("and ");
+ query.append("column_name = '" + column + "' ");
+ }
+ query.append("order by column_id ");
+
+ if (log.isDebugEnabled())
+ log.debug("getIndexInfo Query:" + query.toString());
+
+ ResultSet columnRs = stmt.executeQuery(query.toString());
+
+ return new ResultSetIterator(columnRs, sec) {
+
+ Map element = new HashMap();
+ protected Object convertRow(ResultSet rs) throws SQLException {
+ element.clear();
+ element.put("COLUMN_NAME", rs.getString(1));
+ element.put("TABLE_SCHEM", rs.getString(2));
+ element.put("NULLABLE", new Integer(rs.getInt(3)));
+ element.put("COLUMN_SIZE", new Integer(rs.getInt(4)));
+ element.put("DATA_TYPE", new Integer(rs.getInt(5)));
+ element.put("TABLE_NAME", rs.getString(6));
+ element.put("TYPE_NAME", rs.getString(7));
+ element.put("DECIMAL_DIGITS", new Integer(rs.getInt(8)));
+ element.put("TABLE_CAT", null);
+ element.put("REMARKS", null);
+ return element;
+ }
+ protected Throwable handleSQLException(SQLException e) {
+ throw sec.convert(e, "Error while reading column meta data for " + Table.qualify(catalog, schema, table), null);
+ }
+ };
+ } catch (SQLException e) {
+ throw sec.convert(e, "Error while reading column meta data for " + Table.qualify(catalog, schema, table), null);
+ }
+ }
+
+ public Iterator getPrimaryKeys(final String catalog, final String schema, final String table) {
+ try {
+ log.debug("getPrimaryKeys(" + catalog + "." + schema + "." + table + ")");
+ // Collect PrimaryKeys from the 'ALL' data dicitonary tables.
+ Statement stmt = this.getConnection().createStatement();
+ StringBuffer query = new StringBuffer();
+
+ query.append("select c.table_name, c.column_name, c.position, c.constraint_name, c.owner ");
+ query.append("from all_cons_columns c, all_constraints k ");
+ query.append("where k.constraint_type = 'P' ");
+ query.append("AND k.constraint_name = c.constraint_name ");
+ query.append("AND k.table_name = c.table_name ");
+ query.append("AND k.owner = c.owner ");
+ if (schema != null) {
+ query.append("AND k.owner='" + schema + "' ");
+ }
+ if (table != null) {
+ query.append("AND k.table_name = '" + table + "' ");
+ }
+ query.append("order by c.table_name, c.constraint_name, c.position desc ");
+
+ if (log.isDebugEnabled())
+ log.debug("getPrimaryKeys Query:" + query.toString());
+
+ ResultSet pkeyRs = stmt.executeQuery(query.toString());
+
+ return new ResultSetIterator(pkeyRs, sec) {
+
+ Map element = new HashMap();
+ protected Object convertRow(ResultSet rs) throws SQLException {
+ element.clear();
+ element.put("TABLE_NAME", rs.getString(1));
+ element.put("COLUMN_NAME", rs.getString(2));
+ element.put("KEY_SEQ", new Short(rs.getShort(3)));
+ element.put("PK_NAME", rs.getString(4));
+ element.put("TABLE_SCHEM", rs.getString(5));
+ element.put("TABLE_CAT", null);
+ return element;
+ }
+ protected Throwable handleSQLException(SQLException e) {
+ throw sec.convert(e, "Error while reading primary key meta data for " + Table.qualify(catalog, schema, table), null);
+ }
+ };
+ } catch (SQLException e) {
+ throw sec.convert(e, "Error while reading primary key meta data for " + Table.qualify(catalog, schema, table), null);
+ }
+ }
+
+ public Iterator getExportedKeys(final String catalog, final String schema, final String table) {
+ try {
+ log.debug("getExportedKeys(" + catalog + "." + schema + "." + table + ")");
+ // Collect ExportedKeys from the 'ALL' data dicitonary tables.
+
+ Statement stmt = this.getConnection().createStatement();
+ StringBuffer query = new StringBuffer();
+
+ query.append("select p.table_name, p.owner, f.owner, f.table_name, fc.column_name, pc.column_name, f.constraint_name, fc.position ");
+ query.append("from all_cons_columns pc, all_constraints p, all_cons_columns fc, all_constraints f ");
+ query.append("where f.constraint_type = 'R' ");
+ query.append("AND p.owner = f.r_owner ");
+ query.append("AND p.constraint_name = f.r_constraint_name ");
+ query.append("AND p.constraint_type = 'P' ");
+ query.append("AND pc.owner = p.owner ");
+ query.append("AND pc.constraint_name = p.constraint_name ");
+ query.append("AND pc.table_name = p.table_name ");
+ query.append("AND fc.owner = f.owner ");
+ query.append("AND fc.constraint_name = f.constraint_name ");
+ query.append("AND fc.table_name = f.table_name ");
+ query.append("AND fc.position = pc.position ");
+ if (schema != null) {
+ query.append("AND p.owner='" + schema + "' ");
+ }
+ if (table != null) {
+ query.append("AND p.table_name = '" + table + "' ");
+ }
+ query.append("order by f.table_name, f.constraint_name, fc.position ");
+
+ if (log.isDebugEnabled())
+ log.debug("getExportedKeys Query:" + query.toString());
+
+ ResultSet pExportRs = stmt.executeQuery(query.toString());
+
+ return new ResultSetIterator(pExportRs, sec) {
+
+ Map element = new HashMap();
+ protected Object convertRow(ResultSet rs) throws SQLException {
+ element.clear();
+ element.put( "PKTABLE_NAME", rs.getString(1));
+ element.put( "PKTABLE_SCHEM", rs.getString(2));
+ element.put( "PKTABLE_CAT", null);
+ element.put( "FKTABLE_CAT", null);
+ element.put( "FKTABLE_SCHEM",rs.getString(3));
+ element.put( "FKTABLE_NAME", rs.getString(4));
+ element.put( "FKCOLUMN_NAME", rs.getString(5));
+ element.put( "PKCOLUMN_NAME", rs.getString(6));
+ element.put( "FK_NAME", rs.getString(7));
+ element.put( "KEY_SEQ", new Short(rs.getShort(8)));
+ return element;
+ }
+ protected Throwable handleSQLException(SQLException e) {
+ throw sec.convert(e, "Error while reading exported keys meta data for " + Table.qualify(catalog, schema, table), null);
+ }
+ };
+ } catch (SQLException e) {
+ throw sec.convert(e, "Error while reading exported keys meta data for " + Table.qualify(catalog, schema, table), null);
+ }
+ }
+
+ protected Connection getConnection() throws SQLException {
+ if(connection==null) {
+ connection = provider.getConnection();
+ }
+ return connection;
+ }
+
+ public boolean needQuote(String name) {
+ // TODO: use jdbc metadata to decide on this. but for now we just handle the most typical cases.
+ if(name.indexOf('-')>0) return true;
+ if(name.indexOf(' ')>0) return true;
+ return false;
+ }
+}
18 years, 4 months
Hibernate SVN: r10489 - tags/entitymanager_v3_2_0_CR2
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2006-09-16 17:19:50 -0400 (Sat, 16 Sep 2006)
New Revision: 10489
Added:
tags/entitymanager_v3_2_0_CR2/HibernateExt/
Log:
tags
Copied: tags/entitymanager_v3_2_0_CR2/HibernateExt (from rev 10488, trunk/HibernateExt)
18 years, 4 months