New layout: graphics, css, few improvements, ..

YarentY

www.yarenty.com - projects incubator

JPA – OSGi – Hibernate – JDK6 (part 1) PDF Print E-mail
Written by yarenty   
Thursday, 25 June 2009 11:40
Article Index
JPA – OSGi – Hibernate – JDK6 (part 1)
Running in OSGi container
Hacking Hibernate bundles
All Pages

I want to write some Eclipse application – RCP.

As eclipse in background uses Eqionox Osgi implementation, packages that I want to use should be: bundles or libraries inside bundles.

I decide to use separate bundles – as I don’t know the future of application, and I belive managing them will be much easier.

I’m using: JDK6, Eclipse RCP, Hibernate, MySQL.

In first part - I create hacked version of available bundles - just to start using them, and to prove exactly which bundles need some work to do.

 

Goal: 

Run JPA with Hibernate as persistence provider under OSGi container - as Eclipse RCP applications use Equinox.

Issues:

  1. Hibernate EJB  is not compatible with OSGi: org.hibernate.ejb.HibernatePersistence is looking for /META-INF/persistence.xml in classpath – in OSGi each bundle (jar) have it’s own classpath
  2. Hibernate is using ANTLR, antlr is bundle and in OSGi container other packages that are not declared in manifest are not visible for them. Solution add DynamicImport-Package: * - really breaks OSGi rules but works, or better add packages that should be visible by antlr in fragment bundle.

 

Let s start from beginning.

 I want to write some Eclipse application – RCP. As eclipse in background uses Eqionox Osgi implementation, packages that I want to use should be: bundles or libraries inside of your bundles.

 I decide to use separate bundles – as I don’t know the future of application, and I belive Peter that managing will be much easier.

 

So I’m going to springsource.com/repository and just start downloading first thousand libraries: (using maven does much simplier that task ;-) )

 

com.springsource.antlr-2.7.7.jar

com.springsource.com.mysql.jdbc_5.1.6.jar

com.springsource.javassist-3.3.0.ga.jar

com.springsource.javax.activation-1.1.1.jar

com.springsource.javax.ejb-3.0.0.jar

com.springsource.javax.persistence-1.99.0.jar

com.springsource.javax.servlet-2.5.0.jar

com.springsource.javax.transaction-1.1.0.jar

com.springsource.javax.xml.rpc-1.1.0.jar

com.springsource.javax.xml.soap-1.3.0.jar

com.springsource.javax.xml.stream-1.0.1.jar

com.springsource.net.sf.cglib-2.1.3.jar

com.springsource.org.apache.commons.collections-3.2.1.jar

com.springsource.org.apache.commons.logging-1.1.1.jar

com.springsource.org.dom4j-1.6.1.jar

com.springsource.org.hibernate-3.3.1.GA.jar

com.springsource.org.hibernate.annotations-3.4.0.GA.jar

com.springsource.org.hibernate.annotations.common-3.3.0.ga.jar

com.springsource.org.hibernate.ejb-3.4.0.GA.jar

com.springsource.org.hibernate.validator-3.1.0.GA.jar

com.springsource.org.jboss.util-2.0.4.GA.jar

com.springsource.org.jgroups-2.5.1.jar

com.springsource.org.objectweb.asm-1.5.3.jar

com.springsource.org.objectweb.asm.attrs-1.5.3.jar

com.springsource.slf4j.api-1.5.6.jar

com.springsource.slf4j.jcl-1.5.6.jar

org.hibernate.ejb-library-3.3.2.GA.libd

 

As soon its looks good.

 

In Eclipse (with JPA plugin, and Hibernate Tool) I create my simple project – dao and domain.

 

Domain – user class:

 

package com.yarenty.eireshop.domain;

 

// Generated 10-Jun-2009 12:37:35 by Hibernate Tools 3.2.4.GA

 

import java.util.Date;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import static javax.persistence.GenerationType.IDENTITY;

import javax.persistence.Id;

import javax.persistence.Table;

import javax.persistence.Temporal;

import javax.persistence.TemporalType;

import javax.persistence.Transient;

import javax.persistence.UniqueConstraint;

 

/**

 * User generated by hbm2java

 */

@Entity(name="eire_users")

@Table(name = "eire_users", uniqueConstraints = @UniqueConstraint(columnNames = "username"))

public class User implements java.io.Serializable {

 

      private Long id;

      private Integer location;

      private String username;

      private String pass;

      private String email;

      private String firstName;

      private String lastName;

      private Integer userClass;

      private Boolean active;

      private Date createdDate;

      private Date lastModified;

 

      public User() {

      }

 

      public User(Integer location) {

            this.location = location;

      }

 

      public User(Integer location, String username,

            String pass, String email,

            String firstName, String lastName, Integer userClass,

            Boolean active, Date createdDate, Date lastModified) {

            this.location = location;

            this.username = username;

            this.pass = pass;

            this.email = email;

            this.firstName = firstName;

            this.lastName = lastName;

            this.userClass = userClass;

            this.active = active;

            this.createdDate = createdDate;

            this.lastModified = lastModified;

      }

 

      @Id

      @GeneratedValue(strategy = IDENTITY)

      @Column(name = "id", unique = true, nullable = false)

      public Long getId() {

            return this.id;

      }

 

      public void setId(Long id) {

            this.id = id;

      }

 

      @Column(name = "location_id", nullable = false)

      public Integer getLocation() {

            return this.location;

      }

 

      public void setLocation(Integer location) {

            this.location = location;

      }

 

      @Column(name = "username", unique = true, length = 60)

      public String getUsername() {

            return this.username;

      }

 

      public void setUsername(String username) {

            this.username = username;

      }

 

      @Column(name = "pass", length = 60)

      public String getPass() {

            return this.pass;

      }

 

      public void setPass(String pass) {

            this.pass = pass;

      }

 

      @Column(name = "email")

      public String getEmail() {

            return this.email;

      }

 

      public void setEmail(String email) {

            this.email = email;

      }

 

      @Column(name = "firstname", length = 100)

      public String getFirstName() {

            return this.firstName;

      }

 

      public void setFirstName(String firstName) {

            this.firstName = firstName;

      }

 

      @Column(name = "lastname", length = 100)

      public String getLastName() {

            return this.lastName;

      }

 

      public void setLastName(String lastName) {

            this.lastName = lastName;

      }

 

      @Column(name = "class")

      public Integer getUserClass() {

            return this.userClass;

      }

 

      public void setUserClass(Integer userClass) {

            this.userClass = userClass;

      }

 

      @Column(name = "active")

      public Boolean getActive() {

            return this.active;

      }

 

      public void setActive(Boolean active) {

            this.active = active;

      }

 

      @Temporal(TemporalType.TIMESTAMP)

      @Column(name = "created", length = 19)

      public Date getCreatedDate() {

            return this.createdDate;

      }

 

      public void setCreatedDate(Date createdDate) {

            this.createdDate = createdDate;

      }

 

      @Temporal(TemporalType.TIMESTAMP)

      @Column(name = "modified", length = 19)

      public Date getLastModified() {

            return this.lastModified;

      }

 

      public void setLastModified(Date lastModified) {

            this.lastModified = lastModified;

      }

 

      /**

       * @see java.lang.Object#toString()

       */

      @Override

      @Transient

      public String toString() {

            StringBuffer buffer = new StringBuffer();

            buffer.append(getUsername())

            .append("[").append(getId()).append("] - ")

            .append(getFirstName()).append(" ")

            .append(getLastName()).append(" ")

            .append("<").append(getEmail()).append(">, ")

            .append("created: ").append(getCreatedDate());

            return buffer.toString();

      }

}

 

Changed toString() method – I need more information to display ;-)

 

 

And UserHome:

package com.yarenty.eireshop.dao.impl;

 

// Generated 10-Jun-2009 12:37:36 by Hibernate Tools 3.2.4.GA

 

import java.util.List;

 

import javax.ejb.Stateless;

import javax.persistence.EntityManager;

import javax.persistence.PersistenceContext;

import javax.persistence.Query;

 

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

 

import com.yarenty.eireshop.dao.helper.HibernateHelper;

import com.yarenty.eireshop.dao.helper.JPAHelper;

import com.yarenty.eireshop.domain.User;

 

/**

 * Home object for domain model class User.

 * @see com.yarenty.eireshop.domain.User

 * @author Hibernate Tools

 */

@Stateless

public class UserHome {

 

      private static final Log log = LogFactory.getLog(UserHome.class);

 

      @PersistenceContext

      private static EntityManager entityManager;

     

 

      public void persist(User transientInstance) {

            log.debug("persisting User instance");

            try {

                  entityManager.persist(transientInstance);

                  log.debug("persist successful");

            } catch (RuntimeException re) {

                  log.error("persist failed", re);

                  throw re;

            }

      }

 

      public void remove(User persistentInstance) {

            log.debug("removing User instance");

            try {

                  entityManager.remove(persistentInstance);

                  log.debug("remove successful");

            } catch (RuntimeException re) {

                  log.error("remove failed", re);

                  throw re;

            }

      }

 

      public User merge(User detachedInstance) {

            log.debug("merging User instance");

            try {

                  User result = entityManager.merge(

                                     detachedInstance);

                  log.debug("merge successful");

                  return result;

            } catch (RuntimeException re) {

                  log.error("merge failed", re);

                  throw re;

            }

      }

 

      public User findById(Long id) {

            log.debug("getting User instance with id: " + id);

            try {

                  User instance = entityManager.find(User.class, id);

                  log.debug("get successful");

                  return instance;

            } catch (RuntimeException re) {

                  log.error("get failed", re);

                  throw re;

            }

      }

           

      public List<User> getAll() {

            String SQL_QUERY = " from eire_users user ";

            Query query = entityManager.createQuery(SQL_QUERY);

            return query.getResultList();

      }

}

 

 

 

And I create JPA Helper:

 

package com.yarenty.eireshop.dao.helper;

 

import java.util.List;

import java.util.Properties;

 

import javax.persistence.EntityManager;

import javax.persistence.EntityManagerFactory;

import javax.persistence.EntityTransaction;

import javax.persistence.Persistence;

 

/**

 * @author yarenty

 *

 */

public class JPAHelper {

     

      static EntityManagerFactory emf;

     

      static {

            emf = Persistence

                .createEntityManagerFactory("eireshop");

      }

 

      public static EntityManager getEntityManager() throws Exception{

            return emf.createEntityManager();

      }

 

      public static void shutdown(){

            emf.close();

      }

 

      public static void persist(Object o) {

            EntityManager em = emf.createEntityManager();

            EntityTransaction et = em.getTransaction();

            et.begin();

            em.persist(o);

            et.commit();

            em.close();

      }

           

     

      public static List<?> getAll( Object ob) {

            EntityManager em = emf.createEntityManager();

            EntityTransaction et = em.getTransaction();

            et.begin();

            List<?> obj = (List<?>) em.find(ob.getClass(), ob);

            et.commit();

            em.close();

            return obj;

      }

}

 

 

So to work I put static initializer into UserHome

      static {

            try {

                  entityManager = JPAHelper.getEntityManager();

            } catch (Exception e) {

                  // TODO Auto-generated catch block

                  e.printStackTrace();

            }

      }

 

 

Test class:

 

      public static void main(String[] args) {

 

            List<User> users =  new UserHome().getAll();

            for (User user2 : users) {

                  System.out.println(user2);

            }

 

 

 

Persistance.xml:

 

 

<?xml version="1.0" encoding="UTF-8"?>

<persistence version="1.0"

      xmlns="http://java.sun.com/xml/ns/persistence"

      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

      xsi:schemaLocation="http://java.sun.com/xml/ns/persistence

      http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">

 

 

      <persistence-unit name="eireshop"

                 transaction-type="RESOURCE_LOCAL">

            <provider>org.hibernate.ejb.HibernatePersistence</provider>

            <class>com.yarenty.eireshop.domain.User</class>

            <exclude-unlisted-classes>false</exclude-unlisted-classes>

            <properties>

                  <property name="hibernate.connection.username"

                     value="root" />

                  <property name="hibernate.connection.password"  

                     value="" />

                  <property name="hibernate.connection.pool_size"

                     value="10" />

                  <property name="show_sql" value="true" />

                  <property name="dialect"  

                     value="org.hibernate.dialect.MySQLDialect" />

                  <property name="hibernate.hbm2ddl.auto"

                     value="update" />

                  <property name="hibernate.dialect"

                     value="org.hibernate.dialect.MySQLDialect" />

                  <property name="hibernate.default_catalog"

                     value="eire" />

                  <property name="catalog" value="eire" />

                  <property name="hibernate.connection.driver_class"

                     value="com.mysql.jdbc.Driver" />

                  <property name="hibernate.connection.url"

                     value="jdbc:mysql://localhost/eire"/>

            </properties>

 

      </persistence-unit>

</persistence>

 

 

And check:

 

24-Jun-2009 11:07:26 org.slf4j.impl.JCLLoggerAdapter info

INFO: Hibernate Annotations 3.4.0.GA

24-Jun-2009 11:07:26 org.slf4j.impl.JCLLoggerAdapter info

INFO: Hibernate 3.3.1.GA

24-Jun-2009 11:07:26 org.slf4j.impl.JCLLoggerAdapter info

INFO: hibernate.properties not found

24-Jun-2009 11:07:26 org.slf4j.impl.JCLLoggerAdapter info

INFO: Bytecode provider name : javassist

24-Jun-2009 11:07:26 org.slf4j.impl.JCLLoggerAdapter info

INFO: using JDK 1.4 java.sql.Timestamp handling

24-Jun-2009 11:07:26 org.slf4j.impl.JCLLoggerAdapter info

INFO: Hibernate EntityManager 3.4.0.GA

24-Jun-2009 11:07:26 org.slf4j.impl.JCLLoggerAdapter info

INFO: Binding entity from annotated class: com.yarenty.eireshop.domain.User

24-Jun-2009 11:07:26 org.slf4j.impl.JCLLoggerAdapter info

INFO: Bind entity com.yarenty.eireshop.domain.User on table eire_users

24-Jun-2009 11:07:26 org.slf4j.impl.JCLLoggerAdapter info

INFO: Hibernate Validator 3.1.0.GA

24-Jun-2009 11:07:26 org.slf4j.impl.JCLLoggerAdapter info

INFO: Unable to find org.hibernate.search.event.FullTextIndexEventListener on the classpath. Hibernate Search is not enabled.

24-Jun-2009 11:07:26 org.slf4j.impl.JCLLoggerAdapter info

INFO: Using Hibernate built-in connection pool (not for production use!)

24-Jun-2009 11:07:26 org.slf4j.impl.JCLLoggerAdapter info

INFO: Hibernate connection pool size: 10

24-Jun-2009 11:07:26 org.slf4j.impl.JCLLoggerAdapter info

INFO: autocommit mode: true

24-Jun-2009 11:07:26 org.slf4j.impl.JCLLoggerAdapter info

INFO: using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost/eire

24-Jun-2009 11:07:26 org.slf4j.impl.JCLLoggerAdapter info

INFO: connection properties: {user=root, password=****, autocommit=true, release_mode=auto}

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: RDBMS: MySQL, version: 5.0.51b-community-nt

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-5.1.6 ( Revision: ${svn.Revision} )

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: Using dialect: org.hibernate.dialect.MySQLDialect

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: Transaction strategy: org.hibernate.transaction.JDBCTransactionFactory

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: Automatic flush during beforeCompletion(): disabled

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: Automatic session close at end of transaction: disabled

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: JDBC batch size: 15

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: JDBC batch updates for versioned data: disabled

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: Scrollable result sets: enabled

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: JDBC3 getGeneratedKeys(): enabled

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: Connection release mode: auto

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: Default catalog: ncards_jvd

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: Maximum outer join fetch depth: 2

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: Default batch fetch size: 1

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: Generate SQL with comments: disabled

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: Order SQL updates by primary key: disabled

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: Order SQL inserts for batching: disabled

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: Using ASTQueryTranslatorFactory

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: Query language substitutions: {}

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: JPA-QL strict compliance: enabled

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: Second-level cache: enabled

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: Query cache: disabled

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: Optimize cache for minimal puts: disabled

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: Structured second-level cache entries: disabled

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: Statistics: disabled

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: Deleted entity synthetic identifier rollback: disabled

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: Default entity-mode: pojo

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: Named query checking : enabled

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: building session factory

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: Not binding factory to JNDI, no JNDI name configured

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: Running hbm2ddl schema update

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: fetching database metadata

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: updating schema

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: table found: ncards_jvd.eire_users

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: columns: [id, username, created, email, active, class, lastname, firstname, modified, pass, location_id]

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: foreign keys: []

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: indexes: [eire_users_fkindex1, primary, users_index4467]

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: table found: ncards_jvd.eire_users

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: columns: [id, username, created, email, active, class, lastname, firstname, modified, pass, location_id]

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: foreign keys: []

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: indexes: [eire_users_fkindex1, primary, users_index4467]

24-Jun-2009 11:07:27 org.slf4j.impl.JCLLoggerAdapter info

INFO: schema update complete

ttest3[null] - John Test <test@t.t>, created: Wed Jun 24 11:07:27 BST 2009

ttest3[null] - Jan Novack <test@t.t>, created: Wed Jun 24 11:07:27 BST 2009

jankom2[2] - Janko Muzykant < This e-mail address is being protected from spambots, you need JavaScript enabled to view it >, created: 2008-05-14 00:09:56.0

qwerty[3] - Qwerty Ytrewq < This e-mail address is being protected from spambots, you need JavaScript enabled to view it >, created: 2008-05-23 22:48:17.0

testowy[6] - Testowy Zygmunt < This e-mail address is being protected from spambots, you need JavaScript enabled to view it >, created: 2008-06-11 09:30:40.0

yarenty[7] - Jaroslaw Nowosad < This e-mail address is being protected from spambots, you need JavaScript enabled to view it >, created: 2008-07-05 23:26:55.0

[..]

 

YEAH!!!

 

Everything is working just perfect…

Why breaking?

…let we just check how it will work if I just provide simple plugin and will start them as Eclipse application.

 

 



When I started eclipse RCP application which trying to use the same code...

 

.. I surprisingly (or not surprisingly) see:

 

javax.persistence.PersistenceException: No Persistence provider for EntityManager named eireshop

      at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:129)

      at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:99)

      at com.yarenty.eireshop.dao.helper.JPAHelper.getEntityManager(JPAHelper.java:59)

 

UPS…

Lets investigate:

Go to Osgi container and display all bundles:

osgi>ss

[..]

162   RESOLVED    com.springsource.org.jboss.util_2.0.4.GA

163   RESOLVED    com.springsource.com.mysql.jdbc_5.1.6

171   RESOLVED    com.springsource.org.jgroups_2.5.1

179   RESOLVED    com.springsource.javax.transaction_1.1.0

205   RESOLVED    com.springsource.org.hibernate.annotations_3.4.0.GA

                  Master=228

208   RESOLVED    com.springsource.org.hibernate.validator_3.1.0.GA

218   ACTIVE      com.yarenty.eireshop.ui_1.0.0

226   ACTIVE      com.springsource.antlr_2.7.7

227   RESOLVED    com.springsource.javax.persistence_1.99.0

228   ACTIVE      com.springsource.org.hibernate_3.3.1.GA

                  Fragments=205, 230

229   RESOLVED    com.springsource.org.hibernate.annotations.common_3.3.0.ga

230   RESOLVED    com.springsource.org.hibernate.ejb_3.4.0.GA

                  Master=228

231   RESOLVED    com.yarenty.erieshop.dao_1.0.0

 

osgi>ss

 

 

All looks OK. But when I check source code for javax.persistence I’ve found that searching persistence providers looking for current thread classloader. That will not work in OSGi as current thread has visibility only for bundles that are declared in manifest.

 

      public Collection<PersistenceProvider> findAllProviders() throws IOException {

     

              ClassLoader loader = Thread.currentThread()

                                    .getContextClassLoader();

              Enumeration<URL> resources = loader

                                .getResources(SERVICE_PROVIDER_FILE);

     

              Set<String> providerNames = new HashSet<String>();

              while (resources.hasMoreElements()) {

                  URL url = resources.nextElement();

                  InputStream is = url.openStream();

                  try {

                        providerNames.addAll(

                            providerNamesFromReader(

                                new BufferedReader(

                                   new InputStreamReader(is))));

                  } finally {

                      is.close();

                  }

              }

              Collection<PersistenceProvider> loadedProviders =

                            new HashSet<PersistenceProvider>(); 

              for (String s : providerNames) {

                  try{

                        loadedProviders

                   .add((PersistenceProvider)loader

                            .loadClass(s).newInstance());

                  } catch (ClassNotFoundException exc){

                  } catch (InstantiationException exc){

                  } catch (IllegalAccessException exc){

                  }

              }

              return loadedProviders;

      }

 

 

But I found that there is javax.persistence.osgi  package, with activator and !!! tracker !!!. And that’s what I’m really looking for:

osgi> start 227

Persistence bundle starting...

Persistence bundle started.

 

 

Lets start one more time but this time with started persistence bundle:

osgi> Persistence bundle starting...

Persistence bundle started.

javax.persistence.PersistenceException: No Persistence provider for EntityManager named eireshop

      at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:129)

      at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:99)

      at com.yarenty.eireshop.dao.helper.JPAHelper.getEntityManager(JPAHelper.java:59)

      at com.yarenty.eireshop.dao.impl.UserHome.<clinit>(UserHome.java:34)

      at com.yarenty.eireshop.ui.View.createPartControl(View.java:115)

      at org.eclipse.ui.internal.ViewReference.createPartHelper(ViewReference.java:371)

      at org.eclipse.ui.internal.ViewReference.createPart(ViewReference.java:230)

      at org.eclipse.ui.internal.WorkbenchPartReference.getPart(WorkbenchPartReference.java:594)

      at org.eclipse.ui.internal.PartPane.setVisible(PartPane.java:306)

OSGi - Find all providers.

 

It’s working but couldn’t find providers.

osgi> Persistence bundle starting...

Persistence bundle started.

OSGi - Find all providers.

 

javax.persistence.PersistenceException: No Persistence provider for EntityManager named eireshop

      at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:129)

      at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:99)

      at com.yarenty.eireshop.dao.helper.JPAHelper.getEntityManager(JPAHelper.java:59)

 

 

 

Ok, if it can’t find them itself – lets help them.In my Dao bundle I create Activator class.

package com.yarenty.eireshop.dao.activator;

 

import java.util.Date;

import java.util.Dictionary;

import java.util.Properties;

 

import org.hibernate.ejb.HibernatePersistence;

import org.osgi.framework.BundleActivator;

import org.osgi.framework.BundleContext;

 

import javax.persistence.spi.PersistenceProvider;

 

/**

 * @author ejarnow

 */

public class Activator implements BundleActivator {

     

      private BundleContext context;

 

      @Override

      public void start(BundleContext context) throws Exception {

     

             System.out.println(

                   "Registering persistence provider ;-)");

 

      Properties properties = new Properties();

      properties.put("javax.persistence.spi.PersistenceProvider",

                     "eireshop");

 

            context.registerService(

                    PersistenceProvider.class.getName(),

                    new HibernatePersistence(),

                    properties);

           

           

      }

 

      @Override

      public void stop(BundleContext context) throws Exception {

      }

 

}

 

 

 

 

And output:

osgi> Persistence bundle starting...

Persistence bundle started.

Registering persistence provider ;-)

ProviderTracker: New service detected...

ProviderTracker: Added service eireshop

24-Jun-2009 12:07:31 org.slf4j.impl.JCLLoggerAdapter info

INFO: Hibernate Annotations 3.4.0.GA

24-Jun-2009 12:07:31 org.slf4j.impl.JCLLoggerAdapter info

INFO: Hibernate 3.3.1.GA

24-Jun-2009 12:07:31 org.slf4j.impl.JCLLoggerAdapter info

INFO: hibernate.properties not found

24-Jun-2009 12:07:31 org.slf4j.impl.JCLLoggerAdapter info

INFO: Bytecode provider name : javassist

24-Jun-2009 12:07:31 org.slf4j.impl.JCLLoggerAdapter info

INFO: using JDK 1.4 java.sql.Timestamp handling

24-Jun-2009 12:07:32 org.slf4j.impl.JCLLoggerAdapter info

INFO: Hibernate EntityManager 3.4.0.GA

24-Jun-2009 12:07:32 org.slf4j.impl.JCLLoggerAdapter info

INFO: Could not find any META-INF/persistence.xml file in the classpath

javax.persistence.PersistenceException: No Persistence provider for EntityManager named eireshop

      at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:129)

      at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:99)

      at com.yarenty.eireshop.dao.helper.JPAHelper.getEntityManager(JPAHelper.java:59)

 

 

[…]

 

 

ProviderTracker: Removing service...

ProviderTracker: Removed service eireshop service object: org.hibernate.ejb.HibernatePersistence@1435ec9

Persistence bundle stopping...

Persistence bundle stopped.

 

 

Persistence looks like working – classes inside hibernate are called. Still provider, are not available, but now we see: “Could not find any META-INF/persistence.xml”

As it really is – tested before - it means some bundle doesn’t see my bundle classpath.

 

Now there are two possibilities:

-          hack them

-          write proper solution

 

First I will hack – it’s much easier and will prove where problem is (without reading gazylinos lines of code ;-) ).

 


 


Hack:

-          I put my persistence.xml into hibernate-ejb fragment bundle, as EntityManager is there.

-          Add DynamicImport-Package:* into hibernate Metainf.fm file.

 

 

osgi> Persistence bundle starting...

Persistence bundle started.

Registering persistence provider ;-)

ProviderTracker: New service detected...

ProviderTracker: Added service eireshop

24-Jun-2009 12:43:45 org.slf4j.impl.JCLLoggerAdapter info

INFO: Hibernate Annotations 3.4.0.GA

24-Jun-2009 12:43:45 org.slf4j.impl.JCLLoggerAdapter info

INFO: Hibernate 3.3.1.GA

24-Jun-2009 12:43:45 org.slf4j.impl.JCLLoggerAdapter info

INFO: hibernate.properties not found

24-Jun-2009 12:43:45 org.slf4j.impl.JCLLoggerAdapter info

INFO: Bytecode provider name : javassist

24-Jun-2009 12:43:45 org.slf4j.impl.JCLLoggerAdapter info

INFO: using JDK 1.4 java.sql.Timestamp handling

24-Jun-2009 12:43:45 org.slf4j.impl.JCLLoggerAdapter info

INFO: Hibernate EntityManager 3.4.0.GA

24-Jun-2009 12:43:45 org.slf4j.impl.JCLLoggerAdapter warn

INFO: Binding entity from annotated class: com.yarenty.eireshop.domain.User

24-Jun-2009 12:43:45 org.slf4j.impl.JCLLoggerAdapter info

INFO: Bind entity com.yarenty.eireshop.domain.User on table eire_users

24-Jun-2009 12:43:45 org.slf4j.impl.JCLLoggerAdapter info

INFO: Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory

24-Jun-2009 12:43:46 org.slf4j.impl.JCLLoggerAdapter info

INFO: Using ASTQueryTranslatorFactory

[..]

24-Jun-2009 12:43:46 org.slf4j.impl.JCLLoggerAdapter info

INFO: table found: ncards_jvd.eire_users

24-Jun-2009 12:43:46 org.slf4j.impl.JCLLoggerAdapter info

INFO: columns: [id, username, created, email, active, class, lastname, firstname, modified, pass, location_id]

24-Jun-2009 12:43:46 org.slf4j.impl.JCLLoggerAdapter info

INFO: foreign keys: []

[..]

24-Jun-2009 12:43:46 org.slf4j.impl.JCLLoggerAdapter info

INFO: table found: ncards_jvd.eire_users

24-Jun-2009 12:43:46 org.slf4j.impl.JCLLoggerAdapter info

INFO: columns: [id, username, created, email, active, class, lastname, firstname, modified, pass, location_id]

24-Jun-2009 12:43:46 org.slf4j.impl.JCLLoggerAdapter info

INFO: indexes: [eire_users_fkindex1, primary, users_index4467]

24-Jun-2009 12:43:46 org.slf4j.impl.JCLLoggerAdapter info

INFO: schema update complete

ProviderTracker: Removing service...

ProviderTracker: Removed service eireshop service object: org.hibernate.ejb.HibernatePersistence@14e45b3

 

 

As long it looks pretty good. Let display something in that view:

 

            List<User> users;

            users = new UserHome().getAll();

 

            for (User user2 : users) {

                  System.out.println(user2);

            }

 

 

After start instead of output I get:

org.hibernate.QueryException: ClassNotFoundException: org.hibernate.hql.ast.HqlToken [ from com.yarenty.eireshop.domain.User user ]

            at org.hibernate.hql.ast.HqlLexer.panic(HqlLexer.java:80)

            at antlr.CharScanner.setTokenObjectClass(CharScanner.java:338)

            at org.hibernate.hql.ast.HqlLexer.setTokenObjectClass(HqlLexer.java:54)

 

And reason is – yep, hibernate uses antlr, antlr doesn’t see classes outside its bundle.  Simple solution add DynamicImport-Package:* into antlr Metainf.fm file, better is exactly specify packages that antlr should use, but lets start with simplest solution.

 

And… voile:

 

osgi> Persistence bundle starting...

Persistence bundle started.

Registering persistence provider ;-)

ProviderTracker: New service detected...

ProviderTracker: Added service eireshop

 

[…]

 

ttest3[null] - John Test <test@t.t>, created: Wed Jun 24 11:07:27 BST 2009

ttest3[null] - Jan Novack <test@t.t>, created: Wed Jun 24 11:07:27 BST 2009

jankom2[2] - Janko Muzykant < This e-mail address is being protected from spambots, you need JavaScript enabled to view it >, created: 2008-05-14 00:09:56.0

qwerty[3] - Qwerty Ytrewq < This e-mail address is being protected from spambots, you need JavaScript enabled to view it >, created: 2008-05-23 22:48:17.0

testowy[6] - Testowy Zygmunt < This e-mail address is being protected from spambots, you need JavaScript enabled to view it >, created: 2008-06-11 09:30:40.0

yarenty[7] - Jaroslaw Nowosad < This e-mail address is being protected from spambots, you need JavaScript enabled to view it >, created: 2008-07-05 23:26:55.0

[..]

 

 

 

At end my directory looks like (I changed name to every "hacked" package):

 

com.springsource.com.mysql.jdbc_5.1.6.jar

com.springsource.javassist-3.3.0.ga.jar

com.springsource.javax.activation-1.1.1.jar

com.springsource.javax.ejb-3.0.0.jar

com.springsource.javax.persistence-1.99.0.jar

com.springsource.javax.servlet-2.5.0.jar

com.springsource.javax.transaction-1.1.0.jar

com.springsource.javax.xml.rpc-1.1.0.jar

com.springsource.javax.xml.soap-1.3.0.jar

com.springsource.javax.xml.stream-1.0.1.jar

com.springsource.net.sf.cglib-2.1.3.jar

com.springsource.org.apache.commons.collections-3.2.1.jar

com.springsource.org.apache.commons.logging-1.1.1.jar

com.springsource.org.dom4j-1.6.1.jar

com.springsource.org.hibernate.annotations-3.4.0.GA.jar

com.springsource.org.hibernate.annotations.common-3.3.0.ga.jar

com.springsource.org.hibernate.validator-3.1.0.GA.jar

com.springsource.org.jboss.util-2.0.4.GA.jar

com.springsource.org.jgroups-2.5.1.jar

com.springsource.org.objectweb.asm-1.5.3.jar

com.springsource.org.objectweb.asm.attrs-1.5.3.jar

com.springsource.slf4j.api-1.5.6.jar

com.springsource.slf4j.jcl-1.5.6.jar

 

com.yarenty.antlr-2.7.7.jar

com.yarenty.org.hibernate-3.3.1.GA.jar

com.yarenty.org.hibernate.ejb-3.4.0.GA.jar

 

org.hibernate.ejb-library-3.3.2.GA.libd

 

+ my stuff

+ eclipse RCP stuff

 

 Next part ->don't hack manifest - change hibernate code.

Last Updated ( Thursday, 25 June 2009 13:31 )