Spring and JPA with two data sources (with annotations)

A few days I received a comment from my friend @sock_osg (you can follow on twitter) he recommends me to rewrite my previous post with annotations.

And well here is it. But the are more few things to comment about it, for example in the previous post there are not a Transactional capabilities between DB’s because I’m not using JTA transaction type.

Now for this example I write the code to support transactions between multiple data bases with different data sources, like I read on stack overflow:

if you find yourself with multiple entity managers, with corresponding tx managers, then you should consider using a single JtaTransactionManager instead. The entity managers should be able to participate in JTA transactions, and this will give you full transactionality across both entity managers, without having to worry about which entity manager you’re in at any one time.

You can download all code here, it’s hosted on my Github account, pull the code from the branch named «annotations».

Let’s review the most important files, first the DAO classes: Seguir leyendo

Spring and JPA with two data sources

JPA it’s the most used standard in java to manage the persistence and I ever want to write about this topic.

In this entry I want to share how configure a java project to use JPA with spring with two data sources, you can view all source of this project on my github repository.

Most of the configuration is in spring, in the application context you need declare:

  • 2 Data Sources
  • 2 Entity Manager Factories
  • 2 Transaction Manager

This is explained by self:

Seguir leyendo

Hibernate / JPA Clear Cache

Manejar persistencia puede ser un poco complejo si no se conoce el funcionamientos de los caches, generalmente cuando tienes configurado el framework para utilizarlos tienes que actualizar los datos obligatoriamente desde el código de tu aplicación.

Si por alguna razón los datos son actualizados en la base de datos y el framework no tiene conocimiento de estos cambios, en el cache vas a tener la información vieja e inconsistente.

Esto NO es un error, depende de la forma en como configuras tus querys y de la arquitectura de tu aplicación.

Para poder indicarle al framework que se ejecute el refresh de forma manual al cache de Nivel 1 puedes hacerlo mediente el siguiente código:

@PersistenceContext
private EntityManager emf;
@Override
public void refreshJPACache() {
emf.clear();
}
  • Para JPA obtienes la referencia al EntityManager o EntityManagerFactory y ejecutas el método clear().
  • Para Hibernate debes utilizar el método evict().

Es muy importante conocer en que puntos de tu aplicación debes utilizar el cache ya que puede ser integral en todas tus consultas, por entidades o por querys.

Lo recomendable es aplicarlo en consultas recurrentes o de catálogos.

Referencias:

Saludos!

EJB 3 Overview


Recientenmente he tenido que analizar un proyecto web que se encuentra divido en dos partes (backend y frontend), el entregable es un ear con un jar y un war.

Todo el backend esta constriudo con EJB’s y aunque siempre he escuchado pestes de esta tecnología nunca le he dado un vistazo. Así que comencé por leer algunos artículos y en realidad me parece que los EJB’s son una buena iniciativa en Java para simplificar el desarrollo y adoptar mejores prácticas. Particularmente me ha encantado este:

http://refcardz.dzone.com/refcardz/dependency-injection-in-ejb3 Seguir leyendo