The Virtuoso Drivers for JDBC are available in "jar" file formats for JDBC 1.x, JDBC 2.x and JDBC 3.x specifications. These are Type 4 Drivers implying that utilization is simply a case of adding the relevant "jar" file to your CLASSPATH and then providing an appropriate JDBC URL format in order to establish a JDBC session with a local or remote Virtuoso server. It is important to note that when you make a JDBC connection to a Virtuoso Server, you do also have access to Native and External Virtuoso tables. Thus, you actually have a type 4 JDBC Driver for any number of different database types that have been linked into Virtuoso.
The JDBC 2 and JDBC 3 drivers also incorporate SSL encryption to enable very secure connections to the Virtuoso database.
These drivers are installed alongside the Virtuoso Server or as part of a Virtuoso Client components only installation. They are packaged as follows:
Driver Name | Java Package | "jar" File Archive | Default Location | Java Version |
---|---|---|---|---|
virtuoso.jdbc.Driver | virtuoso.jdbc | virtjdbc.jar | <virtuoso installation directory>\jdk11 | Java 1.1.x |
virtuoso.jdbc2.Driver | virtuoso.jdbc2 | virtjdbc2.jar | <virtuoso installation directory>\jdk12 | Java 1.2/1.3 |
virtuoso.jdbc3.Driver used for Java 1.4 and Java 1.5 | virtuoso.jdbc3 | virtjdbc3.jar | <virtuoso installation directory>\jdk13 | Java 1.4 |
virtuoso.jdbc4.Driver used for Java 1.6 | virtuoso.jdbc4 | virtjdbc4.jar | <virtuoso installation directory>\jdk14 | Java 1.6 |
JDBC compliant applications and applets connect to JDBC Drivers using JDBC Uniform Resource Locators (URLs). Although there are two Virtuoso Drivers for JDBC, both share the same JDBC URL format.
The Virtuoso Driver for JDBC URL format takes the following form:
jdbc:virtuoso://<Hostname>:<Port#>/DATABASE=<dbname>/UID=<user name>/PWD=<password>/ CERT=<certificate_alias>/KPATH=<keystore_path>/PASS=<keystore_password>/ PROVIDER=<ssl_provider_classname>/SSL/CHARSET=<character set>/ TIMEOUT=<timeout_secs>/PWDTYPE=<authentication_type>/log_enable=<integer>
Also is supported Host:Port list in connection string:
jdbc:virtuoso://<Hostname>:<Port#>,<Hostname1>:<Port1#>,<Hostname2>:<Port2#>/
If Port is omitted, the default port 1111 is used.
Each part of the URL is explained below:
this is a constant value of "jdbc" since JDBC is the protocol in question
this is a constant value that identifies "virtuoso" as a sub protocol of JDBC
this identifies the machine hosting a server process that speaks the "virtuoso" sub dialect of the "jdbc" protocol
this identifies the port number on the machine from which the server which speaks the "virtuoso" sub dialect of "jdbc" listening for incoming client connections The default port number for a Virtuoso server is "1111".
this identifies the database (Qualifier or Catalog) that you are connecting to via a Virtuoso server
a valid user name for the Virtuoso database that you are connecting to via JDBC
a valid password for the user name
name of the certificate to use for the SSL connection stored in the keystore. This is a required option for an SSL authenticated connection
This optional parameter lets you specify the keystore file name (default: $HOME/.keystore). The path separator is \, and which is then replaced during the connection by the right platform path separator.
password required for accessing the keystore file. This is required for the SSL authenticated connection.
The class name of the SSL Provider (e.g. com.sun.ssl.net.internal.ssl.Provider) to use for the SSL cryptography. This parameter is required for SSL connections.
The SSL option is used only for SSL connection without user authentication
This allows the client to specify a character set for data encoding. When this option is set then all Java strings, natively Unicode, are converted to the character set specified here.
Specifies the maximum amount of time (in seconds) that the driver will wait for a response to a query. When this time is exceeded a time-out error will be reported and the network connection closed, assumed to be broken.
Specifies the authentication mode; how the user credentials may be transmitted to the server. This option can be one of the following 3 types: cleartext, encrypt, digest. The default is digest.
"cleartext" will transfer the password to the server in cleartext
"encrypt" will transfer the password to the server using Virtuoso's symmetric encryption technique.
"digest" will calculate an MD5 digest of the password (and some additional session variables) that will be sent to the server to be compared with the value calculated server-side.
Set log_enable=2 in order to auto commit on every changed row. Out of memory cannot be caused as with this setting there is no image in the memory for rollback.
boolean attribute 1 - for use RoundRobin; 0 - do not use . (used only if more than one host:post values are in connection string)
integer attribute, prefetch buffer size (default is 100)
integer attribute, socket send buffer size (default is 32768 bytes)
integer attribute, socket receive buffer size (default is 32768 bytes)
boolean attribute 1 - for use PreparedStatement pool; 0 - do not use (Only for Java 1.6 and above)
integer attribute, PreparedStatement pool size (default is 25)
Since JSSE has only incorporated SSL support for JDK 1.2 and above, SSL has only been implemented for the JDBC 2.x, JDBC 3.x and JDBC 4.x drivers for Virtuoso.
JDBC 3.0 compliant applications and applets may connect to a JDBC data source using JDBC javax.sql.DataSource instances. The Virtuoso JDBC 3.0 driver provides an implementation of the javax.sql.DataSource interface in the virtuoso.jdbc3.VirtuosoDataSource class, supporting the following properties:
Name | Type | URL Option Equivalent | Description |
---|---|---|---|
dataSourceName | java.lang.String | used in connection pooling | |
description | java.lang.String | string to describe the data source (free form) | |
serverName | java.lang.String | The host name of the remote host to connect to | |
portNumber | int | The port on the remote host to connect to | |
user | java.lang.String | /UID | username to use for the session |
password | java.lang.String | /PWD | password to use for the session |
databaseName | java.lang.String | /DATABASE | Initial catalog qualifier for the session |
charset | java.lang.String | /CHARSET | Charset used in wide<->narrow translations |
pwdClear | java.lang.String | /PWDTYPE | authentication method |
The Virtuoso JDBC 3.0 driver supports connection pooling.
The virtuoso.jdbc3.VirtuosoDataSource implements the javax.sql.ConnectionPoolDataSource interface. In order to use the connection pooling the administrator must deploy one instance of the virtuoso.jdbc3.VirtuosoDriver in the JNDI repository and set all of it's properties except dataSourceName. This is the "main" connection pooling data source. Then the administrator should deploy a second instance of the virtuoso.jdbc3.VirtuosoDataSource class and set only it's dataSourceName property.
Applications will use the second virtuoso.jdbc3.VirtuosoDataSource instance to get a connection. It will in turn call the first one to obtain all connect info and return the java.sql.Connection instance.
Virtuoso supports the industry standard XA specification for distributed transaction processing. The XA specification defines an interface between the transaction manager (TM) and resource manager (RM) in a distributed transaction system. This is a generic interface and it does not directly address the use of distributed transactions from Java. The Java mapping of the XA interface is defined in Sun Microsystems Java Transaction API (JTA) and JDBC 3.0 specifications. The Virtuoso JDBC 3.0 driver supports the JTA architecture by providing the implementation of JTA resource manager interfaces.
The Virtuoso JDBC 3.0 driver provides the virtuoso.java3.VirtuosoXid, virtuoso.java3.VirtuosoXADataSource, virtuoso.java3.VirtuosoXAConnection, and virtuoso.java3.VirtuosoXAResource classes which implement the interfaces javax.transaction.xa.Xid, javax.transaction.xa.XADataSource, javax.sql.XAConnection, and javax.sql.XAResource respectively. The use if these interfaces is usually transparent for applications and the application developer shouldn't bother with them. They are used only by the JTS transaction manager which normally runs as a part of the J2EE server.
The task of the J2EE server administrator is to setup the necessary Virtuoso XA datasources. The exact procedure of this depends on the J2EE server in use (such as BEA WebLogic, IBM WebSphere, etc). Generally, this includes two steps:
Include the JDBC driver's jar file into J2EE server's class path.
Deploy an instance of javax.transaction.xa.XADataSource with appropriately set properties into the J2EE server's JNDI repository.
The virtuoso.java3.VirtuosoXADataSource class is derived from virtuoso.java3.VirtuosoDataSource and inherits all of its properties. These properties has to be set as described in the section Virtuoso Driver For JDBC 3.0 javax.sql.DataSource.
For example, the following has to be done in case of Sun's J2EE Reference Implementation.
Add the path of virtjdbc3.jar to the J2EE_CLASSPATH variable in the file $(J2EE_HOME)/bin/userconfig.bat on Windows or $(J2EE_HOME)/bin/userconfig.sh on Unix/Linux:
set J2EE_CLASSPATH=C:/Virtuoso/lib/virtjdbc3.jar
J2EE_CLASSPATH=/home/login/virtuoso/lib/virtjdbc3.jar export J2EE_CLASSPATH
Using the following command add the XA datasource with JNDI name "jdbc/Virtuoso" which refers to the Virtuoso server running on the same computer on port 1111:
j2eeadmin -addJdbcXADatasource jdbc/Virtuoso virtuoso.jdbc3.VirtuosoXADataSource -props serverName=localhost portNumber=1111
The Virtuoso JDBC 3.0 driver has two implementations of the javax.sql.RowSet interface - virtuoso.javax.OPLCachedRowSet and virtuoso.javax.OPLJdbcRowSet.
The virtuoso.javax.OPLCachedRowSet class implements a totally disconnected, memory cached rowset and the virtuoso.javax.OPLJdbcRowset class spans the rest of the JDBC API to implement it's methods.
The IRIs and RDF literals, kept in the Virtuoso RDF store are represented by a strings and structures. Thus accessing RDF objects needs special datatypes in order to distinguish strings from IRIs and to get language and datatype of the RDF literals.
Therefore Virtuoso JDBC driver provides following classes for accessing RDF store: virtuoso.jdbc3.VirtuosoExtendedString for IRIs and virtuoso.jdbc3.VirtuosoRdfBox for RDF literal objects.
The class virtuoso.jdbc3.VirtuosoExtendedString will be returned when a string representing an IRI is returned to the client. It has two members "str" and "iriType", the "str" member keeps string representation of the IRI, "iriType" denote regular IRI or blank node with enum values VirtuosoExtendedString.IRI and VirtuosoExtendedString.BNODE.
If the RDF literal object have language or datatype specified then virtuoso.jdbc3.VirtuosoRdfBox will be returned. The following methods could be used :
String toString () : returns string representation of the literal String getType () : returns string containing the datatype of the literal String getLang () : returns language code for the literal
The following code snippet demonstrates how to use extension datatypes for RDF
... initialization etc. skipped for brevity boolean more = stmt.execute("sparql select * from <gr> where { ?x ?y ?z }"); ResultSetMetaData data = stmt.getResultSet().getMetaData(); while(more) { rs = stmt.getResultSet(); while(rs.next()) { for(int i = 1;i <= data.getColumnCount();i++) { String s = rs.getString(i); Object o = ((VirtuosoResultSet)rs).getObject(i); if (o instanceof VirtuosoExtendedString) // String representing an IRI { VirtuosoExtendedString vs = (VirtuosoExtendedString) o; if (vs.iriType == VirtuosoExtendedString.IRI && (vs.strType & 0x01) == 0x01) System.out.println ("<" + vs.str +">"); else if (vs.iriType == VirtuosoExtendedString.BNODE) System.out.println ("<" + vs.str +">"); } else if (o instanceof VirtuosoRdfBox) // Typed literal { VirtuosoRdfBox rb = (VirtuosoRdfBox) o; System.out.println (rb.rb_box + " lang=" + rb.getLang() + " type=" + rb.getType()); } else if(stmt.getResultSet().wasNull()) System.out.println("NULL"); else // { System.out.println(s); } } } more = stmt.getMoreResults(); } ...
JDBC 4.0 compliant applications and applets may connect to a JDBC data source using JDBC javax.sql.DataSource instances. The Virtuoso JDBC 4.0 driver provides an implementation of the javax.sql.DataSource interface in the virtuoso.jdbc4.VirtuosoDataSource class, supporting the following properties:
Name | Type | URL Option Equivalent | Description |
---|---|---|---|
dataSourceName | java.lang.String | used in connection pooling | |
description | java.lang.String | string to describe the data source (free form) | |
serverName | java.lang.String | The host name of the remote host to connect to | |
portNumber | int | The port on the remote host to connect to | |
user | java.lang.String | /UID | username to use for the session |
password | java.lang.String | /PWD | password to use for the session |
databaseName | java.lang.String | /DATABASE | Initial catalog qualifier for the session |
charset | java.lang.String | /CHARSET | Charset used in wide<->narrow translations |
pwdClear | java.lang.String | /PWDTYPE | authentication method |
Additionally, the following attributres are supported:
--- for SSL enabled --- public void setCertificate (String value); public String getCertificate (); public void setKeystorepass (String value); public String getKeystorepass (); public void setKeystorepath (String value); public String getKeystorepath (); public void setProvider (String value); public String getProvider (); ---------------------- public void setFbs (int value); public int getFbs (); public void setSendbs (int value); public int getSendbs (); public void setRecvbs (int value); public int getRecvbs (); public void setRoundrobin (boolean value); public boolean getRoundrobin (); -- For Java 1.6 and above public void setUsepstmtpool (boolean value); public boolean getUsepstmtpool (); public void setPstmtpoolsize (int value); public int getPstmtpoolsize ();
The Virtuoso JDBC 4.0 driver supports connection pooling.
The virtuoso.jdbc4.VirtuosoDataSource implements the javax.sql.ConnectionPoolDataSource interface. In order to use the connection pooling the administrator must deploy one instance of the virtuoso.jdbc4.VirtuosoDriver in the JNDI repository and set all of it's properties except dataSourceName. This is the "main" connection pooling data source. Then the administrator should deploy a second instance of the virtuoso.jdbc4.VirtuosoDataSource class and set only it's dataSourceName property.
Applications will use the second virtuoso.jdbc4.VirtuosoDataSource instance to get a connection. It will in turn call the first one to obtain all connect info and return the java.sql.Connection instance.
VirtuosoConnectionPoolDataSource.class has the following connection pooling attributes:
/** * Get the minimum number of physical connections * the pool will keep available at all times. Zero ( 0 ) indicates that * connections will be created as needed. * * @return the minimum number of physical connections * **/ public int getMinPoolSize(); /** * Set the number of physical connections the pool should keep available * at all times. Zero ( 0 ) indicates that connections should be created * as needed * The default value is 0 . * * @param parm a minimum number of physical connections * * @exception java.sql.SQLException if an error occurs * **/ public void setMinPoolSize(int parm); /** * Get the maximum number of physical connections * the pool will be able contain. Zero ( 0 ) indicates no maximum size. * * @return the maximum number of physical connections * **/ public int getMaxPoolSize(); /** * Set the maximum number of physical conections that the pool should contain. * Zero ( 0 ) indicates no maximum size. * The default value is 0 . * * @param parm a maximum number of physical connections * * @exception java.sql.SQLException if an error occurs * **/ public void setMaxPoolSize(int parm); /** * Get the number of physical connections the pool * will contain when it is created * * @return the number of physical connections * **/ public int getInitialPoolSize(); /** * Set the number of physical connections the pool * should contain when it is created * * @param parm a number of physical connections * * @exception java.sql.SQLException if an error occurs * **/ public void setInitialPoolSize(int parm); /** * Get the number of seconds that a physical connection * will remain unused in the pool before the * connection is closed. Zero ( 0 ) indicates no limit. * * @return the number of seconds **/ public int getMaxIdleTime(); /** * Set the number of seconds that a physical connection * should remain unused in the pool before the * connection is closed. Zero ( 0 ) indicates no limit. * * @param parm a number of seconds * * @exception java.sql.SQLException if an error occurs * **/ public void setMaxIdleTime(int parm); /** * Get the interval, in seconds, that the pool will wait * before enforcing the current policy defined by the * values of the above connection pool properties * * @return the interval (in seconds) **/ public int getPropertyCycle(); /** * Set the interval, in seconds, that the pool should wait * before enforcing the current policy defined by the * values of the above connection pool properties * * @param parm an interval (in seconds) **/ public void setPropertyCycle(int parm); /** * Get the total number of statements that the pool will * keep open. Zero ( 0 ) indicates that caching of * statements is disabled. * * @return the total number of statements **/ public int getMaxStatements(); /** * Set the total number of statements that the pool should * keep open. Zero ( 0 ) indicates that caching of * statements is disabled. * * @param parm a total number of statements * * @exception java.sql.SQLException if an error occurs * **/ public void setMaxStatements(int parm);
Virtuoso supports the industry standard XA specification for distributed transaction processing. The XA specification defines an interface between the transaction manager (TM) and resource manager (RM) in a distributed transaction system. This is a generic interface and it does not directly address the use of distributed transactions from Java. The Java mapping of the XA interface is defined in Sun Microsystems Java Transaction API (JTA) and JDBC 4.0 specifications. The Virtuoso JDBC 4.0 driver supports the JTA architecture by providing the implementation of JTA resource manager interfaces.
The Virtuoso JDBC 4.0 driver provides the virtuoso.java3.VirtuosoXid, virtuoso.java3.VirtuosoXADataSource, virtuoso.java3.VirtuosoXAConnection, and virtuoso.java3.VirtuosoXAResource classes which implement the interfaces javax.transaction.xa.Xid, javax.transaction.xa.XADataSource, javax.sql.XAConnection, and javax.sql.XAResource respectively. The use if these interfaces is usually transparent for applications and the application developer shouldn't bother with them. They are used only by the JTS transaction manager which normally runs as a part of the J2EE server.
The task of the J2EE server administrator is to setup the necessary Virtuoso XA datasources. The exact procedure of this depends on the J2EE server in use (such as BEA WebLogic, IBM WebSphere, etc). Generally, this includes two steps:
Include the JDBC driver's jar file into J2EE server's class path.
Deploy an instance of javax.transaction.xa.XADataSource with appropriately set properties into the J2EE server's JNDI repository.
The virtuoso.java3.VirtuosoXADataSource class is derived from virtuoso.java3.VirtuosoDataSource and inherits all of its properties. These properties has to be set as described in the section Virtuoso Driver For JDBC 4.0 javax.sql.DataSource.
For example, the following has to be done in case of Sun's J2EE Reference Implementation.
Add the path of virtjdbc4.jar to the J2EE_CLASSPATH variable in the file $(J2EE_HOME)/bin/userconfig.bat on Windows or $(J2EE_HOME)/bin/userconfig.sh on Unix/Linux:
set J2EE_CLASSPATH=C:/Virtuoso/lib/virtjdbc4.jar
J2EE_CLASSPATH=/home/login/virtuoso/lib/virtjdbc4.jar export J2EE_CLASSPATH
Using the following command add the XA datasource with JNDI name "jdbc/Virtuoso" which refers to the Virtuoso server running on the same computer on port 1111:
j2eeadmin -addJdbcXADatasource jdbc/Virtuoso virtuoso.jdbc4.VirtuosoXADataSource -props serverName=localhost portNumber=1111
The Virtuoso JDBC 4.0 driver has two implementations of the javax.sql.RowSet interface - virtuoso.javax.OPLCachedRowSet and virtuoso.javax.OPLJdbcRowSet.
The virtuoso.javax.OPLCachedRowSet class implements a totally disconnected, memory cached rowset and the virtuoso.javax.OPLJdbcRowset class spans the rest of the JDBC API to implement it's methods.
The IRIs and RDF literals, kept in the Virtuoso RDF store are represented by a strings and structures. Thus accessing RDF objects needs special datatypes in order to distinguish strings from IRIs and to get language and datatype of the RDF literals.
Therefore Virtuoso JDBC driver provides following classes for accessing RDF store: virtuoso.jdbc4.VirtuosoExtendedString for IRIs and virtuoso.jdbc4.VirtuosoRdfBox for RDF literal objects.
The class virtuoso.jdbc4.VirtuosoExtendedString will be returned when a string representing an IRI is returned to the client. It has two members "str" and "iriType", the "str" member keeps string representation of the IRI, "iriType" denote regular IRI or blank node with enum values VirtuosoExtendedString.IRI and VirtuosoExtendedString.BNODE.
If the RDF literal object have language or datatype specified then virtuoso.jdbc4.VirtuosoRdfBox will be returned. The following methods could be used :
String toString () : returns string representation of the literal String getType () : returns string containing the datatype of the literal String getLang () : returns language code for the literal
The following code snippet demonstrates how to use extension datatypes for RDF
... initialization etc. skipped for brevity boolean more = stmt.execute("sparql select * from <gr> where { ?x ?y ?z }"); ResultSetMetaData data = stmt.getResultSet().getMetaData(); while(more) { rs = stmt.getResultSet(); while(rs.next()) { for(int i = 1;i <= data.getColumnCount();i++) { String s = rs.getString(i); Object o = ((VirtuosoResultSet)rs).getObject(i); if (o instanceof VirtuosoExtendedString) // String representing an IRI { VirtuosoExtendedString vs = (VirtuosoExtendedString) o; if (vs.iriType == VirtuosoExtendedString.IRI && (vs.strType & 0x01) == 0x01) System.out.println ("<" + vs.str +">"); else if (vs.iriType == VirtuosoExtendedString.BNODE) System.out.println ("<" + vs.str +">"); } else if (o instanceof VirtuosoRdfBox) // Typed literal { VirtuosoRdfBox rb = (VirtuosoRdfBox) o; System.out.println (rb.rb_box + " lang=" + rb.getLang() + " type=" + rb.getType()); } else if(stmt.getResultSet().wasNull()) System.out.println("NULL"); else // { System.out.println(s); } } } more = stmt.getMoreResults(); } ...
Perform the following steps in order to make use of your Virtuoso Drivers for JDBC:
You only have to perform these steps if a first attempt to use the Virtuoso Drivers for JDBC fails, the Virtuoso installer will attempt to configure these settings for you at installation time.
Ensure your PATH environment variable is pointing to a version of the Java Virtual Machine (JVM) that is compatible with the version of the JDBC Driver Manager installed on your machine. Consult the section above to double check. You can also type the following command to verify Java versions:
java -version
Add the appropriate Virtuoso for JDBC "jar" file to your CLASSPATH environment variable.
Attempt to make a connection using one of the sample JDBC Applications or Applets provided with your Virtuoso installation.
If you have problems using the virtuoso JDBC driver despite your CLASSPATH being defined correctly, you may force the Java Virtual Machine to load a specific JDBC driver using: -D on the java command line: e.g:
-Djdbc.drivers=virtuoso.jdbc.Driver.
You can check the Virtuoso JDBC driver version from the command line using: java virtuoso.jdbc.Driver
What
Hibernate is a powerful, open source, high performance object/relational persistence and query service. Hibernate lets you develop persistent classes following object-oriented idiom - including association, inheritance, polymorphism, composition, and collections. Hibernate allows you to express queries in its own portable SQL extension (HQL), as well as in native SQL, or with an object-oriented Criteria and Example API.
Why
Hibernate employs very aggressive, and very intelligent first and second level caching strategy, providing a high performance and scalable development framework for Java. Greater cross portability and productivity can also be achieve using hibernate as the same techniques can be employed across multiple databases.
How
Hibernate uses JDBC for accessing databases and may require a given database has a custom SQL dialect file that informs Hibernate what SQL dialects are to be use for performing certain operations against the target database. Although not strictly required, it should be used to ensure Hibernate Query Language (HQL) statements are correctly converted into the proper SQL dialect for the underlying database. Virtuoso includes a new jar file called virt_dialect.jar containing the SQL dialect mappings required between hibernate and Virtuoso and is used in conjunction to the Virtuoso JDBC Drivers (virtjdbc3.jar or virtjdbc4.jar).
Three sample programs are provided to test Virtuoso hibernate support. Extract the contents of the zip file to a location of choice.
The following Ant targets are available:
clean Clean the build directory compile Build example run Build and run example
Edit the file hibernate.cfg.xml in the "bin" and "src" directories of the hibernate application directory with the correct connection attributes for the Virtuoso Server instance:
$ more hibernate.cfg.xml <?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">virtuoso.jdbc4.Driver</property> <property name="connection.url">jdbc:virtuoso://localhost:1111/</property> <property name="connection.username">dba</property> <property name="connection.password">dba</property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property> <!-- SQL dialect --> <property name="dialect">virtuoso.hibernate.VirtuosoDialect</property> <!-- Enable Hibernate's current session context --> <property name="current_session_context_class">thread</property> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-- Drop and re-create the database schema on startup --> <property name="hbm2ddl.auto">create</property> <mapping resource="events/Event.hbm.xml"/> </session-factory> </hibernate-configuration>
The key attributes being
This sample performs a simple insert and retrieval of data against the Virtuoso database.
antlr-2.7.6.jar commons-collections-3.1.jar commons-logging-1.0.4.jar dom4j-1.6.1.jar hibernate3.jar javassist-3.4.GA.jar jta-1.1.jar lib.lst log4j-1.2.15.jar slf4j-api-1.5.10.jar slf4j-api-1.5.2.jar slf4j-jcl-1.5.10.jar virtjdbc4.jar virt_dialect.jar
$ ant run Buildfile: build.xml clean: [delete] Deleting directory /Users/hughwilliams/hibernate/ex1/bin [mkdir] Created dir: /Users/hughwilliams/hibernate/ex1/bin copy-resources: [copy] Copying 3 files to /Users/hughwilliams/hibernate/ex1/bin [copy] Copied 2 empty directories to 1 empty directory under /Users/hughwilliams/hibernate/ex1/bin compile: [javac] Compiling 3 source files to /Users/hughwilliams/hibernate/ex1/bin run: [java] Hibernate: insert into Event (EVENT_DATE, title) values (?, ?) [java] Hibernate: select identity_value() [java] Hibernate: insert into Event (EVENT_DATE, title) values (?, ?) [java] Hibernate: select identity_value() [java] Hibernate: select event0_.EVENT_ID as EVENT1_0_, event0_.EVENT_DATE as EVENT2_0_, event0_.title as title0_ from Event event0_ [java] Event: My Event1 Time: 2010-03-14 03:27:51.0 [java] Event: My Event2 Time: 2010-03-14 03:27:53.0 BUILD SUCCESSFUL Total time: 3 seconds
Hello World with Java Persistence
antlr-2.7.6.jar asm-attrs.jar asm.jar c3p0-0.9.0.jar cglib-2.1.3.jar commons-collections-2.1.1.jar commons-logging-1.0.4.jar dom4j-1.6.1.jar ejb3-persistence.jar freemarker.jar hibernate-annotations.jar hibernate-commons-annotations.jar hibernate-entitymanager.jar hibernate-tools.jar hibernate3.jar javassist.jar jboss-archive-browsing.jar jta.jar log4j-1.2.13.jar virtjdbc4.jar virt_dialect.jar
$ ant schemaexport Buildfile: build.xml compile: copymetafiles: schemaexport: [hibernatetool] Executing Hibernate Tool with a JPA Configuration [hibernatetool] 1. task: hbm2ddl (Generates database schema) [hibernatetool] [hibernatetool] drop table MESSAGES; [hibernatetool] [hibernatetool] create table MESSAGES ( [hibernatetool] MESSAGE_ID decimal(20,0) identity, [hibernatetool] MESSAGE_TEXT varchar(255) null, [hibernatetool] NEXT_MESSAGE_ID decimal(20,0) null, [hibernatetool] primary key (MESSAGE_ID) [hibernatetool] ); [hibernatetool] [hibernatetool] alter table MESSAGES [hibernatetool] add [hibernatetool] foreign key (NEXT_MESSAGE_ID) [hibernatetool] references MESSAGES; BUILD SUCCESSFUL Total time: 2 seconds
$ more helloworld-ddl.sql drop table MESSAGES; create table MESSAGES ( MESSAGE_ID decimal(20,0) identity, MESSAGE_TEXT varchar(255) null, NEXT_MESSAGE_ID decimal(20,0) null, primary key (MESSAGE_ID) ); alter table MESSAGES add foreign key (NEXT_MESSAGE_ID) references MESSAGES;
$ ant run Buildfile: build.xml compile: copymetafiles: run: [java] 1 message(s) found: [java] Hello World with JPA BUILD SUCCESSFUL Total time: 2 seconds
$ ant run Buildfile: build.xml compile: copymetafiles: run: [java] 2 message(s) found: [java] Hello World with JPA [java] Hello World with JPA BUILD SUCCESSFUL Total time: 2 seconds
This sample performs more complex insert and retrieval of data against the Virtuoso database.
$ ant run Buildfile: build.xml clean: [delete] Deleting directory /Users/hughwilliams/hibernate/ex3/bin [mkdir] Created dir: /Users/hughwilliams/hibernate/ex3/bin copy-resources: [copy] Copying 4 files to /Users/hughwilliams/hibernate/ex3/bin [copy] Copied 2 empty directories to 1 empty directory under /Users/hughwilliams/hibernate/ex3/bin compile: [javac] Compiling 4 source files to /Users/hughwilliams/hibernate/ex3/bin [javac] Note: Some input files use unchecked or unsafe operations. [javac] Note: Recompile with -Xlint:unchecked for details. run: [java] Hibernate: insert into EVENTS (EVENT_DATE, title) values (?, ?) [java] Hibernate: select identity_value() [java] Hibernate: insert into EVENTS (EVENT_DATE, title) values (?, ?) [java] Hibernate: select identity_value() [java] Hibernate: insert into PERSON (age, firstname, lastname) values (?, ?, ?) [java] Hibernate: select identity_value() [java] Hibernate: select person0_.PERSON_ID as PERSON1_2_0_, event2_.EVENT_ID as EVENT1_0_1_, person0_.age as age2_0_, person0_.firstname as firstname2_0_, person0_.lastname as lastname2_0_, event2_.EVENT_DATE as EVENT2_0_1_, event2_.title as title0_1_, events1_.PERSON_ID as PERSON2_0__, events1_.EVENT_ID as EVENT1_0__ from PERSON person0_ left outer join PERSON_EVENT events1_ on person0_.PERSON_ID=events1_.PERSON_ID left outer join EVENTS event2_ on events1_.EVENT_ID=event2_.EVENT_ID where person0_.PERSON_ID=? [java] Hibernate: select event0_.EVENT_ID as EVENT1_0_0_, event0_.EVENT_DATE as EVENT2_0_0_, event0_.title as title0_0_ from EVENTS event0_ where event0_.EVENT_ID=? [java] Hibernate: select participan0_.EVENT_ID as EVENT1_1_, participan0_.PERSON_ID as PERSON2_1_, person1_.PERSON_ID as PERSON1_2_0_, person1_.age as age2_0_, person1_.firstname as firstname2_0_, person1_.lastname as lastname2_0_ from PERSON_EVENT participan0_ left outer join PERSON person1_ on participan0_.PERSON_ID=person1_.PERSON_ID where participan0_.EVENT_ID=? [java] Hibernate: insert into PERSON_EVENT (PERSON_ID, EVENT_ID) values (?, ?) [java] Hibernate: update PERSON set age=?, firstname=?, lastname=? where PERSON_ID=? [java] Added person 1 to event 2 [java] Hibernate: insert into PERSON (age, firstname, lastname) values (?, ?, ?) [java] Hibernate: select identity_value() [java] Hibernate: select person0_.PERSON_ID as PERSON1_2_0_, person0_.age as age2_0_, person0_.firstname as firstname2_0_, person0_.lastname as lastname2_0_ from PERSON person0_ where person0_.PERSON_ID=? [java] Hibernate: select emailaddre0_.PERSON_ID as PERSON1_0_, emailaddre0_.EMAIL_ADDR as EMAIL2_0_ from PERSON_EMAIL_ADDR emailaddre0_ where emailaddre0_.PERSON_ID=? [java] Hibernate: insert into PERSON_EMAIL_ADDR (PERSON_ID, EMAIL_ADDR) values (?, ?) [java] Hibernate: select person0_.PERSON_ID as PERSON1_2_0_, person0_.age as age2_0_, person0_.firstname as firstname2_0_, person0_.lastname as lastname2_0_ from PERSON person0_ where person0_.PERSON_ID=? [java] Hibernate: select emailaddre0_.PERSON_ID as PERSON1_0_, emailaddre0_.EMAIL_ADDR as EMAIL2_0_ from PERSON_EMAIL_ADDR emailaddre0_ where emailaddre0_.PERSON_ID=? [java] Hibernate: insert into PERSON_EMAIL_ADDR (PERSON_ID, EMAIL_ADDR) values (?, ?) [java] Added two email addresses (value typed objects) to person entity : 1 [java] Hibernate: select event0_.EVENT_ID as EVENT1_0_, event0_.EVENT_DATE as EVENT2_0_, event0_.title as title0_ from EVENTS event0_ [java] Event: My Event Time: 2010-03-14 03:30:02.0 [java] Event: My Event Time: 2010-03-14 03:30:06.0 BUILD SUCCESSFUL Total time: 5 seconds
This example demonstrates how to make Multi Thread Virtuoso connection using JDBC.
It starts 3 threads: one thread executes SPARQL select and two threads execute SPARQL inserts:
import java.util.*; import java.sql.*; import java.math.*; public class MTtest extends Thread { int mode = 0; int startId = 0; static String urlDB = "jdbc:virtuoso://localhost:1111"; public MTtest(int _mode, int _init) { mode = _mode; startId = _init; } void prnRs(ResultSet rs) { try { ResultSetMetaData rsmd; System.out.println(">>>>>>>>"); rsmd = rs.getMetaData(); int cnt = rsmd.getColumnCount(); while(rs.next()) { Object o; System.out.print("Thread:"+Thread.currentThread().getId()+" "); for (int i = 1; i <= cnt; i++) { o = rs.getObject(i); if (rs.wasNull()) System.out.print("<NULL> "); else System.out.print("["+ o + "] "); } System.out.println(); } } catch (Exception e) { System.out.println(e); e.printStackTrace(); } System.out.println(">>>>>>>>"); } public static void main(String argv[]) { try { Class.forName("virtuoso.jdbc3.Driver"); Connection conn = DriverManager.getConnection(urlDB,"dba","dba"); Statement st = conn.createStatement(); st.execute("sparql clear graph <mttest>"); st.execute("sparql insert into graph <mttest> { <xxx> <P01> \"test1\" }"); st.execute("sparql insert into graph <mttest> { <xxx> <P01> \"test2\" }"); st.execute("sparql insert into graph <mttest> { <xxx> <P01> \"test3\" }"); st.execute("sparql insert into graph <mttest> { <xxx> <P01> \"test4\" }"); st.execute("sparql insert into graph <mttest> { <xxx> <P01> \"test5\" }"); conn.close(); int init = 0; for(int i=0; i < 2; i++) { MTtest thr1 = new MTtest(1, init); init+=10; MTtest thr2 = new MTtest(0, init); init+=10; MTtest thr3 = new MTtest(0, init); init+=10; thr1.start(); thr2.start(); thr3.start(); thr1.join(); thr2.join(); thr3.join(); } System.out.println("===End==="); } catch (Exception e) { System.out.print(e); e.printStackTrace(); } } public void run( ) { try { Connection conn = DriverManager.getConnection(urlDB,"dba","dba"); Statement st; st = conn.createStatement(); if (mode == 1) { String query = "sparql SELECT * from <mttest> WHERE {?s ?p ?o}"; ResultSet rs = st.executeQuery(query); prnRs(rs); } else { long id = Thread.currentThread().getId(); for (int i =0; i < 5; i++) st.execute("sparql insert into graph <mttest> { <xxx"+startId+"> <P"+id+"> \"test"+i+"\" }"); System.out.println("\nThread:"+Thread.currentThread().getId()+" ===Rows Inserted==="); } conn.close(); } catch (SQLException e) { System.out.println("==========================================================="); System.out.println(">>["+e.getMessage()+"]"); System.out.println(">>["+e.getErrorCode()+"]"); System.out.println(">>["+e.getSQLState()+"]"); System.out.println(e); System.out.println("==========================================================="); e.printStackTrace(); System.exit(-1); } catch (Exception e) { System.out.println("==========================================================="); System.out.println(e); System.out.println("==========================================================="); e.printStackTrace(); System.exit(-1); } } // run( ) }
Previous
Virtuoso Driver for ODBC |
Chapter Contents |
Next
OLE DB Provider for Virtuoso |