# Aufgabe in OSGI/Hibernate/Spring-DM



## ch21 (17. Mrz 2010)

Hallo,

Ich lerne gerade OSGI, Hibernate und Spring-DM.

Dazu habe ich eine Übungsaufgabe, die folgend beschrieben ist::

verwenden Spring-DM und deployen darin "The First Hibernate Application":

http://docs.jboss.org/hibernate/stab...orial-firstapp

Die Anwendung soll neben den Infrastruktur-Komponenten (JTA TransaktionManager und Hibernate SessionFactory) aus 3 weiteren Komponenten bestehen:

1. Das Modell (Klassen mit Mapping-Informationen, als XML oder besser als Annotations)
2. Eine Service-Klasse mit den Methoden zum Speichern, Ändern, Löschen und Suchen von Events
3. Eine Test-Anwendung, die über die Service-Klasse ein paar Events erzeugt, danach sucht, sie ändert und wieder löscht


Datenbank ist MySQL, Ein/Ausgabe ist durch console.

Ich habe schon zwei Wochen versucht, aber leider immer nicht geschafft.

Wer kann mir helfen?


Grüsse

Chen


----------



## KYLT (22. Mrz 2010)

Moin,
wobei hackt es denn genau ? Zeig doch mal die Teile die du bereits geschafft hast


----------



## ch21 (22. Mrz 2010)

Zuerst habe ich zwei Interface CommonDaoService und SessionService aufgebaut.

```
public interface CommonDaoService {
	
	public void save(Object obj) throws Exception;
	public void update(Object obj) throws Exception;
	public void delete(Object obj) throws Exception;
	public void deleteById(Class po, int id) throws Exception;
	public Object getById(Class po,int id) throws Exception;

}
```


```
import org.hibernate.Session;

public interface SessionService {
	public Session get() throws Exception;
	
	public void free() throws Exception; 

}
```

Dann mache ich zwei Komponenten für den beiden Interface.


```
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import osgi.modul.hibernate.service.CommonDaoService;
import osgi.modul.hibernate.service.SessionService;

public class CommonDaoComponent implements CommonDaoService {

	// -----------------------------------------------------------Instance Variables

	private SessionService SessionService;

	// -----------------------------------------------------------Public Method
	
	public void setSessionService(SessionService SessionService) {
		System.out.println("\t");
		System.out.println("运行2\t");
		System.out.println("\t");
		this.SessionService = SessionService;
	}

	public void unsetSessionService(SessionService SessionService) {
		if (this.SessionService != SessionService)
			return;
		this.SessionService = null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see osgi.modul.hibernate.service.CommonDaoService#save(java.lang.Object)
	 */
	public void save(Object obj) throws Exception {
		Session _session = SessionService.get();
		Transaction tx = _session.beginTransaction();
		try {
			_session.save(obj);
			tx.commit();
		} catch (HibernateException e) {
			tx.rollback();
			throw new Exception(e);
		} finally {
			SessionService.free();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see osgi.modul.hibernate.service.CommonDaoService#update(java.lang.Object)
	 */
	public void update(Object obj) throws Exception {
		Session _session = SessionService.get();
		Transaction tx = _session.beginTransaction();
		try {
			_session.update(obj);
			tx.commit();
		} catch (HibernateException e) {
			tx.rollback();
			throw new Exception(e);
		} finally {
			SessionService.free();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see osgi.modul.hibernate.service.CommonDaoService#delete(java.lang.Object)
	 */
	public void delete(Object obj) throws Exception {
		Session _session = SessionService.get();
		Transaction tx = _session.beginTransaction();
		try {
			_session.delete(obj);
			tx.commit();
		} catch (HibernateException e) {
			tx.rollback();
			throw new Exception(e);
		} finally {
			SessionService.free();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see osgi.modul.hibernate.service.CommonDaoService#deleteById(java.lang.Class,
	 *      int)
	 */
	public void deleteById(Class po, int id) throws Exception {
		Object obj = getById(po, id);
		delete(obj);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see osgi.modul.hibernate.service.CommonDaoService#getById(java.lang.Class,
	 *      int)
	 */
	public Object getById(Class po, int id) throws Exception {
		Session _session = SessionService.get();
		Object obj = null;
		try {
			obj = _session.get(po, new Integer(id));
		} finally {
			SessionService.free();
		}
		return obj;
	}

}
```


```
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.IExtensionDelta;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.IRegistryChangeEvent;
import org.eclipse.core.runtime.IRegistryChangeListener;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.log.LogService;

import osgi.modul.hibernate.service.SessionService;

public class SessionComponent implements SessionService,IRegistryChangeListener{

	// -------------------------------------------------------Instance Variables
	
	private static final String DEFAULT_CONFIGFILE="hibernate.cfg.xml";
	
	private static final ThreadLocal _session=new ThreadLocal();
	
	private String _configFile;
	
	private SessionFactory _sf;
	
	private IExtensionRegistry registry;
	
	private List poExtensions=new ArrayList();
	
	private LogService log;

	// -------------------------------------------------------Public Method
	
	public void activate(ComponentContext context){
		_configFile=(String) context.getProperties().get("configFile");
		if((_configFile==null)||("".equals(_configFile))){
			_configFile=DEFAULT_CONFIGFILE;
		}
		IExtension[] extensions=registry.getExtensionPoint("HibernateModul.HibernateExtension").getExtensions();
		for (int i = 0; i < extensions.length; i++) {
			poExtensions.add(extensions[i]);
		}
		initSessionFactory();
	}
	
	public void deactivate(ComponentContext context){
		if(_sf!=null)
			_sf.close();
	}
	
	public void setRegistry(IExtensionRegistry registry){
		registry.addRegistryChangeListener(this,"HibernateModul");
		this.registry=registry;
	}
	
	public void unsetRegistry(IExtensionRegistry registry){
		if(this.registry!=registry){
			return;
		}
		this.registry=null;
	}
	
	public void setLog(LogService log){
		this.log=log;
	}
	
	public void unsetLog(LogService log){
		if(this.log!=log){
			return;
		}
		this.log=null;
	}
	
	/* (non-Javadoc)
	 * @see osgi.modul.hibernate.session.SessionService#free()
	 */
	public void free() throws Exception {
		Session s=(Session) _session.get();
		if(s!=null){
			s.close();
			_session.set(null);
		}
	}

	/* (non-Javadoc)
	 * @see osgi.modul.hibernate.session.SessionService#get()
	 */
	public Session get() throws Exception {
		Session s=(Session) _session.get();
		if(s==null){
			s=_sf.openSession();
			_session.set(s);
		}
		return s;
	}
	
	/*
	 * (non-Javadoc)
	 * @see org.eclipse.core.runtime.IRegistryChangeListener#registryChanged(org.eclipse.core.runtime.IRegistryChangeEvent)
	 */
	public void registryChanged(IRegistryChangeEvent event) {
		IExtensionDelta[] deltas=event.getExtensionDeltas("HibernateModul", "HibernateExtension");
		if(deltas.length==0)
			return;
		for (int i = 0; i < deltas.length; i++) {
			switch (deltas[i].getKind()) {
			case IExtensionDelta.ADDED:
				poExtensions.add(deltas[i].getExtension());
				break;
			case IExtensionDelta.REMOVED:
				poExtensions.remove(deltas[i].getExtension());
				break;
			default:
				break;
			}
		}
		initSessionFactory();
	}
	
	// -------------------------------------------------------Private Method
	
	private void initSessionFactory(){
		Class poClass=null;
		try{
			if(_sf!=null){
				_sf.close();
			}
			Configuration config=(new Configuration()).configure(_configFile);
			for (Iterator iter = poExtensions.iterator(); iter.hasNext();) {
				IExtension extension = (IExtension) iter.next();
				IConfigurationElement[] elements=extension.getConfigurationElements();
				for (int j = 0; j < elements.length; j++) {
					poClass=elements[j].createExecutableExtension("class").getClass();
					config.addClass(poClass);
				}
			}
			_sf=config.buildSessionFactory();
		}
		catch(Throwable t){
			throw new RuntimeException("initialize Hibernate SessionFactory Error："+t);
		}
	}
}
```

Service-Component: OSGi-INF/Sessioncomponent.xml :
[XML]
<?xml version="1.0" encoding="UTF-8"?>
<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0" name="SessionComponent">
   <implementation class="osgi.modul.hibernate.service.impl.SessionComponent"/>
   <service>
      <provide interface="osgi.modul.hibernate.service.SessionService"/>
   </service>
   <reference bind="setRegistry" cardinality="0..1" interface="org.eclipse.core.runtime.IRegistryChangeListener" name="IRegistryChangeListener" policy="dynamic" unbind="unsetRegistry"/>
   <reference bind="setLog" cardinality="0..1" interface="org.osgi.service.log.LogService" name="LogService" policy="dynamic" unbind="unsetLog"/>
</scr:component>

[\XML]

OSGi-INF/CommonDaocomponent.xml
[XML]<?xml version="1.0" encoding="UTF-8"?>
<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0" name="CommonDaoComponent">
   <implementation class="osgi.modul.hibernate.service.impl.CommonDaoComponent"/>
   <reference bind="setSessionService" cardinality="0..1" interface="osgi.modul.hibernate.service.SessionService" name="SessionService" policy="dynamic" unbind="unsetSessionService"/>
   <service>
      <provide interface="osgi.modul.hibernate.service.CommonDaoService"/>
   </service>
</scr:component>
[\XML]


Manifest.in ist wie folgendÖ

Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: HibernateModul
Bundle-SymbolicName: HibernateModul;singleton:=true
Bundle-Version: 1.0.0.qualifier
Bundle-ClassPath: bin/,
 lib/antlr-2.7.6.jar,
 lib/commons-collections-3.1.jar,
 lib/dom4j-1.6.1.jar,
 lib/hibernate3.jar,
 lib/javassist-3.9.0.GA.jar,
 lib/jta-1.1.jar,
 lib/mysql-connector-java-5.1.8-bin.jar,
 lib/slf4j-api-1.5.8.jar
Import-Package: org.eclipse.core.runtime,
 org.osgi.framework;version="1.5.0",
 org.osgi.service.component,
 org.osgi.service.log
Require-Bundle: org.eclipse.equinox.registry;bundle-version="3.4.100",
 org.eclipse.equinox.common;bundle-version="3.5.1"
Export-Package: osgi.modul.hibernate.service
Service-Component: OSGi-INF/Sessioncomponent.xml,OSGi-INF/CommonDaocomponent.xml
DynamicImport-Package: *
Bundle-RequiredExecutionEnvironment: OSGi/Minimum-1.2

HibernateExtension-Schema ist:

[XML]
<?xml version='1.0' encoding='UTF-8'?>
<!-- Schema file written by PDE -->
<schema targetNamespace="HibernateModul" xmlns="http://www.w3.org/2001/XMLSchema">
<annotation>
      <appinfo>
         <meta.schema plugin="HibernateModul" id="HibernateExtension" name="HibernateExtension"/>
      </appinfo>
      <documentation>
         [Enter description of this extension point.]
      </documentation>
   </annotation>

   <element name="extension">
      <complexType>
         <sequence minOccurs="1" maxOccurs="unbounded">
            <element ref="po" minOccurs="1" maxOccurs="unbounded"/>
         </sequence>
         <attribute name="point" type="string" use="required">
            <annotation>
               <documentation>

               </documentation>
            </annotation>
         </attribute>
         <attribute name="id" type="string">
            <annotation>
               <documentation>

               </documentation>
            </annotation>
         </attribute>
         <attribute name="name" type="string">
            <annotation>
               <documentation>

               </documentation>
               <appinfo>
                  <meta.attribute translatable="true"/>
               </appinfo>
            </annotation>
         </attribute>
      </complexType>
   </element>

   <element name="po">
      <complexType>
         <attribute name="class" type="string" use="required">
            <annotation>
               <documentation>

               </documentation>
            </annotation>
         </attribute>
      </complexType>
   </element>

   <annotation>
      <appinfo>
         <meta.section type="since"/>
      </appinfo>
      <documentation>
         [Enter the first release in which this extension point appears.]
      </documentation>
   </annotation>

   <annotation>
      <appinfo>
         <meta.section type="examples"/>
      </appinfo>
      <documentation>
         [Enter extension point usage example here.]
      </documentation>
   </annotation>

   <annotation>
      <appinfo>
         <meta.section type="apiinfo"/>
      </appinfo>
      <documentation>
         [Enter API information here.]
      </documentation>
   </annotation>

   <annotation>
      <appinfo>
         <meta.section type="implementation"/>
      </appinfo>
      <documentation>
         [Enter information about supplied implementation of this extension point.]
      </documentation>
   </annotation>
</schema>
[\XML]

Sonst gibt es ein DatenModul und eine Anwendung. Sie sind nicht wichtig.


----------



## ch21 (22. Mrz 2010)

Fehlermeldung ist wie folgende:

Configuration location:
    file:/D:/Wilken/equinox/.metadata/.plugins/org.eclipse.pde.core/hibernate/
Configuration file:
    file:/D:/Wilken/equinox/.metadata/.plugins/org.eclipse.pde.core/hibernate/config.ini loaded
Install location:
    file:/D:/eclipse/
Framework located:
    file:/D:/eclipse/plugins/org.eclipse.osgi_3.5.2.R35x_v20100126.jar
Framework classpath:
    file:/D:/eclipse/plugins/org.eclipse.osgi_3.5.2.R35x_v20100126.jar
Debug options:
    file:/D:/Wilken/equinox/.metadata/.plugins/org.eclipse.pde.core/hibernate/.options loaded

osgi> Time to load bundles: 47
DEBUG 18 ComponentStorage.parseXMLDeclaration(): loading bundleentry://25.fwk23025815/OSGi-INF/Sessioncomponent.xml
DEBUG 18 ComponentStorage.parseXMLDeclaration(): loading bundleentry://25.fwk23025815/OSGi-INF/CommonDaocomponent.xml
DEBUG 18 WorkThread.run()
DEBUG 18 WorkThread.run(): object to process [QueuedJob] WorkPerformer: org.eclipse.equinox.internal.ds.SCRManager@1f17e77; actionType 1
DEBUG 18 Resolver.enableComponents(): [Component[
	name = SessionComponent
	activate = activate
	deactivate = deactivate
	modified = 
	configuration-policy = optional
	factory = null
	autoenable = true
	immediate = false
	implementation = osgi.modul.hibernate.service.impl.SessionComponent
	properties = null
	serviceFactory = false
	serviceInterface = [osgi.modul.hibernate.service.SessionService]
	references = {
		Reference[name = IRegistryChangeListener, interface = org.eclipse.core.runtime.IRegistryChangeListener, policy = dynamic, cardinality = 1..1, target = null, bind = setRegistry, unbind = unsetRegistry]
		Reference[name = LogService, interface = org.osgi.service.log.LogService, policy = dynamic, cardinality = 0..1, target = null, bind = setLog, unbind = unsetLog]
	}
	located in bundle = HibernateModul_1.0.0.qualifier [25]
], Component[
	name = CommonDaoComponent
	activate = activate
	deactivate = deactivate
	modified = 
	configuration-policy = optional
	factory = null
	autoenable = true
	immediate = false
	implementation = osgi.modul.hibernate.service.impl.CommonDaoComponent
	properties = null
	serviceFactory = false
	serviceInterface = [osgi.modul.hibernate.service.CommonDaoService]
	references = {
		Reference[name = SessionService, interface = osgi.modul.hibernate.service.SessionService, policy = dynamic, cardinality = 0..1, target = null, bind = setSessionService, unbind = unsetSessionService]
	}
	located in bundle = HibernateModul_1.0.0.qualifier [25]
]]
DEBUG 18 Resolver.map(): Creating SCP for component SessionComponent
DEBUG 18 Resolver.map(): Creating SCP for component CommonDaoComponent
DEBUG 18 Resolver.resolveEligible(): reference 'IRegistryChangeListener' of component 'SessionComponent' is not resolved
DEBUG 18 Resolver:resolveEligible(): resolved components = [CommonDaoComponent]
DEBUG 18 Resolver.getEligible(): processing service event org.osgi.framework.ServiceEvent[source={osgi.modul.hibernate.service.CommonDaoService}={component.name=CommonDaoComponent, component.id=1, service.id=45}]
DEBUG 18 Service event type: REGISTERED
DEBUG 18 Resolver.resolveEligible(): reference 'IRegistryChangeListener' of component 'SessionComponent' is not resolved
DEBUG 18 Resolver:resolveEligible(): resolved components = [CommonDaoComponent]
DEBUG 18 InstanceProcess.registerService(): CommonDaoComponent registered as *service*
DEBUG 18 WorkThread.run()
DEBUG 18 ComponentStorage.parseXMLDeclaration(): loading bundleentry://27.fwk23025815/OSGI-INF/Anwendung.xml
DEBUG 18 WorkThread.run(): object to process [QueuedJob] WorkPerformer: org.eclipse.equinox.internal.ds.SCRManager@1f17e77; actionType 1
DEBUG 18 Resolver.enableComponents(): [Component[
	name = Anwendung
	activate = activate
	deactivate = deactivate
	modified = 
	configuration-policy = optional
	factory = null
	autoenable = true
	immediate = false
	implementation = osgi.modul.anwendung.Anwendung
	properties = null
	serviceFactory = false
	serviceInterface = [org.eclipse.osgi.framework.console.CommandProvider]
	references = {
		Reference[name = CommonDaoService, interface = osgi.modul.hibernate.service.CommonDaoService, policy = dynamic, cardinality = 0..1, target = null, bind = setCommonDaoService, unbind = unsetCommonDaoService]
	}
	located in bundle = Anwendung_1.0.0.qualifier [27]
]]
DEBUG 18 Resolver.map(): Creating SCP for component Anwendung
DEBUG 18 Resolver.resolveEligible(): reference 'IRegistryChangeListener' of component 'SessionComponent' is not resolved
DEBUG 18 Resolver:resolveEligible(): resolved components = [CommonDaoComponent, Anwendung]
DEBUG 18 Resolver.getEligible(): processing service event org.osgi.framework.ServiceEvent[source={org.eclipse.osgi.framework.console.CommandProvider}={component.name=Anwendung, component.id=2, service.id=46}]
DEBUG 18 Service event type: REGISTERED
DEBUG 18 Resolver.resolveEligible(): reference 'IRegistryChangeListener' of component 'SessionComponent' is not resolved
DEBUG 18 Resolver:resolveEligible(): resolved components = [CommonDaoComponent, Anwendung]
DEBUG 18 InstanceProcess.buildComponent(): building component Anwendung
DEBUG 18 ServiceComponentProp.bindReference(): component Anwendung -> Reference[name = CommonDaoService, interface = osgi.modul.hibernate.service.CommonDaoService, policy = dynamic, cardinality = 0..1, target = null, bind = setCommonDaoService, unbind = unsetCommonDaoService]
DEBUG 18 InstanceProcess.buildComponent(): building component CommonDaoComponent
DEBUG 18 ServiceComponentProp.bindReference(): component CommonDaoComponent -> Reference[name = SessionService, interface = osgi.modul.hibernate.service.SessionService, policy = dynamic, cardinality = 0..1, target = null, bind = setSessionService, unbind = unsetSessionService]
DEBUG 18 ServiceComponentProp.bindReference(): The service is not yet registered, but it is already instantiated
DEBUG 18 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ServiceComponentProp.activate(): name: CommonDaoComponent
DEBUG 18 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ServiceComponentProp.activate(): using bundle: Anwendung
DEBUG 18 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ServiceComponentProp.activate(): instance: org.eclipse.equinox.internal.ds.impl.ComponentInstanceImpl@84da23
DEBUG 18 ServiceComponent.getMethod(): activate
DEBUG 18 ServiceReg.getService(): service 'CommonDaoComponent' is used 1 time(s), object = osgi.modul.hibernate.service.impl.CommonDaoComponent@13c468a

DEBUG 18 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ServiceComponentProp.activate(): name: Anwendung
DEBUG 18 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ServiceComponentProp.activate(): using bundle: org.eclipse.osgi
DEBUG 18 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ServiceComponentProp.activate(): instance: org.eclipse.equinox.internal.ds.impl.ComponentInstanceImpl@ee22f7
DEBUG 18 ServiceComponent.getMethod(): activate
DEBUG 18 ServiceReg.getService(): service 'Anwendung' is used 1 time(s), object = osgi.modul.anwendung.Anwendung@39ab89
DEBUG 18 InstanceProcess.registerService(): Anwendung registered as *service*
DEBUG 18 WorkThread.run()


----------



## Noctarius (22. Mrz 2010)

Ohne jetzt den ganzen Plott gelesen zu haben:
Hibernate und OSGi ist immer schwierig, da Hibernate mit Proxies arbeitet.


----------

