Getting an EntityManagerFactory whitout persistence.xml - jpa

I develop a webApp which is connecting to many similar database.
The target databases are set by the final user in an administration GUI.
They work with differents database engine.
I use JPA and Eclipselink 2.6.4 to query theses databases.
Actually I've no other choice than writing a persistence.xml file on the fly and to use it to create an EntityManagerFactory.
pros.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML, persistenceFilesPath + "/" + persistenceFileName);
Persistence.createEntityManagerFactory(envCode, pros);
I would like to bypass this step to get directly an EntityManagerFactory without writing an persitence.xml file.
I've read some things on PersistenceUnitInfo and createContainerEntityManagerFactory but nothing really concrete.
I'm looking for ideas to reach my goal. I hope you will have somes.
Thanks

Related

Connecting Spring Batch to Remote Cassandra Database

I'm hoping to read data from a CSV file, process the data, and upload it to a remote database. I'm using Spring's starter repo as a base. Code is here
I tried putting this information in the properties file:
spring.data.cassandra.contact-points=IP, IP
spring.data.cassandra.port=PORT
spring.data.cassandra.keyspace-name=KEYSPACE_NAME
spring.data.cassandra.username=USER
spring.data.cassandra.password=PASS
spring.data.cassandra.ssl=TRUE
However, I think it keeps defaulting to pushing to some local tomcat jdbc. I'm not really sure where to start. Any help is appreciated! Thanks.
Your code doesn't have anything to use Cassandra. It doesn't have any of the dependencies and the ItemWriter implementation is a JdbcBatchItemWriter which I don't think will work for Cassandra. You need to configure your application to actually use Cassandra (the spring data starter as well as an ItemWriter implementation that can write to Cassandra).

Web app with EF + database first not working on Azure

I have a ASP.NET MVC application which uses EF (v6) as data access layer. My application works fine on IIS Express and also when deployed to the server running IIS 7.5.
The problem is that I'm getting the following exception when I deploy it to Azure (Web Sites).
Code generated using the T4 templates for Database First and Model First development may not work correctly if used in Code First mode. To continue using Database First or Model First ensure that the Entity Framework connection string is specified in the config file of executing application. To use these classes, that were generated from Database First or Model First, with Code First add any additional configuration using attributes or the DbModelBuilder API and then remove the code that throws this exception.
I've searched the web and I made sure my connection string starts with "metadata=" + checked my db context class' constructor to be sure it contains the correct name (in my case it's "name=PsDataEntities"))
My connection string looks like this: <add name="PsDataEntities" connectionString="metadata=res://*/PsDataModel.csdl|res://*/PsDataModel.ssdl|res://*/PsDataModel.msl;
provider=System.Data.SqlClient;
provider connection string="data source=SERVER_NAME;initial catalog=DB_NAME;user id=UID;password=PWD;
MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
Anybody had the same problems?
Any help is appreciated
I did a few more tests (like changing metadata in the connection string to use fully qualified names instead of '*') without success, then I decided to set my metadata (regarding .csdl/.ssdl/.msl) programatically with the help from this post. Application now works correctly when deployed to Azure.

How to use Apache-Commons DBCP with EclipseLink JPA and Tomcat 7.x

I've been working on a web application, deployed on Tomcat 7, which use EclipseLink JPA to handle the persistence layer.
Everything works fine in a test environment but we're having serious issues in the production environment due to a firewall cutting killing inactive connections. Basically if a connection is inactive for a while a firewall the sits between the Tomcat server and the DB server kill it, with the result of leaving "stale" connections in the pool.
The next time that connection is used the code never returns, until it gets a "Connection timed out" SQLException (full ex.getMessage() below).
EL Fine]: 2012-07-13
18:24:39.479--ServerSession(309463268)--Connection(69352859)--Thread(Thread[http-bio-8080-exec-5,5,main])--
MY QUERY REPLACED TO POST IT TO SO [EL Config]: 2012-07-13
18:40:10.229--ServerSession(309463268)--Connection(69352859)--Thread(Thread[http-bio-8080-exec-5,5,main])--disconnect
[EL Info]: 2012-07-13
18:40:10.23--UnitOfWork(1062365884)--Thread(Thread[http-bio-8080-exec-5,5,main])--Communication
failure detected when attempting to perform read query outside of a
transaction. Attempting to retry query. Error was: Exception
[EclipseLink-4002] (Eclipse Persistence Services -
2.3.0.v20110604-r9504): org.eclipse.persistence.exceptions.DatabaseException Internal
Exception: java.sql.SQLException: Eccezione IO: Connection timed out
I already tried several configuration in the persistence.xml, but since I have no access to the firewall configuration I had no luck with these methods. I also tried to use setCheckConnections()
ConnectionPool cp = ((JpaEntityManager)em).getServerSession().getDefaultConnectionPool();
cp.setCheckConnections();
cp.releaseConnection(cp.acquireConnection());
I managed to solve the issue in a test script using testOnBorrow, testWhileIdle and other features that are avalaible from DBCP Apache Commons. I'd like to know how to override the EclipseLink internal connection pool to use a custom connection pool so that I can provide an already configured pool, based on DBCP rather than just configuring the internal one using persistence.xml.
I know I should provide a SessionCustomizer, I'm uncertain which one is the correct pattern to use. Basically I would like to preserve the performance of DBCP in a JPA-like way.
I'm deploying on Tomcat 7, I know that if I switch to GF I won't have this problem, but for a matter of consistency with other webapp on the same server I'd prefere to stay on Tomcat.
What you want is definitely possible, but you might be hitting the limits of the "do it yourself" approach.
This is one of the more difficult things to explain, but there are effectively two ways to configure your EntityManagerFactory. The "do it yourself" approach and the "container" approach.
When you call Persistence.createEntityManagerFactory it eventually delegates to this method of the PersistenceProvider interface implemented by EclipseLink:
EntityManagerFactory createEntityManagerFactory(String emName, Map map)
The deal here is EclipseLink will then take it upon itself to do all the work, including its own connection creation and handling. This is the "do it yourself" approach. I don't know EclipseLink well enough to know if there is a way to feed it connections using this approach. After two days on Stackoverflow it doesn't seem like anyone else has that info either.
So here is why this "works in GF". When you let the container create the EntityManagerFactory for you by having it injected or looking it up, the container uses a different method on the PersistenceProvider interface implemented by EclipseLink:
EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map map)
The long and short of it is that this PersistenceUnitInfo is an interface that the container implements and has these two very key methods on it:
public DataSource getJtaDataSource();
public DataSource getNonJtaDataSource();
With this mode EclipseLink will not try to do its own connection handling and will simply call these methods to get the DataSource from the container. This is really what you need.
There are two possible approaches you could take to solving this:
You could attempt to instantiate the EclipseLink PersistenceProvider implementation yourself and call the createContainerEntityManagerFactory method passing in your own implementation of the PersistenceUnitInfo interface and feed the DBCP configured DataSource instances into EclipseLink that way. You would need to parse the persistence.xml file yourself and feed that data in through the PersistenceUnitInfo. As well EclipseLink might also expect a TransactionManager, in which case you'll be stuck unless you hunt down a TransactionManager you can add to Tomcat.
You could use the Java EE 6 certified version of Tomcat, TomEE. DataSources are configured in the tomee.xml, created using DBCP with full support for all the options you need, and passed to the PersistenceProvider using the described createContainerEntityManagerFactory call. You then get the EntityManagerFactory injected via #PersistenceUnit or look it up.
If you do attempt to use TomEE, make sure your persistence.xml is updated to explicitly set transaction-type="RESOURCE_LOCAL" because the default is JTA. Even though it's non-compliant to use JTA with the Persistence.createEntityManagerFactory approach, there aren't any persistence providers that will complain and let you know you're doing something wrong, they treat it as RESOURCE_LOCAL ignoring the schema. So when you go to port your app to an actual certified server, it blows up.
Another note on TomEE is that in the current release, you'll have to put your EclipseLink libs in the <tomcat>/lib/ directory. This is fixed in trunk, just not released yet.
I'm not sure how useful these slides will be without the explanation that goes along with them, but the second part of this presentation is a deep dive into how container-managed EntityManager's work, specifically with regards to connection handling and transactions. You can ignore the transaction part as you aren't using them and already have an in production you're not likely to dramatically change, but it might be interesting for future development.
Best of luck!

Best way to store Database configuration parameters?

I'm developing a web application at the moment. The web application needs to access a Patients database, which for now is a simple MySQL database but may likely be replaced by some other DB (or data source) in the future. At the moment, everything is hardcoded but I would like to have some way to configure the DB connection (that is, the database URL, user, password etc.).
What would be a simple and straightforward solution? It would be good if I could change the configuration by simple editing of a file.
I've seen there's the Properties API as well as Preferences. Or is there some idiom concerning servlets/web apps?
A servlet is part of a web app, and this web app is deployed in a Java EE container (Tomcat, WebLogic, etc.).
The standard way to get a database connection is to use JNDI to get a DataSource instance, and to ask a connection to this DataSource. The DataSource, most of the time, will pool database connections to avoid creating and closing too many connections and thus be much faster :
Context initCtx = new InitialContext();
DataSource dataSource = (DataSource) initCtx.lookup("java:comp/env/jdbc/MyDataSource");
Connection c = dataSource.getConnection();
try {
// ...
}
finally {
c.close(); // makes the connection available for a new thread
}
The DataSource will have to be declared in the web.xml file:
<resource-ref>
<description>Datasource example</description>
<res-ref-name>jdbc/MyDataSource</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
It will have to be defined (with its URL, number of connections, user, password, settings, etc.) inside your Java EE container. This is where it depends on your container.
Read the following explanations for Tomcat : http://tomcat.apache.org/tomcat-7.0-doc/jndi-datasource-examples-howto.html
I think a configuration XML along with your web application is a good idea. Each time the application is initiated by a new request the configuration is loaded and the database connection information available from any internal context that you make.
On IIS this is a standard way through the Web.config file.
regards

How to perform direct HQL queries on grails hibernate DB for test purposes in Eclipse

For testing purposes, I'd like to have a console where I can just enter an HQL command and see what it returns on the grails hibernate DB (in my case a MySQL DB) while it's running e.g. in the test environment. What's the best way to do that?
I'm using Eclipse and already came across the JBoss Hibernate Tools, but I'm not sure how to configure them to use my grails MySQL DB. What Type (Core, Annotations, JPA) do I have to choose there and what to fill in the 'Configuration File' / 'Persistence unit' fields? I already set up a property file (see below).
hibernate.connection.username=sa
hibernate.connection.password=
hibernate.connection.driver_class=org.hsqldb.jdbcDriver
hibernate.connection.url=jdbc:mysql://localhost/myproject
hibernate.connection.provider_class=org.hibernate.connection.DriverManagerConnectionProvider
But is this the best approach anyway?
I am not 100% sure if your close, but the Driver_class property is wrong for MySQL. Try
hibernate.connection.username=sa
hibernate.connection.password=
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.url=jdbc:mysql://localhost/myproject
hibernate.connection.provider_class=org.hibernate.connection.DriverManagerConnectionProvider
The Class needs to be com.mysql.jdbc.Driver
Hope this helps