Some confusion surrounding JDBC Resources and JDBC Connection pools Glassfish - java

I am about to make a connection to my database and I am using EJB and JPA. I have recently started doing these technologies so I have some problems understand it all at this point:)
I know that the persistence.xml is needed in order to use JPA. It is the file where I configure how to connect to the database, that I know. However it seems like there are multiple ways of doing it.
What would be the difference (or when should I even use the one alternative over the other?) of defining properties such as username, database, password etc. in the persistence.xml file and in Glassfish? Advantages/disadvantages if any.
Underneath on the image I posted I have JDBC Resources and JDBC Connection Pools. I am a litte confused about the terminology of the two. Why don't we add properties such as username, database, password and so on in the JDBC Resources? Could someone explain the difference between them and what they mean?
JDBC Resources
A JDBC resource (data source) provides applications with a means of
connecting to a database. Typically, the administrator creates a JDBC
resource for each database accessed by the applications deployed in a
domain. (However, more than one JDBC resource can be created for a
database.)
http://download.oracle.com/docs/cd/E19316-01/820-4335/ablih/index.html
I think it strange that we add such properties on the pool but not in the resource, but I probably misunderstand the concepts.

In the "JDBC connection pools" you can create container managed JDBC data sources (with connection pooling capabilities). The data source needs to know about at least the JDBC driver, the JDBC URL, username and password.
In the "JDBC resources" you can bind those container managed JDBC data sources to one or more JNDI names so that they are by JNDI available to the deployed web application.
In the persistence.xml you can specify whether to use a local data source or to use a container managed data source. If you want to use a container managed data source, then you should specify its JNDI name. Using a container managed data source has the advantage that you can share a single data source among multiple web applications. In case of JPA, it has also the advantage that you can make use of JTA (container managed transactions) so that you don't need to call transaction.begin(), commit(), rollback() etc in every method.

Related

Class.forName("org.sqlite.JDBC") vs JDBC.PREFIX to load JDBC class

We had recently moved to building projects using Maven. Earlier, all the JARs were added in libs folder and added to classpath. While moving to the Maven build, I missed to add a dependency to the 'sqlite-jdbc'. This library is required to read data from a local .db3 file.
As the 'org.sqlite.JBDC' class was loaded by calling the code Class.forName("org.sqlite.JDBC"), there was no compilation error and I deployed the WAR file and servlet failed in the server. I was thinking of a way to find the issue at the compilation time itself to avoid any such mistakes in the future. Can I simply call the JDBC.PREFIX to load the JDBC, so that, If I forget to add the dependency to the pom.xml file, I can find the issue at the compile time, itself?
Is there was difference between Class.forName("org.sqlite.JDBC") vs JDBC.PREFIX to load JDBC class?
No need for Class.forName
There is no generally no need to call Class.forName.
Such calls were used in the early years. Modern Java was changed so that JDBC drivers are automatically loaded and registered with the JVM via the Java Service Provider Interface (SPI) facility.
If you are using books or tutorials advising Class.forName, you may want to obtain more up-to-date learning materials.
DataSource
Furthermore, in Servlet work you generally should not be explicitly accessing the JDBC driver.
Setting the database server address, username, and password would require hard-coding text. When the deployment sysadmins change the IP address, or rotate passwords, your code breaks. You would then have to modify your source code, re-compile, and re-deploy.
Instead, you should externalize such configuration details.
For SQLite, see Using DataSource to connect to SQLite with (Xerial) sqlite-jdbc driver.
JNDI
You can externalize database configuration by using the the DataSource interface. After obtaining a DataSource object at runtime, make database connections by calling its getConnection method. That DataSource object holds the database server address, username, password, and all other settings needed to make a connection to the database.
Obtain a DataSource object at runtime by using JNDI. Your Servlet container may act as the naming/directory server to provide the DataSource object, if your sysadmin so configures it. Or the DataSource can be obtained via JNDI from an external server such as an LDAP server.
Again, the beauty of using DataSource and JNDI is that you as the Servlet programmer need not be involved, or even informed, when the deployment details change.
JDBC driver location
For Servlet work, you generally do not bundle the JDBC driver with your app.
Instead, the JDBC driver goes into a folder managed by your Servlet container. Study the documentation for your particular Servlet container. For Apache Tomcat, see this Answer.
In development, your IDE may need access to the JDBC driver to compile. If so, in your Maven POM, mark the dependency with a <scope>provided</scope> element. This tag tells Maven to omit that dependency from the final build because the dependency will already be present (provided) at runtime.
If you insist on bundling your JDBC driver within the WAR file of your web app, then see the important Comment by Mark Rotteveel.
This topic has been addressed many times on Stack Overflow. Search to learn more.

Share Hibernate connection with other libraries

I'm writing a web application in Java and use Hibernate to map the database with my java objects. In Hibernate I connect to the database using C3PO pool. Now I need to schedule some tasks. Herefore I will use Quartz. Now the scheduled tasks will be stored in the database. It is possible to share the connection pool of C3PO with Quartz? So that the database settings are in one and the same file and that only one library is responsible to open a databaseconnection.
This is sort of a subjective thing, but suffice it to say, if you want to share the connection you have a number of options.
If you are using spring, define the c3p0 connection pool as a bean and inject it into both the Hibernate session factory and the Quartz scheduler beans.
If you are trying to stay "pure" and not using Spring, you can define your a JNDI based data-source at the container level.
There are some nuances with both approaches.
Unfortunately without indicating how "portable" you are trying to be and what you are currently using beyond just 'java', 'quartz-scheduler' and 'c3p0' as tags an answer will be vague at best.
EDIT
Thanks to the OP for adding additional information.
So with regard to that information, if you are using a Dynamic Web Project, you may be able to add a container specific deployment descriptor to WebContent directory.
For tomcat, META-INF/context.xml
For Jetty, WEB-INF/jetty-web.xml
With those, you can define a JNDI data source. Refer to the specific container for information on how to do that. Once done, Hibernate and Quartz can be configured to use a JNDI reference for the data source you have configured.

Connection pool for dynamic database connections

The problem setup is based on a webservice (Spring/Java, Tomcat7 and MySql) where every user gets their own database, hence each request needs their own connection. As all databases are created dynamically during runtime, configuring them statically before startup is not an option.
To optimise database connection usage, an implementation of a database connection pool would be great, right?
With Java/Spring: How would I create a connection pool for dynamic databases? I am a bit struck by the lack of clean options here!
Problem: Tomcat's Connection Pool (and as far as i understand C3P0 as well) treats each new DataSource instance as a whole new connection pool -> stack-reference
Is it a good idea to create a static datasource with a generic MySql connection (without specifing the database on connection) and use a connection pool with this datasource together with adapted SQL statements?
stack-reference
What about developing a custom persistent database based datasource pool? Any experience with performance here? Any advice? Any libraries that do that?
Or would it be feasable to workaround Tomcat's DataSource problem by creating Tomcat JNDI Datasources dynamically by manipulating it's context.xml dynamically from Java?
I can't believe that there aren't more plain/simple solutions for this. Grails/Hibernate struggles with this, Java/JDBC struggles with this, ... is it such a rare use-case to separate userdata on a user basis by creating user specific databases dynamically? If so, what would be a better setup?
EDIT
Another option is the suggestion from #M.Deinum to use a single configured datasource and dynamically hotswap it for the right connection ->M.Deinum Blog and stack-reference. How does that perform with a connection pool like the ones above?
I believe that HikariCP works without having to specify a single database.
Once the databases are created in runtime, you have to create the pools also in runtime. I am afraid the spring infrastructure is not giving you any help here, as it is tuned for the usual static use case.
I'd have a map of pools:
have a Map < connectionUrlString,List< c3poPool > > map
when requesting a connection, get the corresponding c3po pool from the map
and you can get the best of both worlds, since the real connection pool for each dynamically created database is handled by a c3po instance, but you can create new instances in runtime
This works as a low-level solution. If you want to go further, you can wrap this logic into a db connection provider, and register that as a "driver". This way any part of your application requests a new connection, you can just return one connection from the existing pools (and if a totally new connection is requested, create a new pool for that).
First than all, sorry for my english, i'm improving every day.
In my experience, I had a similar situation and it was resolve with spring framework. Let me explain you how you'd solve that question.
Make a spring config file with these characteristics:
a) A resource loader: This one is the responsible of load properties from configurations files or from database, those properties will be the appropriates to establish the database connection.
b) A pool database configuration parameterized with the properties that you'll load.
Create a locator class: In this class you'll need a HashMap
Use the multi context feature of spring: The idea is assign a code to every one connection that you establish and later load that connection like an application context with spring, then in the locator class, put in the map that context and use it as frequent as you need.
I think is you follow these steps, you can create dynamic pool or database connection as you want.

SSL code inside Hibernate

I'm looking for the code inside Hibernate that manages SSL connections and certificates -- however, so far I have been unable to. The repository I've been looking at is here, https://github.com/hibernate/hibernate-orm
Am I missing something?
Hibernate is a object relational mapping library -- it maps java object manipulation into SQL transactions. You don't use it to manage SSL connections / certificate (although it might / not contain code that does this). So yes maybe you're missing (a lot of) things.
Typically you need to configure DBMS datasource for hibernate to use, and if you need SSL for your database connection this is where you configure it
Datasource is typically vendor specific, plus you have to take into account connection pooling provider

Pattern for connecting to different databases using JDBC

I'm writing an application which has to be configurable to connect to Oracle, SQL Server and MySQL depending on client whim.
Up till now I'd been planning on using the JDBC-ODBC bridge and just connecting to the databases using different connection strings.
I'm told this is not very efficient.
Is there a pattern or best practice for connecting to multiple database systems? Or for selecting which driver to use?
Should I have it configurable? but include all three drivers or build three separate clients?
I'm not doing anything complex just pumping (inserting) data into the database from an event stream.
I would suggest that you make it configurable and include the three drivers. You can use a pattern like this: Create a super class (lets call it DAO) that provides the functionality of connecting to the database. This could be abstract.
Create a concrete sub class for each type of database that you wish to connect to. So you may end up with MySQLDAO, MSSQLDAO, and OracleDAO. each one will load the respective driver and use its respective connection string.
Create another class (lets call it DAOFactory) with a method getDAO(DB) that will create an instance of the DAO depending on the value of DB.
So for instance(in Pseudocode):
if(DB.equals("MySQL")){
DAO = new MySQLDAO();
}
return DAO;
So any code that needs to connect to the database will call the DAOFactory and ask for a DAO instance. You may store the DB value in an external file (like a properties file) so that you do not have to modify code to change the type of database.
this way your code does not need to know which type of database it is connecting to, and if you decide to support a fourth type of database later you will have to add one more class and modify the DAOFactory, not the rest of your code.
If you need anything complex, Hibernate is a good choice.
otherwise, what I would do is store your connection details in a properties file (or some other form of configuration) - namely: driver classname, JDBC url, username and password.
Then, all you need to do is load up the connection details from your properties file and include the correct JAR file on your classpath and you're done.
You could use a library such as Commons-DBCP if you wanted it to be a little easier to configure but other than that it's all you need to do (provided your SQL statements work on every database, of course).
If you're careful (and you test), you can do this with straight JDBC and just vary the driver class and connection information. You definitely want to stay away from the JDBC-ODBC bridge as it's generally slow and unreliable. The bridge is more likely to behave differently across dbs than JDBC is.
I think the DAO path is overkill if your requirements are as simple as listed.
If you're doing a lot of inserts, you might want to investigate prepared statements and batched updates as they are far more efficient. This might end up being less portable - hard to say without testing.
Take a look at Datasource. This is the preferred mechanism for obtaining a database connection.
IMO this provides an adminstrator the greatest flexibility for choosing database, connection pooling, and transaction strategies.
If you're using tomcat, then see here for how to register a Datasource with tomcat's JNDI.
If you're using Spring, then you can obtain a Datasource using jee:jndi-lookup.
If you're using Spring, but don't want to use JNDI, take a look at DriverManagerDataSource for a discussion of how to obtain a pooled Datasource (DBCP or C3P0).

Categories