package org.apache.ode.dao.jpa.ojpa;


import java.util.List;
import java.util.Properties;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import org.apache.ode.bpel.dao.BpelDAOConnection;
import org.apache.ode.bpel.dao.BpelDAOConnectionFactory;
import org.apache.ode.dao.jpa.BPELDAOConnectionImpl;

public class BPELDAOConnectionFactoryImpl implements BpelDAOConnectionFactory {

	private EntityManager em;
	
	public BPELDAOConnectionFactoryImpl(EntityManager em) {
		this.em = em;
	}
	
	public BpelDAOConnection getConnection() {
		
		List<BpelDAOConnection> conns = null;
		
		Query q = em.createQuery("SELECT x FROM BPELDAOConnectionImpl x order by x._id asc");
		
		try {
			conns = (List<BpelDAOConnection>)q.getResultList();
		} catch (NoResultException e) {
			return new BPELDAOConnectionImpl(new Long(1));
		}
		
		if ( conns.size() < 1 ) {
			return new BPELDAOConnectionImpl(new Long(1));
		}
		
		return conns.get(conns.size()-1);
	}
	
	public BpelDAOConnection getConnection(Long connID) {
		BpelDAOConnection conn = null;
		
		Query q = em.createQuery("SELECT x FROM BPELDAOConnectionImpl x WHERE x._id = ?1");
		q.setParameter(1, connID);
		
		try {
			conn = (BpelDAOConnection)q.getSingleResult();
		} catch (NoResultException e){}
		
		if ( conn == null ) {
			conn = new BPELDAOConnectionImpl(connID);
		}
		
		return conn;
	}
	
	public Long getConnectionId(BpelDAOConnection conn) {
		BPELDAOConnectionImpl oConn = (BPELDAOConnectionImpl)conn;
		return oConn.getID();
	}

	public void init(Properties properties) {
	}

}

@@ -821,24 +821,29 @@
 ultList();%0D%0A
+%09%09%09%0D%0A
 %09%09%7D catch (N
@@ -904,32 +904,35 @@
 Impl(new Long(1)
+,em
 );%0D%0A%09%09%7D%0D%0A%09%09%0D%0A%09%09i
@@ -1004,16 +1004,19 @@
  Long(1)
+,em
 );%0D%0A%09%09%7D%0D
@@ -1026,40 +1026,134 @@
 %0D%0A%09%09
-return conns.get(conns.size()-1)
+BPELDAOConnectionImpl conn = (BPELDAOConnectionImpl)conns.get(conns.size()-1);%0D%0A%09%09conn.setEntityManger(em);%0D%0A%09%09%0D%0A%09%09return conn
 ;%0D%0A%09
@@ -1217,19 +1217,19 @@
 ) %7B%0D%0A%09%09B
-pel
+PEL
 DAOConne
@@ -1229,24 +1229,28 @@
 AOConnection
+Impl
  conn = null
@@ -1398,19 +1398,19 @@
 onn = (B
-pel
+PEL
 DAOConne
@@ -1414,16 +1414,20 @@
 nnection
+Impl
 )q.getSi
@@ -1441,16 +1441,46 @@
 ult();%0D%0A
+%09%09%09conn.setEntityManger(em);%0D%0A
 %09%09%7D catc
@@ -1573,24 +1573,27 @@
 nImpl(connID
+,em
 );%0D%0A%09%09%7D%0D%0A%09%09%0D

add support for delete