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.

 

 




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