Liquibase + JPA: Run order - java

I have a Java Project in which I use JPA for persistence.
Now I want to integrate LiquiBase in my project, but I don't know how to change the order JPA/Liquibase are executed.
For clarity:
Until now my persistence.xml looks like this:
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
<property name="javax.persistence.jdbc.url" value=.../>
<property name="javax.persistence.jdbc.user" value=.../>
<property name="eclipselink.ddl-generation" value="create-or-extend-tables"/>
I now tried to set:
<property name="eclipselink.ddl-generation" value="none"/>
so that liquibase handles all the database-stuff.
But now when I run my Code, JPA throws an Error because some tables are missing, although these tables should be created by liquibase, which leads me to believe that JPA is running before liquibase.
How do I change that order?
Until now, Liquibase is executed in code via this lines:
java.sql.Connection connection = openConnection(); //your openConnection logic here
Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
Liquibase liquibase = new liquibase.Liquibase("path/to/changelog.xml", new ClassLoaderResourceAccessor(), database);
liquibase.update(new Contexts(), new LabelExpression());
I read somewhere that this could be achieved via Liquibase Servlet listener, but that requires the database data-source, and I dont know how to get that.
Liquibase itself works fine.

If you want to run Liquibase as part of your application I recommend to use one of the options documented in the "Automated" section:
http://www.liquibase.org/documentation/running.html
Servlet Listener
Spring Listener
JEE CDI Listener
If you're developing a Java EE application, first create a data source:
https://docs.oracle.com/javaee/7/tutorial/resource-creation002.htm
Note that this is application server specific.
Since Java EE 6 there is now also an application server independent annotation which can be used: http://docs.oracle.com/javaee/7/api/javax/annotation/sql/DataSourceDefinition.html
In your persistence.xml I suggest to use transaction-type="JTA" and reference the data source using:
<jta-data-source>jdbc/someDB</jta-data-source>
Omit the part:
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
<property name="javax.persistence.jdbc.url" value=.../>
<property name="javax.persistence.jdbc.user" value=.../>

Related

Hibernate creating Schemas on each application run?

I have built a web application using MVC pattern and Hibernate. I am trying to configure my hibernate to create schemas for my classes by using following property
<property name="hibernate.hbm2ddl.auto">create</property>
But, I found out that this drops the previous existing schema and re-creates schema on each application run. Is there anyway I configure my hibernate to create schemas only on my first application run and for any future application run just update the rows in existing database?
As YomanTaMero mentioned instead of :
<property name="hibernate.hbm2ddl.auto">create</property>
try this:
<property name="hibernate.hbm2ddl.auto">update</property>
Noticed "update" above?

Shutdown Derby database using JPA not DriverManager

I have an RCP client application that uses embedded Derby in the same JVM for persistence. I access it via JPA using RESOURCE_LOCAL and Eclipse Link as a JPA provider. I leave starting the Derby instance to JPA and persistence.xml.
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME, props);
Persistence.xml
<properties>
<property name="eclipse.weaving" value="false" />
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver" />
<property name="javax.persistence.jdbc.url" value="jdbc:derby:pathToDb" />
<property name="eclipselink.logging.level.sql" value="FINEST" />
<property name="eclipselink.logging.parameters" value="true" />
</properties>
At one point in the application, I need to stop the underlying Derby database. All of the examples show calling:
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
DriverManager.getConnection("jdbc:derby:pathToDb;shutdown=true");
This is problematic, especially in an RCP application with multiple class loaders (it uses OSGI under the covers). I have tried using
if (factory.isOpen())
factory.close();
but this does not shutdown the Derby instance, only the JPA connection to it.
Is there a way, using JPA, to shutdown the underlying Derby instance?
Update
I tried using the OSGI console to stop the persistence related bundles including javax.persistence, JPA and Derby. Stopping these did not release the file locks that Derby put on log files.
Update 2
Revised to clarify that the use is not in an OSGI server application.
The issue was not the classloader but an import issue.
An RCP application has a "target platform" that is dynamically searched by the framework for dependencies. This does not happen when calling Class.forName(). Once I explicitly added the Derby jar to my bundle's dependencies, the class was found and the database is shutting down properly.
Lesson learned: check the simple stuff before assuming it is hard!

Play Framework 1 hibernate integration

I am using Play 1.2.5. I am using hibernate in my play project. I have added the database info in application.conf as follows
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/dbname
db.user=username
db.pass=password
Also I have added the database info in the hibernate.cfg.xml under the conf folder as follows,
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/dbname</property>
<property name="hibernate.connection.username">username</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
My application is running properly but I am not sure whether it is a good practise to define the db connections in both the files. Is there a way to define the db connection in a single place. Please correct me if I am wrong.
You don't need a Hibernate mapping file. Mapping is specified using JPA annotations on your model classes.
Have a read of the guide to get started.

Spring’s embedded H2 datasource and DB_CLOSE_ON_EXIT

For unit tests (call them integration tests if you want) I have configured an embedded database in my Spring config like so:
<jdbc:embedded-database id="dataSource" type="H2">
<jdbc:script location="classpath:schema_h2.sql" />
</jdbc:embedded-database>
Now, when running the tests from the command line, they work fine, but I get some errors at the end (harmless, but irritating):
WARN 2013-03-25 12:20:22,656 [Thread-9] o.s.j.d.e.H2EmbeddedDatabaseConfigurer 'Could not shutdown embedded database'
org.h2.jdbc.JdbcSQLException: Database is already closed (to disable automatic closing at VM shutdown, add ";DB_CLOSE_ON_EXIT=FALSE" to the db URL) [90121-170]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:329) ~[h2-1.3.170.jar:1.3.170]
...
at org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFactoryBean.destroy(EmbeddedDatabaseFactoryBean.java:65) [spring-jdbc-3.2.1.RELEASE.jar:3.2.1.RELEASE]
at org.springframework.beans.factory.support.DisposableBeanAdapter.destroy(DisposableBeanAdapter.java:238) [spring-beans-3.2.1.RELEASE.jar:3.2.1.RELEASE]
Now the tip contained in the exception is fine in general, but how do I add this attribute to the embedded datasource? Do I have to expand it, configure it by hand so to speak, to add such ‘advanced’ features?
Specify parameter in JDBC url jdbc:h2:~/test;DB_CLOSE_ON_EXIT=FALSE
Also for in-memory test database I suggest you to add DB_CLOSE_DELAY=-1, like this:
jdbc:h2:mem:alm;MODE=Oracle;DB_CLOSE_DELAY=-1
To add JDBC connection url to embedded-dababase change it to:
<bean id="dataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
<property name="driverClass" value="org.h2.Driver"/>
<property name="url" value="jdbc:h2:mem:test;MODE=Oracle;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"/>
<property name="username" value="sa"/>
<property name="password" value=""/>
</bean>
<jdbc:initialize-database data-source="dataSource" ignore-failures="DROPS">
<jdbc:script location="classpath:schema_h2.sql" />
</jdbc:initialize-database>
I had the same issue as Michael Piefel's one and tried to implement the solution that Michail Nikolaev explained.
but it did not work, somehow spring-batch, then, where are the metadata JOB_* tables are.
So, as the version of spring-jdbc used by my application is 3.0.5 and increasing the spring-framework one enters in conflict with dwr (i use it in my app) it's a geo localization based on spring, dwr and gmaps api.
I downloaded the spring-jdbc 4.0.3 release and get from it the H2EmbeddedDatabaseConfigurer.class who has DB_CLOSE_ON_EXIT=FALSE by default and replace with it the one on the spring-jdbc 3.0.5 Release and deploy-it in the war file and it works, the shutdown of the VM didn't provoke the closing of the in-memory database.
Hope this unusual solution helps if other people like me wouldn't be able to implement the other solution.
I had the same problem, but it was because I forgot to add the annotation #Entity on one of my entities. I add it and it work now !
I hope this helps someone.

Oracle connections in Spring

I am using Oracle 9 JDBC Thin Driver - the connection string I have used for standard JDBC was:
jdbcConn.connect("jdbc:oracle:thin:myDevDb/myDevDb#fooServer:1521:MYSIDNAME");
...just trying to get my head around using this kind of connection in Spring 2.5.
How do you wire up Spring to an Oracle connection - think it has something to do with an XML conifg file but not sure, there seems to be a couple of ways to do it.
Any help much appreciated...
LATEST EDIT
Thanks to those who have responded so far - but I need a bit of a "leg up" - on the part where you configure in the database connection string setup in your config, where do you put this info, and how?
I have an existing Java web application - and I am trying to get to grips with how I 'shoehorn' Spring into my existing app.
There are a few ways of doing this and it depends on what your environment is. If you're using Spring there's a fair chance you're deploying a Web application or you're otherwise in a J2EE environment. If this is the case (and arguably even if it isn't) you probably want to configure a DataSource.
This is a fairly minimal solution:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
The above is using the Apache (Jakarta Commons) database connection pooling but your appserver probably has an alternative you may want to use instead. Also, different database vendors have their own data source implementations too (eg OracleDataSource and OracleXADataSource for Oracle).
Note the use of properties like jdbc.username. This is a typical configuration because database configurations typically vary between environment. You can activate a property configurator with something like:
<bean id="jdbcConfiguration" class="org.springframework.beans.factory.config.PropertiesPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties"/>
</bean>
Now you probably want transactions too I would imagine. The easiest way is to use a platform transaction manager but, like with most things Spring, there are multiple ways of doing it.
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
After this you can use this bean directly or (arguably more common) you can use declarative transactions with AOP (annotations).
More on these subjects in the (superb) Spring reference documentation.

Categories